diff --git a/.github/workflows/maven-verify.yml b/.github/workflows/maven-verify.yml index 9683e3bb27..5008055108 100644 --- a/.github/workflows/maven-verify.yml +++ b/.github/workflows/maven-verify.yml @@ -31,7 +31,7 @@ jobs: ff-goal: 'clean install site site:stage -P reporting -nsu' ff-site-goal: '-v' verify-goal: 'clean install -nsu -P run-its' - verify-fail-fast: false + verify-fail-fast: true failure-upload-path: | surefire-its/target/*/log.txt surefire-its/target/**/surefire-reports/* diff --git a/maven-failsafe-plugin/pom.xml b/maven-failsafe-plugin/pom.xml index ed8758f5eb..cdca61c2a6 100644 --- a/maven-failsafe-plugin/pom.xml +++ b/maven-failsafe-plugin/pom.xml @@ -17,281 +17,281 @@ ~ specific language governing permissions and limitations ~ under the License. --> - - 4.0.0 + 4.0.0 + + + org.apache.maven.surefire + surefire + 3.0.0-M10-SNAPSHOT + - - org.apache.maven.surefire - surefire - 3.0.0-M10-SNAPSHOT - + org.apache.maven.plugins + maven-failsafe-plugin + maven-plugin - org.apache.maven.plugins - maven-failsafe-plugin - maven-plugin + Maven Failsafe Plugin + Maven Failsafe MOJO in maven-failsafe-plugin. - Maven Failsafe Plugin - Maven Failsafe MOJO in maven-failsafe-plugin. + + ${mavenVersion} + - - ${mavenVersion} - + + Failsafe + Surefire + 8184 + 8185 + - - Failsafe - Surefire - 8184 - 8185 - + + + org.apache.maven.surefire + maven-surefire-common + ${project.version} + + + org.apache.maven.plugins + maven-surefire-plugin + ${project.version} + site-source + zip + provided + + + org.apache.maven + maven-plugin-api + provided + + + org.apache.maven + maven-core + provided + + + org.apache.maven.plugin-tools + maven-plugin-annotations + provided + + + org.mockito + mockito-core + test + + - - + + + + org.apache.maven.plugins + maven-plugin-plugin + + + org.jacoco + jacoco-maven-plugin + + jacoco.agent + + + + jacoco-agent + + prepare-agent + + + + + + maven-surefire-plugin + + ${jvm.args.tests} ${jacoco.agent} + + **/JUnit4SuiteTest.java + + + + org.apache.maven.surefire - maven-surefire-common - ${project.version} - - - org.apache.maven.plugins - maven-surefire-plugin - ${project.version} - provided - zip - site-source - - - org.apache.maven - maven-plugin-api - provided - - - org.apache.maven - maven-core - provided - - - org.apache.maven.plugin-tools - maven-plugin-annotations - provided - - - org.mockito - mockito-core - test - - + surefire-shadefire + 3.0.0-M7 + + + + + + maven-dependency-plugin + + + site-site + + unpack-dependencies + + pre-site + + maven-surefire-plugin + provided + zip + site-source + ${project.build.directory}/source-site + true + + + + + + maven-resources-plugin + + + copy-resources + + copy-resources + + pre-site + + ${basedir}/../target/source-site + + + ${basedir}/../src/site + false + + + + + + + + org.apache.maven.plugins + maven-antrun-plugin + + + generate-test-report + + run + + pre-site + + + + + + + + + + + org.apache.maven.plugins + maven-site-plugin + + ${project.build.directory}/source-site + + + + - + + + + org.apache.maven.plugins + maven-plugin-plugin + + + + + + + ci + + + enableCiProfile + true + + + - - org.apache.maven.plugins - maven-plugin-plugin - - - org.jacoco - jacoco-maven-plugin - - - jacoco-agent - - prepare-agent - - - - - jacoco.agent - - - - maven-surefire-plugin - - - org.apache.maven.surefire - surefire-shadefire - 3.0.0-M7 - - + + maven-docck-plugin + 1.1 + + + + check + + + + + + + + + run-its + + verify + + + org.apache.maven.plugins + maven-invoker-plugin + + + pre-its + + install + + pre-integration-test - ${jvm.args.tests} ${jacoco.agent} - - **/JUnit4SuiteTest.java - + ${skipTests} - - - maven-dependency-plugin - - - site-site - pre-site - - unpack-dependencies - - - maven-surefire-plugin - provided - zip - site-source - ${project.build.directory}/source-site - true - - - - - - maven-resources-plugin - - - copy-resources - pre-site - - copy-resources - - - ${basedir}/../target/source-site - - - ${basedir}/../src/site - false - - - - - - - - org.apache.maven.plugins - maven-antrun-plugin - - - generate-test-report - pre-site - - run - - - - - - - - - - - - org.apache.maven.plugins - maven-site-plugin + + + integration-test + + run + - ${project.build.directory}/source-site + src/it + ${project.build.directory}/it + + verify + -nsu + + + */pom.xml + + verify + src/it/settings.xml + ${skipTests} + true + + ${failsafe-integration-test-port} + ${failsafe-integration-test-stop-port} + + true - + + + - - - + + + + reporting + - - org.apache.maven.plugins - maven-plugin-plugin - + + org.apache.maven.plugins + maven-changes-plugin + + false + + + + + jira-report + + + + - - - - - ci - - - enableCiProfile - true - - - - - - maven-docck-plugin - 1.1 - - - - check - - - - - - - - - run-its - - verify - - - org.apache.maven.plugins - maven-invoker-plugin - - - pre-its - pre-integration-test - - install - - - ${skipTests} - - - - integration-test - - run - - - src/it - ${project.build.directory}/it - - verify - -nsu - - - */pom.xml - - verify - src/it/settings.xml - ${skipTests} - true - - ${failsafe-integration-test-port} - ${failsafe-integration-test-stop-port} - - true - - - - - - - - - reporting - - - - org.apache.maven.plugins - maven-changes-plugin - - false - - - - - jira-report - - - - - - - - + + + diff --git a/maven-failsafe-plugin/src/it/jetty-war-test-failing/src/test/java/basic/BasicIT.java b/maven-failsafe-plugin/src/it/jetty-war-test-failing/src/test/java/basic/BasicIT.java index c271570157..b7891e1c93 100644 --- a/maven-failsafe-plugin/src/it/jetty-war-test-failing/src/test/java/basic/BasicIT.java +++ b/maven-failsafe-plugin/src/it/jetty-war-test-failing/src/test/java/basic/BasicIT.java @@ -1,5 +1,3 @@ -package basic; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -19,6 +17,8 @@ * under the License. */ +package basic; + import java.io.IOException; import java.util.Properties; diff --git a/maven-failsafe-plugin/src/it/jetty-war-test-passing/src/test/java/basic/BasicIT.java b/maven-failsafe-plugin/src/it/jetty-war-test-passing/src/test/java/basic/BasicIT.java index ab903640e8..1c8b4ccbe8 100644 --- a/maven-failsafe-plugin/src/it/jetty-war-test-passing/src/test/java/basic/BasicIT.java +++ b/maven-failsafe-plugin/src/it/jetty-war-test-passing/src/test/java/basic/BasicIT.java @@ -1,5 +1,3 @@ -package basic; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package basic; import java.io.IOException; import java.util.Properties; diff --git a/maven-failsafe-plugin/src/main/java/org/apache/maven/plugin/failsafe/IntegrationTestMojo.java b/maven-failsafe-plugin/src/main/java/org/apache/maven/plugin/failsafe/IntegrationTestMojo.java index b673b96b56..1d3d54da4e 100644 --- a/maven-failsafe-plugin/src/main/java/org/apache/maven/plugin/failsafe/IntegrationTestMojo.java +++ b/maven-failsafe-plugin/src/main/java/org/apache/maven/plugin/failsafe/IntegrationTestMojo.java @@ -1,3 +1,21 @@ +/* + * 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.maven.plugin.failsafe; /* @@ -19,6 +37,12 @@ * under the License. */ +import java.io.File; +import java.io.IOException; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugin.surefire.AbstractSurefireMojo; @@ -27,14 +51,8 @@ import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.plugins.annotations.ResolutionScope; -import org.apache.maven.surefire.extensions.ForkNodeFactory; import org.apache.maven.surefire.api.suite.RunResult; - -import java.io.File; -import java.io.IOException; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; +import org.apache.maven.surefire.extensions.ForkNodeFactory; import static org.apache.maven.plugin.failsafe.util.FailsafeSummaryXmlUtils.writeSummary; @@ -44,11 +62,13 @@ * @author Jason van Zyl * @author Stephen Connolly */ -@Mojo( name = "integration-test", requiresProject = true, requiresDependencyResolution = ResolutionScope.TEST, - defaultPhase = LifecyclePhase.INTEGRATION_TEST, threadSafe = true ) -public class IntegrationTestMojo - extends AbstractSurefireMojo -{ +@Mojo( + name = "integration-test", + requiresProject = true, + requiresDependencyResolution = ResolutionScope.TEST, + defaultPhase = LifecyclePhase.INTEGRATION_TEST, + threadSafe = true) +public class IntegrationTestMojo extends AbstractSurefireMojo { private static final String FAILSAFE_IN_PROGRESS_CONTEXT_KEY = "failsafe-in-progress"; @@ -60,7 +80,7 @@ public class IntegrationTestMojo @Parameter private File classesDirectory; - @Parameter( defaultValue = "${project.build.outputDirectory}", readonly = true, required = true ) + @Parameter(defaultValue = "${project.build.outputDirectory}", readonly = true, required = true) private File defaultClassesDirectory; /** @@ -69,16 +89,16 @@ public class IntegrationTestMojo * * @since 2.4.3-alpha-2 */ - @Parameter( property = "skipITs" ) + @Parameter(property = "skipITs") private boolean skipITs; /** * Base directory where all reports are written to. */ - @Parameter( defaultValue = "${project.build.directory}/failsafe-reports" ) + @Parameter(defaultValue = "${project.build.directory}/failsafe-reports") private File reportsDirectory; - @SuppressWarnings( "checkstyle:linelength" ) + @SuppressWarnings("checkstyle:linelength") /** * Specify this parameter to run individual tests by file name, overriding parameter {@code includes} and * {@code excludes}. Each pattern you specify here will be used to create an include pattern formatted like @@ -101,32 +121,32 @@ public class IntegrationTestMojo * method pattern would become: {@code #testMethod[*]}. If using @Parameters(name="{index}: fib({0})={1}") * and selecting the index e.g. 5 in pattern, the non-regex method pattern would become {@code #testMethod[5:*]}. */ - @Parameter( property = "it.test" ) + @Parameter(property = "it.test") private String test; /** * The summary file to write integration test results to. */ - @Parameter( defaultValue = "${project.build.directory}/failsafe-reports/failsafe-summary.xml", required = true ) + @Parameter(defaultValue = "${project.build.directory}/failsafe-reports/failsafe-summary.xml", required = true) private File summaryFile; /** * Option to print summary of test suites or just print the test cases that have errors. */ - @Parameter( property = "failsafe.printSummary", defaultValue = "true" ) + @Parameter(property = "failsafe.printSummary", defaultValue = "true") private boolean printSummary; /** * Selects the formatting for the test report to be generated. Can be set as "brief" or "plain". * Only applies to the output format of the output files (target/surefire-reports/testName.txt) */ - @Parameter( property = "failsafe.reportFormat", defaultValue = "brief" ) + @Parameter(property = "failsafe.reportFormat", defaultValue = "brief") private String reportFormat; /** * Option to generate a file test report or just output the test report to the console. */ - @Parameter( property = "failsafe.useFile", defaultValue = "true" ) + @Parameter(property = "failsafe.useFile", defaultValue = "true") private boolean useFile; /** @@ -137,7 +157,7 @@ public class IntegrationTestMojo * @deprecated Since 3.0.0-M8, use "failsafe.failIfNoSpecifiedTests" instead. */ @Deprecated - @Parameter( property = "it.failIfNoSpecifiedTests", defaultValue = "true" ) + @Parameter(property = "it.failIfNoSpecifiedTests", defaultValue = "true") private boolean failIfNoSpecifiedTestsDeprecated; /** @@ -147,7 +167,7 @@ public class IntegrationTestMojo * * @since 3.0.0-M8 */ - @Parameter( property = "failsafe.failIfNoSpecifiedTests", defaultValue = "true" ) + @Parameter(property = "failsafe.failIfNoSpecifiedTests", defaultValue = "true") private boolean failIfNoSpecifiedTests; /** @@ -158,7 +178,7 @@ public class IntegrationTestMojo * * @since 2.4 */ - @Parameter( property = "maven.failsafe.debug" ) + @Parameter(property = "maven.failsafe.debug") private String debugForkedProcess; /** @@ -167,7 +187,7 @@ public class IntegrationTestMojo * * @since 2.4 */ - @Parameter( property = "failsafe.timeout" ) + @Parameter(property = "failsafe.timeout") private int forkedProcessTimeoutInSeconds; /** @@ -179,7 +199,7 @@ public class IntegrationTestMojo * * @since 2.20 */ - @Parameter( property = "failsafe.exitTimeout", defaultValue = "30" ) + @Parameter(property = "failsafe.exitTimeout", defaultValue = "30") private int forkedProcessExitTimeoutInSeconds; /** @@ -192,7 +212,7 @@ public class IntegrationTestMojo * * @since 2.16 */ - @Parameter( property = "failsafe.parallel.timeout" ) + @Parameter(property = "failsafe.parallel.timeout") private double parallelTestsTimeoutInSeconds; /** @@ -206,10 +226,10 @@ public class IntegrationTestMojo * * @since 2.16 */ - @Parameter( property = "failsafe.parallel.forcedTimeout" ) + @Parameter(property = "failsafe.parallel.forcedTimeout") private double parallelTestsTimeoutForcedInSeconds; - @SuppressWarnings( "checkstyle:linelength" ) + @SuppressWarnings("checkstyle:linelength") /** * A list of {@literal } elements specifying the test filter (by pattern) of tests which should be * included in testing. If it is not specified and the {@code test} parameter is unspecified as well, the default @@ -237,7 +257,7 @@ public class IntegrationTestMojo * to the POM property ${project.build.testOutputDirectory}, typically * {@literal src/test/java} unless overridden. */ - @Parameter( property = "failsafe.includes" ) + @Parameter(property = "failsafe.includes") // TODO use regex for fully qualified class names in 3.0 and change the filtering abilities private List includes; @@ -265,7 +285,7 @@ public class IntegrationTestMojo * to the POM property ${project.build.testOutputDirectory}, typically * {@literal src/test/java} unless overridden. */ - @Parameter( property = "failsafe.excludes" ) + @Parameter(property = "failsafe.excludes") // TODO use regex for fully qualified class names in 3.0 and change the filtering abilities private List excludes; @@ -276,7 +296,7 @@ public class IntegrationTestMojo * * @since 2.3 */ - @Parameter( property = "failsafe.useSystemClassLoader", defaultValue = "true" ) + @Parameter(property = "failsafe.useSystemClassLoader", defaultValue = "true") private boolean useSystemClassLoader; /** @@ -290,7 +310,7 @@ public class IntegrationTestMojo * * @since 2.4.3 */ - @Parameter( property = "failsafe.useManifestOnlyJar", defaultValue = "true" ) + @Parameter(property = "failsafe.useManifestOnlyJar", defaultValue = "true") private boolean useManifestOnlyJar; /** @@ -300,7 +320,7 @@ public class IntegrationTestMojo * * @since 3.0.0-M1 */ - @Parameter( property = "encoding", defaultValue = "${project.reporting.outputEncoding}" ) + @Parameter(property = "encoding", defaultValue = "${project.reporting.outputEncoding}") private String encoding; /** @@ -309,7 +329,7 @@ public class IntegrationTestMojo * they fail. If a failing test passes in any of those reruns, it will be marked as pass and reported as a "flake". * However, all the failing attempts will be recorded. */ - @Parameter( property = "failsafe.rerunFailingTestsCount", defaultValue = "0" ) + @Parameter(property = "failsafe.rerunFailingTestsCount", defaultValue = "0") private int rerunFailingTestsCount; /** @@ -321,7 +341,7 @@ public class IntegrationTestMojo * * @since 2.2 */ - @Parameter( property = "failsafe.suiteXmlFiles" ) + @Parameter(property = "failsafe.suiteXmlFiles") private File[] suiteXmlFiles; /** @@ -348,7 +368,7 @@ public class IntegrationTestMojo * * @since 2.7 */ - @Parameter( property = "failsafe.runOrder", defaultValue = "filesystem" ) + @Parameter(property = "failsafe.runOrder", defaultValue = "filesystem") private String runOrder; /** @@ -364,7 +384,7 @@ public class IntegrationTestMojo * * @since 3.0.0-M6 */ - @Parameter( property = "failsafe.runOrder.random.seed" ) + @Parameter(property = "failsafe.runOrder.random.seed") private Long runOrderRandomSeed; /** @@ -384,7 +404,7 @@ public class IntegrationTestMojo * * @since 2.13 */ - @Parameter( property = "failsafe.includesFile" ) + @Parameter(property = "failsafe.includesFile") private File includesFile; /** @@ -404,7 +424,7 @@ public class IntegrationTestMojo * * @since 2.13 */ - @Parameter( property = "failsafe.excludesFile" ) + @Parameter(property = "failsafe.excludesFile") private File excludesFile; /** @@ -418,7 +438,7 @@ public class IntegrationTestMojo * * @since 2.19 */ - @Parameter( property = "failsafe.skipAfterFailureCount", defaultValue = "0" ) + @Parameter(property = "failsafe.skipAfterFailureCount", defaultValue = "0") private int skipAfterFailureCount; /** @@ -438,7 +458,7 @@ public class IntegrationTestMojo * * @since 2.19 */ - @Parameter( property = "failsafe.shutdown", defaultValue = "exit" ) + @Parameter(property = "failsafe.shutdown", defaultValue = "exit") private String shutdown; /** @@ -449,7 +469,7 @@ public class IntegrationTestMojo * * @since 3.0.0-M2 */ - @Parameter( property = "failsafe.useModulePath", defaultValue = "true" ) + @Parameter(property = "failsafe.useModulePath", defaultValue = "true") private boolean useModulePath; /** @@ -464,7 +484,7 @@ public class IntegrationTestMojo * * @since 3.0.0-M5 */ - @Parameter( property = "failsafe.forkNode" ) + @Parameter(property = "failsafe.forkNode") private ForkNodeFactory forkNode; /** @@ -480,7 +500,7 @@ public class IntegrationTestMojo * * @since 3.0.0-M4 */ - @Parameter( property = "failsafe.excludedEnvironmentVariables" ) + @Parameter(property = "failsafe.excludedEnvironmentVariables") private String[] excludedEnvironmentVariables; /** @@ -521,10 +541,10 @@ public class IntegrationTestMojo * * @since 3.0.0-M4 */ - @Parameter( property = "failsafe.enableProcessChecker" ) + @Parameter(property = "failsafe.enableProcessChecker") private String enableProcessChecker; - @Parameter( property = "failsafe.systemPropertiesFile" ) + @Parameter(property = "failsafe.systemPropertiesFile") private File systemPropertiesFile; /** @@ -532,7 +552,7 @@ public class IntegrationTestMojo * * @since 3.0.0-M6 */ - @Parameter( property = "failsafe.includeJUnit5Engines" ) + @Parameter(property = "failsafe.includeJUnit5Engines") private String[] includeJUnit5Engines; /** @@ -540,152 +560,127 @@ public class IntegrationTestMojo * * @since 3.0.0-M6 */ - @Parameter( property = "failsafe.excludeJUnit5Engines" ) + @Parameter(property = "failsafe.excludeJUnit5Engines") private String[] excludeJUnit5Engines; @Override - protected int getRerunFailingTestsCount() - { + protected int getRerunFailingTestsCount() { return rerunFailingTestsCount; } @Override - @SuppressWarnings( "unchecked" ) - protected void handleSummary( RunResult summary, Exception firstForkException ) - throws MojoExecutionException, MojoFailureException - { + @SuppressWarnings("unchecked") + protected void handleSummary(RunResult summary, Exception firstForkException) + throws MojoExecutionException, MojoFailureException { File summaryFile = getSummaryFile(); - if ( !summaryFile.getParentFile().isDirectory() ) - { + if (!summaryFile.getParentFile().isDirectory()) { //noinspection ResultOfMethodCallIgnored summaryFile.getParentFile().mkdirs(); } - try - { - Object token = getPluginContext().get( FAILSAFE_IN_PROGRESS_CONTEXT_KEY ); - writeSummary( summary, summaryFile, token != null ); - } - catch ( Exception e ) - { - throw new MojoExecutionException( e.getMessage(), e ); + try { + Object token = getPluginContext().get(FAILSAFE_IN_PROGRESS_CONTEXT_KEY); + writeSummary(summary, summaryFile, token != null); + } catch (Exception e) { + throw new MojoExecutionException(e.getMessage(), e); } - getPluginContext().put( FAILSAFE_IN_PROGRESS_CONTEXT_KEY, FAILSAFE_IN_PROGRESS_CONTEXT_KEY ); + getPluginContext().put(FAILSAFE_IN_PROGRESS_CONTEXT_KEY, FAILSAFE_IN_PROGRESS_CONTEXT_KEY); } - private boolean isJarArtifact( File artifactFile ) - { - return artifactFile != null && artifactFile.isFile() && artifactFile.getName().toLowerCase().endsWith( ".jar" ); + private boolean isJarArtifact(File artifactFile) { + return artifactFile != null + && artifactFile.isFile() + && artifactFile.getName().toLowerCase().endsWith(".jar"); } - private static File toAbsoluteCanonical( File f ) - { - try - { + private static File toAbsoluteCanonical(File f) { + try { return f == null ? null : f.getAbsoluteFile().getCanonicalFile(); - } - catch ( IOException e ) - { - throw new IllegalStateException( e.getLocalizedMessage(), e ); + } catch (IOException e) { + throw new IllegalStateException(e.getLocalizedMessage(), e); } } @Override - @SuppressWarnings( "deprecation" ) - protected boolean isSkipExecution() - { + @SuppressWarnings("deprecation") + protected boolean isSkipExecution() { return isSkip() || isSkipTests() || isSkipITs() || isSkipExec(); } @Override - protected String getPluginName() - { + protected String getPluginName() { return "failsafe"; } @Override - protected String[] getDefaultIncludes() - { - return new String[]{ "**/IT*.java", "**/*IT.java", "**/*ITCase.java" }; + protected String[] getDefaultIncludes() { + return new String[] {"**/IT*.java", "**/*IT.java", "**/*ITCase.java"}; } @Override - protected String getReportSchemaLocation() - { + protected String getReportSchemaLocation() { return "https://maven.apache.org/surefire/maven-failsafe-plugin/xsd/failsafe-test-report-3.0.xsd"; } @Override - public boolean isSkipTests() - { + public boolean isSkipTests() { return skipTests; } @Override @Deprecated - public void setSkipTests( boolean skipTests ) - { + public void setSkipTests(boolean skipTests) { this.skipTests = skipTests; } - public boolean isSkipITs() - { + public boolean isSkipITs() { return skipITs; } - public void setSkipITs( boolean skipITs ) - { + public void setSkipITs(boolean skipITs) { this.skipITs = skipITs; } @Override @Deprecated - public boolean isSkipExec() - { + public boolean isSkipExec() { return skipExec; } @Override @Deprecated - public void setSkipExec( boolean skipExec ) - { + public void setSkipExec(boolean skipExec) { this.skipExec = skipExec; } @Override - public boolean isSkip() - { + public boolean isSkip() { return skip; } @Override - public void setSkip( boolean skip ) - { + public void setSkip(boolean skip) { this.skip = skip; } @Override - public File getBasedir() - { + public File getBasedir() { return basedir; } @Override - public void setBasedir( File basedir ) - { + public void setBasedir(File basedir) { this.basedir = basedir; } @Override - public File getTestClassesDirectory() - { + public File getTestClassesDirectory() { return testClassesDirectory; } @Override - public void setTestClassesDirectory( File testClassesDirectory ) - { + public void setTestClassesDirectory(File testClassesDirectory) { this.testClassesDirectory = testClassesDirectory; } @@ -695,392 +690,328 @@ public void setTestClassesDirectory( File testClassesDirectory ) * used instead. See the resolution of {@link #getClassLoaderConfiguration() ClassLoaderConfiguration}. */ @Override - public File getMainBuildPath() - { + public File getMainBuildPath() { File artifact = getProject().getArtifact().getFile(); boolean isDefaultClsDir = classesDirectory == null; - return isDefaultClsDir ? ( isJarArtifact( artifact ) ? artifact : defaultClassesDirectory ) : classesDirectory; + return isDefaultClsDir ? (isJarArtifact(artifact) ? artifact : defaultClassesDirectory) : classesDirectory; } @Override - public void setMainBuildPath( File mainBuildPath ) - { - classesDirectory = toAbsoluteCanonical( mainBuildPath ); + public void setMainBuildPath(File mainBuildPath) { + classesDirectory = toAbsoluteCanonical(mainBuildPath); } - public void setDefaultClassesDirectory( File defaultClassesDirectory ) - { - this.defaultClassesDirectory = toAbsoluteCanonical( defaultClassesDirectory ); + public void setDefaultClassesDirectory(File defaultClassesDirectory) { + this.defaultClassesDirectory = toAbsoluteCanonical(defaultClassesDirectory); } @Override - public File getReportsDirectory() - { + public File getReportsDirectory() { return reportsDirectory; } @Override - public void setReportsDirectory( File reportsDirectory ) - { + public void setReportsDirectory(File reportsDirectory) { this.reportsDirectory = reportsDirectory; } @Override - public String getTest() - { + public String getTest() { return test; } @Override - public void setTest( String test ) - { + public void setTest(String test) { this.test = test; } - public File getSummaryFile() - { + public File getSummaryFile() { return summaryFile; } - public void setSummaryFile( File summaryFile ) - { + public void setSummaryFile(File summaryFile) { this.summaryFile = summaryFile; } @Override - public boolean isPrintSummary() - { + public boolean isPrintSummary() { return printSummary; } @Override - public void setPrintSummary( boolean printSummary ) - { + public void setPrintSummary(boolean printSummary) { this.printSummary = printSummary; } @Override - public String getReportFormat() - { + public String getReportFormat() { return reportFormat; } @Override - public void setReportFormat( String reportFormat ) - { + public void setReportFormat(String reportFormat) { this.reportFormat = reportFormat; } @Override - public boolean isUseFile() - { + public boolean isUseFile() { return useFile; } @Override - public void setUseFile( boolean useFile ) - { + public void setUseFile(boolean useFile) { this.useFile = useFile; } @Override - public String getDebugForkedProcess() - { + public String getDebugForkedProcess() { return debugForkedProcess; } @Override - public void setDebugForkedProcess( String debugForkedProcess ) - { + public void setDebugForkedProcess(String debugForkedProcess) { this.debugForkedProcess = debugForkedProcess; } @Override - public int getForkedProcessTimeoutInSeconds() - { + public int getForkedProcessTimeoutInSeconds() { return forkedProcessTimeoutInSeconds; } @Override - public void setForkedProcessTimeoutInSeconds( int forkedProcessTimeoutInSeconds ) - { + public void setForkedProcessTimeoutInSeconds(int forkedProcessTimeoutInSeconds) { this.forkedProcessTimeoutInSeconds = forkedProcessTimeoutInSeconds; } @Override - public int getForkedProcessExitTimeoutInSeconds() - { + public int getForkedProcessExitTimeoutInSeconds() { return forkedProcessExitTimeoutInSeconds; } @Override - public void setForkedProcessExitTimeoutInSeconds( int forkedProcessExitTimeoutInSeconds ) - { + public void setForkedProcessExitTimeoutInSeconds(int forkedProcessExitTimeoutInSeconds) { this.forkedProcessExitTimeoutInSeconds = forkedProcessExitTimeoutInSeconds; } @Override - public double getParallelTestsTimeoutInSeconds() - { + public double getParallelTestsTimeoutInSeconds() { return parallelTestsTimeoutInSeconds; } @Override - public void setParallelTestsTimeoutInSeconds( double parallelTestsTimeoutInSeconds ) - { + public void setParallelTestsTimeoutInSeconds(double parallelTestsTimeoutInSeconds) { this.parallelTestsTimeoutInSeconds = parallelTestsTimeoutInSeconds; } @Override - public double getParallelTestsTimeoutForcedInSeconds() - { + public double getParallelTestsTimeoutForcedInSeconds() { return parallelTestsTimeoutForcedInSeconds; } @Override - public void setParallelTestsTimeoutForcedInSeconds( double parallelTestsTimeoutForcedInSeconds ) - { + public void setParallelTestsTimeoutForcedInSeconds(double parallelTestsTimeoutForcedInSeconds) { this.parallelTestsTimeoutForcedInSeconds = parallelTestsTimeoutForcedInSeconds; } @Override - public boolean isUseSystemClassLoader() - { + public boolean isUseSystemClassLoader() { return useSystemClassLoader; } @Override - public void setUseSystemClassLoader( boolean useSystemClassLoader ) - { + public void setUseSystemClassLoader(boolean useSystemClassLoader) { this.useSystemClassLoader = useSystemClassLoader; } @Override - public boolean isUseManifestOnlyJar() - { + public boolean isUseManifestOnlyJar() { return useManifestOnlyJar; } @Override - public void setUseManifestOnlyJar( boolean useManifestOnlyJar ) - { + public void setUseManifestOnlyJar(boolean useManifestOnlyJar) { this.useManifestOnlyJar = useManifestOnlyJar; } @Override - public String getEncoding() - { + public String getEncoding() { return encoding; } @Override - public void setEncoding( String encoding ) - { + public void setEncoding(String encoding) { this.encoding = encoding; } // the following will be refactored out once the common code is all in one place - public boolean isTestFailureIgnore() - { + public boolean isTestFailureIgnore() { return true; // ignore } - public void setTestFailureIgnore( boolean testFailureIgnore ) - { + public void setTestFailureIgnore(boolean testFailureIgnore) { // ignore } @Override - protected void addPluginSpecificChecksumItems( ChecksumCalculator checksum ) - { - checksum.add( skipITs ); - checksum.add( summaryFile ); + protected void addPluginSpecificChecksumItems(ChecksumCalculator checksum) { + checksum.add(skipITs); + checksum.add(summaryFile); } @Override - public File getSystemPropertiesFile() - { + public File getSystemPropertiesFile() { return systemPropertiesFile; } @Override - public void setSystemPropertiesFile( File systemPropertiesFile ) - { + public void setSystemPropertiesFile(File systemPropertiesFile) { this.systemPropertiesFile = systemPropertiesFile; } @Override - @SuppressWarnings( "deprecation" ) - public boolean getFailIfNoSpecifiedTests() - { - if ( !failIfNoSpecifiedTestsDeprecated ) - { - getConsoleLogger().warning( "Use " + getPluginName() - + ".failIfNoSpecifiedTests property instead of obsolete it.failIfNoSpecifiedTests." ); + @SuppressWarnings("deprecation") + public boolean getFailIfNoSpecifiedTests() { + if (!failIfNoSpecifiedTestsDeprecated) { + getConsoleLogger() + .warning("Use " + getPluginName() + + ".failIfNoSpecifiedTests property instead of obsolete it.failIfNoSpecifiedTests."); } // since both have default "true", assuming that any "false" is set by user on purpose return failIfNoSpecifiedTests && failIfNoSpecifiedTestsDeprecated; } @Override - public void setFailIfNoSpecifiedTests( boolean failIfNoSpecifiedTests ) - { + public void setFailIfNoSpecifiedTests(boolean failIfNoSpecifiedTests) { this.failIfNoSpecifiedTests = failIfNoSpecifiedTests; } @Override - public int getSkipAfterFailureCount() - { + public int getSkipAfterFailureCount() { return skipAfterFailureCount; } @Override - public String getShutdown() - { + public String getShutdown() { return shutdown; } @Override - public List getIncludes() - { + public List getIncludes() { return includes; } @Override - public void setIncludes( List includes ) - { + public void setIncludes(List includes) { this.includes = includes; } @Override - public List getExcludes() - { + public List getExcludes() { return excludes; } @Override - public void setExcludes( List excludes ) - { + public void setExcludes(List excludes) { this.excludes = excludes; } @Override - public File[] getSuiteXmlFiles() - { + public File[] getSuiteXmlFiles() { return suiteXmlFiles.clone(); } @Override - @SuppressWarnings( "UnusedDeclaration" ) - public void setSuiteXmlFiles( File[] suiteXmlFiles ) - { + @SuppressWarnings("UnusedDeclaration") + public void setSuiteXmlFiles(File[] suiteXmlFiles) { this.suiteXmlFiles = suiteXmlFiles.clone(); } @Override - public String getRunOrder() - { + public String getRunOrder() { return runOrder; } @Override - @SuppressWarnings( "UnusedDeclaration" ) - public void setRunOrder( String runOrder ) - { + @SuppressWarnings("UnusedDeclaration") + public void setRunOrder(String runOrder) { this.runOrder = runOrder; } @Override - public Long getRunOrderRandomSeed() - { + public Long getRunOrderRandomSeed() { return runOrderRandomSeed; } @Override - public void setRunOrderRandomSeed( Long runOrderRandomSeed ) - { + public void setRunOrderRandomSeed(Long runOrderRandomSeed) { this.runOrderRandomSeed = runOrderRandomSeed; } @Override - public File getIncludesFile() - { + public File getIncludesFile() { return includesFile; } @Override - public File getExcludesFile() - { + public File getExcludesFile() { return excludesFile; } @Override - protected boolean useModulePath() - { + protected boolean useModulePath() { return useModulePath; } @Override - protected void setUseModulePath( boolean useModulePath ) - { + protected void setUseModulePath(boolean useModulePath) { this.useModulePath = useModulePath; } @Override - protected final List suiteXmlFiles() - { - return hasSuiteXmlFiles() ? Arrays.asList( suiteXmlFiles ) : Collections.emptyList(); + protected final List suiteXmlFiles() { + return hasSuiteXmlFiles() ? Arrays.asList(suiteXmlFiles) : Collections.emptyList(); } @Override - protected final boolean hasSuiteXmlFiles() - { + protected final boolean hasSuiteXmlFiles() { return suiteXmlFiles != null && suiteXmlFiles.length != 0; } @Override - protected final ForkNodeFactory getForkNode() - { + protected final ForkNodeFactory getForkNode() { return forkNode; } @Override - protected final String[] getExcludedEnvironmentVariables() - { + protected final String[] getExcludedEnvironmentVariables() { return excludedEnvironmentVariables == null ? new String[0] : excludedEnvironmentVariables; } - void setExcludedEnvironmentVariables( String[] excludedEnvironmentVariables ) - { + void setExcludedEnvironmentVariables(String[] excludedEnvironmentVariables) { this.excludedEnvironmentVariables = excludedEnvironmentVariables; } @Override - protected final String getEnableProcessChecker() - { + protected final String getEnableProcessChecker() { return enableProcessChecker; } - public String[] getIncludeJUnit5Engines() - { + public String[] getIncludeJUnit5Engines() { return includeJUnit5Engines; } - @SuppressWarnings( "UnusedDeclaration" ) - public void setIncludeJUnit5Engines( String[] includeJUnit5Engines ) - { + @SuppressWarnings("UnusedDeclaration") + public void setIncludeJUnit5Engines(String[] includeJUnit5Engines) { this.includeJUnit5Engines = includeJUnit5Engines; } - public String[] getExcludeJUnit5Engines() - { + public String[] getExcludeJUnit5Engines() { return excludeJUnit5Engines; } - @SuppressWarnings( "UnusedDeclaration" ) - public void setExcludeJUnit5Engines( String[] excludeJUnit5Engines ) - { + @SuppressWarnings("UnusedDeclaration") + public void setExcludeJUnit5Engines(String[] excludeJUnit5Engines) { this.excludeJUnit5Engines = excludeJUnit5Engines; } } diff --git a/maven-failsafe-plugin/src/main/java/org/apache/maven/plugin/failsafe/VerifyMojo.java b/maven-failsafe-plugin/src/main/java/org/apache/maven/plugin/failsafe/VerifyMojo.java index 0dd1529d94..25045636f5 100644 --- a/maven-failsafe-plugin/src/main/java/org/apache/maven/plugin/failsafe/VerifyMojo.java +++ b/maven-failsafe-plugin/src/main/java/org/apache/maven/plugin/failsafe/VerifyMojo.java @@ -1,3 +1,21 @@ +/* + * 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.maven.plugin.failsafe; /* @@ -19,6 +37,9 @@ * under the License. */ +import java.io.File; +import java.util.Collection; + import org.apache.maven.execution.MavenSession; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; @@ -36,12 +57,9 @@ import org.apache.maven.surefire.booter.SurefireBooterForkException; import org.codehaus.plexus.logging.Logger; -import java.io.File; -import java.util.Collection; - import static org.apache.maven.plugin.surefire.SurefireHelper.reportExecution; -import static org.apache.maven.surefire.shared.utils.StringUtils.capitalizeFirstLetter; import static org.apache.maven.surefire.api.suite.RunResult.noTestsRun; +import static org.apache.maven.surefire.shared.utils.StringUtils.capitalizeFirstLetter; /** * Verify integration tests ran using Surefire. @@ -49,12 +67,9 @@ * @author Stephen Connolly * @author Jason van Zyl */ -@SuppressWarnings( "unused" ) -@Mojo( name = "verify", defaultPhase = LifecyclePhase.VERIFY, requiresProject = true, threadSafe = true ) -public class VerifyMojo - extends AbstractMojo - implements SurefireReportParameters -{ +@SuppressWarnings("unused") +@Mojo(name = "verify", defaultPhase = LifecyclePhase.VERIFY, requiresProject = true, threadSafe = true) +public class VerifyMojo extends AbstractMojo implements SurefireReportParameters { /** * Set this to 'true' to skip running tests, but still compile them. Its use is NOT RECOMMENDED, but quite @@ -62,7 +77,7 @@ public class VerifyMojo * * @since 2.4 */ - @Parameter( property = "skipTests" ) + @Parameter(property = "skipTests") private boolean skipTests; /** @@ -71,7 +86,7 @@ public class VerifyMojo * * @since 2.4.3-alpha-2 */ - @Parameter( property = "skipITs" ) + @Parameter(property = "skipITs") private boolean skipITs; /** @@ -81,7 +96,7 @@ public class VerifyMojo * @deprecated Use -DskipTests instead. */ @Deprecated - @Parameter( property = "maven.test.skip.exec" ) + @Parameter(property = "maven.test.skip.exec") private boolean skipExec; /** @@ -89,40 +104,40 @@ public class VerifyMojo * enable it using the "maven.test.skip" property, because maven.test.skip disables both running the * tests and compiling the tests. Consider using the skipTests parameter instead. */ - @Parameter( property = "maven.test.skip", defaultValue = "false" ) + @Parameter(property = "maven.test.skip", defaultValue = "false") private boolean skip; /** * Set this to true to ignore a failure during testing. Its use is NOT RECOMMENDED, but quite convenient on * occasion. */ - @Parameter( property = "maven.test.failure.ignore", defaultValue = "false" ) + @Parameter(property = "maven.test.failure.ignore", defaultValue = "false") private boolean testFailureIgnore; /** * The base directory of the project being tested. This can be obtained in your unit test by * System.getProperty("basedir"). */ - @Parameter( defaultValue = "${basedir}" ) + @Parameter(defaultValue = "${basedir}") private File basedir; /** * The directory containing generated test classes of the project being tested. * This will be included at the beginning the test classpath. */ - @Parameter( defaultValue = "${project.build.testOutputDirectory}" ) + @Parameter(defaultValue = "${project.build.testOutputDirectory}") private File testClassesDirectory; /** * Base directory where all reports are written to. */ - @Parameter( defaultValue = "${project.build.directory}/failsafe-reports" ) + @Parameter(defaultValue = "${project.build.directory}/failsafe-reports") private File reportsDirectory; /** * The summary file to read integration test results from. */ - @Parameter( defaultValue = "${project.build.directory}/failsafe-reports/failsafe-summary.xml", required = true ) + @Parameter(defaultValue = "${project.build.directory}/failsafe-reports/failsafe-summary.xml", required = true) private File summaryFile; /** @@ -137,16 +152,16 @@ public class VerifyMojo * * @since 2.4 */ - @Parameter( property = "failIfNoTests", defaultValue = "false" ) + @Parameter(property = "failIfNoTests", defaultValue = "false") private boolean failIfNoTests; /** * Set this to a value greater than 0 to fail the whole test set if the cumulative number of flakes reaches * this threshold. Set to 0 to allow an unlimited number of flakes. - * + * * @since 3.0.0-M6 */ - @Parameter( property = "failsafe.failOnFlakeCount", defaultValue = "0" ) + @Parameter(property = "failsafe.failOnFlakeCount", defaultValue = "0") private int failOnFlakeCount; /** @@ -155,13 +170,13 @@ public class VerifyMojo * * @deprecated since of 2.20.1 */ - @Parameter( property = "encoding", defaultValue = "${project.reporting.outputEncoding}" ) + @Parameter(property = "encoding", defaultValue = "${project.reporting.outputEncoding}") private String encoding; /** * The current build session instance. */ - @Parameter( defaultValue = "${session}", readonly = true ) + @Parameter(defaultValue = "${session}", readonly = true) private MavenSession session; @Component @@ -172,278 +187,222 @@ public class VerifyMojo private volatile PluginConsoleLogger consoleLogger; @Override - public void execute() - throws MojoExecutionException, MojoFailureException - { + public void execute() throws MojoExecutionException, MojoFailureException { cli = commandLineOptions(); - if ( verifyParameters() ) - { - logDebugOrCliShowErrors( capitalizeFirstLetter( getPluginName() ) - + " report directory: " + getReportsDirectory() ); + if (verifyParameters()) { + logDebugOrCliShowErrors( + capitalizeFirstLetter(getPluginName()) + " report directory: " + getReportsDirectory()); RunResult summary; - try - { - summary = existsSummaryFile() ? readSummary( summaryFile ) : noTestsRun(); - - if ( existsSummaryFiles() ) - { - for ( final File summaryFile : summaryFiles ) - { - summary = summary.aggregate( readSummary( summaryFile ) ); + try { + summary = existsSummaryFile() ? readSummary(summaryFile) : noTestsRun(); + + if (existsSummaryFiles()) { + for (final File summaryFile : summaryFiles) { + summary = summary.aggregate(readSummary(summaryFile)); } } - } - catch ( Exception e ) - { - throw new MojoExecutionException( e.getMessage(), e ); + } catch (Exception e) { + throw new MojoExecutionException(e.getMessage(), e); } - reportExecution( this, summary, getConsoleLogger(), getBooterForkException( summary ) ); + reportExecution(this, summary, getConsoleLogger(), getBooterForkException(summary)); } } - private Exception getBooterForkException( RunResult summary ) - { - String firstForkExceptionFailureMessage = - String.format( "%s: " , SurefireBooterForkException.class.getName() ); - if ( summary.getFailure() != null && summary.getFailure().contains( firstForkExceptionFailureMessage ) ) - { + private Exception getBooterForkException(RunResult summary) { + String firstForkExceptionFailureMessage = String.format("%s: ", SurefireBooterForkException.class.getName()); + if (summary.getFailure() != null && summary.getFailure().contains(firstForkExceptionFailureMessage)) { return new SurefireBooterForkException( - summary.getFailure().substring( firstForkExceptionFailureMessage.length() ) ); + summary.getFailure().substring(firstForkExceptionFailureMessage.length())); } return null; } - void setLogger( Logger logger ) - { + void setLogger(Logger logger) { this.logger = logger; } - private PluginConsoleLogger getConsoleLogger() - { - if ( consoleLogger == null ) - { - synchronized ( this ) - { - if ( consoleLogger == null ) - { - consoleLogger = new PluginConsoleLogger( logger ); + private PluginConsoleLogger getConsoleLogger() { + if (consoleLogger == null) { + synchronized (this) { + if (consoleLogger == null) { + consoleLogger = new PluginConsoleLogger(logger); } } } return consoleLogger; } - private RunResult readSummary( File summaryFile ) throws Exception - { - return FailsafeSummaryXmlUtils.toRunResult( summaryFile ); + private RunResult readSummary(File summaryFile) throws Exception { + return FailsafeSummaryXmlUtils.toRunResult(summaryFile); } - protected boolean verifyParameters() - throws MojoFailureException - { - if ( isSkip() || isSkipTests() || isSkipITs() || isSkipExec() ) - { - getConsoleLogger().info( "Tests are skipped." ); + protected boolean verifyParameters() throws MojoFailureException { + if (isSkip() || isSkipTests() || isSkipITs() || isSkipExec()) { + getConsoleLogger().info("Tests are skipped."); return false; } - if ( !getTestClassesDirectory().exists() ) - { - if ( getFailIfNoTests() ) - { - throw new MojoFailureException( "No tests to run!" ); + if (!getTestClassesDirectory().exists()) { + if (getFailIfNoTests()) { + throw new MojoFailureException("No tests to run!"); } } - if ( !existsSummary() ) - { - getConsoleLogger().info( "No tests to run." ); + if (!existsSummary()) { + getConsoleLogger().info("No tests to run."); return false; } - if ( failOnFlakeCount < 0 ) - { - throw new MojoFailureException( "Parameter \"failOnFlakeCount\" should not be negative." ); + if (failOnFlakeCount < 0) { + throw new MojoFailureException("Parameter \"failOnFlakeCount\" should not be negative."); } return true; } - protected String getPluginName() - { + protected String getPluginName() { return "failsafe"; } - protected String[] getDefaultIncludes() - { + protected String[] getDefaultIncludes() { return null; } @Override - public boolean isSkipTests() - { + public boolean isSkipTests() { return skipTests; } @Override - public void setSkipTests( boolean skipTests ) - { + public void setSkipTests(boolean skipTests) { this.skipTests = skipTests; } - public boolean isSkipITs() - { + public boolean isSkipITs() { return skipITs; } - public void setSkipITs( boolean skipITs ) - { + public void setSkipITs(boolean skipITs) { this.skipITs = skipITs; } @Override @Deprecated - public boolean isSkipExec() - { + public boolean isSkipExec() { return skipExec; } @Override @Deprecated - public void setSkipExec( boolean skipExec ) - { + public void setSkipExec(boolean skipExec) { this.skipExec = skipExec; } @Override - public boolean isSkip() - { + public boolean isSkip() { return skip; } @Override - public void setSkip( boolean skip ) - { + public void setSkip(boolean skip) { this.skip = skip; } @Override - public boolean isTestFailureIgnore() - { + public boolean isTestFailureIgnore() { return testFailureIgnore; } @Override - public void setTestFailureIgnore( boolean testFailureIgnore ) - { + public void setTestFailureIgnore(boolean testFailureIgnore) { this.testFailureIgnore = testFailureIgnore; } @Override - public File getBasedir() - { + public File getBasedir() { return basedir; } @Override - public void setBasedir( File basedir ) - { + public void setBasedir(File basedir) { this.basedir = basedir; } @Override - public File getTestClassesDirectory() - { + public File getTestClassesDirectory() { return testClassesDirectory; } @Override - public void setTestClassesDirectory( File testClassesDirectory ) - { + public void setTestClassesDirectory(File testClassesDirectory) { this.testClassesDirectory = testClassesDirectory; } @Override - public File getReportsDirectory() - { + public File getReportsDirectory() { return reportsDirectory; } @Override - public void setReportsDirectory( File reportsDirectory ) - { + public void setReportsDirectory(File reportsDirectory) { this.reportsDirectory = reportsDirectory; } - public File getSummaryFile() - { + public File getSummaryFile() { return summaryFile; } - public void setSummaryFile( File summaryFile ) - { + public void setSummaryFile(File summaryFile) { this.summaryFile = summaryFile; } @Override - public boolean getFailIfNoTests() - { + public boolean getFailIfNoTests() { return failIfNoTests; } @Override - public void setFailIfNoTests( boolean failIfNoTests ) - { + public void setFailIfNoTests(boolean failIfNoTests) { this.failIfNoTests = failIfNoTests; } @Override - public int getFailOnFlakeCount() - { + public int getFailOnFlakeCount() { return failOnFlakeCount; } @Override - public void setFailOnFlakeCount( int failOnFlakeCount ) - { + public void setFailOnFlakeCount(int failOnFlakeCount) { this.failOnFlakeCount = failOnFlakeCount; } - public MavenSession getSession() - { + public MavenSession getSession() { return session; } - public void setSession( MavenSession session ) - { + public void setSession(MavenSession session) { this.session = session; } - private boolean existsSummaryFile() - { + private boolean existsSummaryFile() { return summaryFile != null && summaryFile.isFile(); } - private boolean existsSummaryFiles() - { + private boolean existsSummaryFiles() { return summaryFiles != null && summaryFiles.length != 0; } - private boolean existsSummary() - { + private boolean existsSummary() { return existsSummaryFile() || existsSummaryFiles(); } - private Collection commandLineOptions() - { - return SurefireHelper.commandLineOptions( session, getConsoleLogger() ); + private Collection commandLineOptions() { + return SurefireHelper.commandLineOptions(session, getConsoleLogger()); } - private void logDebugOrCliShowErrors( String s ) - { - SurefireHelper.logDebugOrCliShowErrors( s, getConsoleLogger(), cli ); + private void logDebugOrCliShowErrors(String s) { + SurefireHelper.logDebugOrCliShowErrors(s, getConsoleLogger(), cli); } - } diff --git a/maven-failsafe-plugin/src/main/java/org/apache/maven/plugin/failsafe/util/FailsafeSummaryXmlUtils.java b/maven-failsafe-plugin/src/main/java/org/apache/maven/plugin/failsafe/util/FailsafeSummaryXmlUtils.java index 03e340ca73..27cd052fd7 100644 --- a/maven-failsafe-plugin/src/main/java/org/apache/maven/plugin/failsafe/util/FailsafeSummaryXmlUtils.java +++ b/maven-failsafe-plugin/src/main/java/org/apache/maven/plugin/failsafe/util/FailsafeSummaryXmlUtils.java @@ -1,3 +1,21 @@ +/* + * 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.maven.plugin.failsafe.util; /* @@ -19,13 +37,9 @@ * under the License. */ -import org.apache.maven.surefire.shared.io.IOUtils; -import org.apache.maven.surefire.api.suite.RunResult; -import org.w3c.dom.Node; -import org.xml.sax.InputSource; - import javax.xml.xpath.XPath; import javax.xml.xpath.XPathFactory; + import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; @@ -34,6 +48,11 @@ import java.io.Reader; import java.util.Locale; +import org.apache.maven.surefire.api.suite.RunResult; +import org.apache.maven.surefire.shared.io.IOUtils; +import org.w3c.dom.Node; +import org.xml.sax.InputSource; + import static java.lang.Boolean.parseBoolean; import static java.lang.Integer.parseInt; import static java.lang.String.format; @@ -47,92 +66,85 @@ * @author Tibor Digana (tibor17) * @since 2.20 */ -public final class FailsafeSummaryXmlUtils -{ +public final class FailsafeSummaryXmlUtils { private static final String FAILSAFE_SUMMARY_XML_SCHEMA_LOCATION = "https://maven.apache.org/surefire/maven-surefire-plugin/xsd/failsafe-summary.xsd"; private static final String MESSAGE_NIL_ELEMENT = ""; - private static final String MESSAGE_ELEMENT = - "%s"; - - private static final String FAILSAFE_SUMMARY_XML_TEMPLATE = - "\n" - + "\n" - + " %d\n" - + " %d\n" - + " %d\n" - + " %d\n" - + " %s\n" - + ""; - - private FailsafeSummaryXmlUtils() - { - throw new IllegalStateException( "No instantiable constructor." ); + private static final String MESSAGE_ELEMENT = "%s"; + + private static final String FAILSAFE_SUMMARY_XML_TEMPLATE = "\n" + + "\n" + + " %d\n" + + " %d\n" + + " %d\n" + + " %d\n" + + " %s\n" + + ""; + + private FailsafeSummaryXmlUtils() { + throw new IllegalStateException("No instantiable constructor."); } - public static RunResult toRunResult( File failsafeSummaryXml ) throws Exception - { + public static RunResult toRunResult(File failsafeSummaryXml) throws Exception { XPathFactory xpathFactory = XPathFactory.newInstance(); XPath xpath = xpathFactory.newXPath(); - try ( Reader reader = new InputStreamReader( new FileInputStream( failsafeSummaryXml ), UTF_8 ) ) - { - Node root = ( Node ) xpath.evaluate( "/", new InputSource( reader ), NODE ); - - String completed = xpath.evaluate( "/failsafe-summary/completed", root ); - String errors = xpath.evaluate( "/failsafe-summary/errors", root ); - String failures = xpath.evaluate( "/failsafe-summary/failures", root ); - String skipped = xpath.evaluate( "/failsafe-summary/skipped", root ); - String failureMessage = xpath.evaluate( "/failsafe-summary/failureMessage", root ); - String timeout = xpath.evaluate( "/failsafe-summary/@timeout", root ); - - return new RunResult( parseInt( completed ), parseInt( errors ), parseInt( failures ), parseInt( skipped ), - isBlank( failureMessage ) ? null : unescapeXml( failureMessage ), - parseBoolean( timeout ) - ); + try (Reader reader = new InputStreamReader(new FileInputStream(failsafeSummaryXml), UTF_8)) { + Node root = (Node) xpath.evaluate("/", new InputSource(reader), NODE); + + String completed = xpath.evaluate("/failsafe-summary/completed", root); + String errors = xpath.evaluate("/failsafe-summary/errors", root); + String failures = xpath.evaluate("/failsafe-summary/failures", root); + String skipped = xpath.evaluate("/failsafe-summary/skipped", root); + String failureMessage = xpath.evaluate("/failsafe-summary/failureMessage", root); + String timeout = xpath.evaluate("/failsafe-summary/@timeout", root); + + return new RunResult( + parseInt(completed), + parseInt(errors), + parseInt(failures), + parseInt(skipped), + isBlank(failureMessage) ? null : unescapeXml(failureMessage), + parseBoolean(timeout)); } } - public static void fromRunResultToFile( RunResult fromRunResult, File toFailsafeSummaryXml ) - throws IOException - { + public static void fromRunResultToFile(RunResult fromRunResult, File toFailsafeSummaryXml) throws IOException { String failure = fromRunResult.getFailure(); - String msg = isBlank( failure ) ? MESSAGE_NIL_ELEMENT : format( MESSAGE_ELEMENT, escapeXml10( failure ) ); - String xml = format( Locale.ROOT, FAILSAFE_SUMMARY_XML_TEMPLATE, + String msg = isBlank(failure) ? MESSAGE_NIL_ELEMENT : format(MESSAGE_ELEMENT, escapeXml10(failure)); + String xml = format( + Locale.ROOT, + FAILSAFE_SUMMARY_XML_TEMPLATE, fromRunResult.getFailsafeCode(), - String.valueOf( fromRunResult.isTimeout() ), + String.valueOf(fromRunResult.isTimeout()), fromRunResult.getCompletedCount(), fromRunResult.getErrors(), fromRunResult.getFailures(), fromRunResult.getSkipped(), - msg ); + msg); - try ( FileOutputStream os = new FileOutputStream( toFailsafeSummaryXml ) ) - { - IOUtils.write( xml, os, UTF_8 ); + try (FileOutputStream os = new FileOutputStream(toFailsafeSummaryXml)) { + IOUtils.write(xml, os, UTF_8); } } - public static void writeSummary( RunResult mergedSummary, File mergedSummaryFile, boolean inProgress ) - throws Exception - { - if ( !mergedSummaryFile.getParentFile().isDirectory() ) - { + public static void writeSummary(RunResult mergedSummary, File mergedSummaryFile, boolean inProgress) + throws Exception { + if (!mergedSummaryFile.getParentFile().isDirectory()) { //noinspection ResultOfMethodCallIgnored mergedSummaryFile.getParentFile().mkdirs(); } - if ( mergedSummaryFile.exists() && inProgress ) - { - RunResult runResult = toRunResult( mergedSummaryFile ); - mergedSummary = mergedSummary.aggregate( runResult ); + if (mergedSummaryFile.exists() && inProgress) { + RunResult runResult = toRunResult(mergedSummaryFile); + mergedSummary = mergedSummary.aggregate(runResult); } - fromRunResultToFile( mergedSummary, mergedSummaryFile ); + fromRunResultToFile(mergedSummary, mergedSummaryFile); } } diff --git a/maven-failsafe-plugin/src/test/java/org/apache/maven/plugin/failsafe/IntegrationTestMojoTest.java b/maven-failsafe-plugin/src/test/java/org/apache/maven/plugin/failsafe/IntegrationTestMojoTest.java index 2553369d69..d57a0c922e 100644 --- a/maven-failsafe-plugin/src/test/java/org/apache/maven/plugin/failsafe/IntegrationTestMojoTest.java +++ b/maven-failsafe-plugin/src/test/java/org/apache/maven/plugin/failsafe/IntegrationTestMojoTest.java @@ -1,3 +1,21 @@ +/* + * 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.maven.plugin.failsafe; /* @@ -19,6 +37,9 @@ * under the License. */ +import java.io.File; +import java.io.IOException; + import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.DefaultArtifact; import org.apache.maven.artifact.versioning.InvalidVersionSpecificationException; @@ -26,9 +47,6 @@ import org.junit.Before; import org.junit.Test; -import java.io.File; -import java.io.IOException; - import static org.apache.maven.artifact.versioning.VersionRange.createFromVersionSpec; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; @@ -37,80 +55,67 @@ /** * @since 2.20 */ -public class IntegrationTestMojoTest -{ +public class IntegrationTestMojoTest { private IntegrationTestMojo mojo; @Before - public void init() throws InvalidVersionSpecificationException, IOException - { - Artifact artifact = new DefaultArtifact( "g", "a", createFromVersionSpec( "1.0" ), "compile", "jar", "", null ); - artifact.setFile( new File( "./target/tmp/a-1.0.jar" ) ); - new File( "./target/tmp" ).mkdir(); + public void init() throws InvalidVersionSpecificationException, IOException { + Artifact artifact = new DefaultArtifact("g", "a", createFromVersionSpec("1.0"), "compile", "jar", "", null); + artifact.setFile(new File("./target/tmp/a-1.0.jar")); + new File("./target/tmp").mkdir(); artifact.getFile().createNewFile(); mojo = new IntegrationTestMojo(); - MavenProject project = mock( MavenProject.class ); - when( project.getArtifact() ).thenReturn( artifact ); - mojo.setProject( project ); + MavenProject project = mock(MavenProject.class); + when(project.getArtifact()).thenReturn(artifact); + mojo.setProject(project); } @Test - public void shouldBeJar() - { - mojo.setDefaultClassesDirectory( new File( "./target/classes" ) ); + public void shouldBeJar() { + mojo.setDefaultClassesDirectory(new File("./target/classes")); File binaries = mojo.getMainBuildPath(); - assertThat( binaries.getName() ).isEqualTo( "a-1.0.jar" ); + assertThat(binaries.getName()).isEqualTo("a-1.0.jar"); } @Test - public void shouldBeAnotherJar() - { - mojo.setMainBuildPath( new File( "./target/another-1.0.jar" ) ); - mojo.setDefaultClassesDirectory( new File( "./target/classes" ) ); + public void shouldBeAnotherJar() { + mojo.setMainBuildPath(new File("./target/another-1.0.jar")); + mojo.setDefaultClassesDirectory(new File("./target/classes")); File binaries = mojo.getMainBuildPath(); - assertThat( binaries.getName() ).isEqualTo( "another-1.0.jar" ); + assertThat(binaries.getName()).isEqualTo("another-1.0.jar"); } @Test - public void shouldBeClasses() - { - mojo.setMainBuildPath( new File( "./target/classes" ) ); - mojo.setDefaultClassesDirectory( new File( "./target/classes" ) ); + public void shouldBeClasses() { + mojo.setMainBuildPath(new File("./target/classes")); + mojo.setDefaultClassesDirectory(new File("./target/classes")); File binaries = mojo.getMainBuildPath(); - assertThat( binaries.getName() ).isEqualTo( "classes" ); + assertThat(binaries.getName()).isEqualTo("classes"); } @Test - public void shouldGetNullEnv() - { - assertThat( mojo.getExcludedEnvironmentVariables() ) - .hasSize( 0 ); + public void shouldGetNullEnv() { + assertThat(mojo.getExcludedEnvironmentVariables()).hasSize(0); } @Test - public void shouldGetEnv() - { - mojo.setExcludedEnvironmentVariables( new String[] { "ABC", "KLM" } ); - assertThat( mojo.getExcludedEnvironmentVariables() ) - .hasSize( 2 ) - .contains( "ABC", "KLM" ); + public void shouldGetEnv() { + mojo.setExcludedEnvironmentVariables(new String[] {"ABC", "KLM"}); + assertThat(mojo.getExcludedEnvironmentVariables()).hasSize(2).contains("ABC", "KLM"); } @Test - public void testShouldGetPropertyFile() - { - mojo.setSystemPropertiesFile( new File( "testShouldGetPropertyFile" ) ); - assertThat( mojo.getSystemPropertiesFile() ) - .isEqualTo( new File( "testShouldGetPropertyFile" ) ); + public void testShouldGetPropertyFile() { + mojo.setSystemPropertiesFile(new File("testShouldGetPropertyFile")); + assertThat(mojo.getSystemPropertiesFile()).isEqualTo(new File("testShouldGetPropertyFile")); } @Test - public void shouldHaveJUnit5EnginesFilter() - { - mojo.setIncludeJUnit5Engines( new String[] { "e1", "e2" } ); - assertThat( mojo.getIncludeJUnit5Engines() ).isEqualTo( new String[] { "e1", "e2" } ); + public void shouldHaveJUnit5EnginesFilter() { + mojo.setIncludeJUnit5Engines(new String[] {"e1", "e2"}); + assertThat(mojo.getIncludeJUnit5Engines()).isEqualTo(new String[] {"e1", "e2"}); - mojo.setExcludeJUnit5Engines( new String[] { "e1", "e2" } ); - assertThat( mojo.getExcludeJUnit5Engines() ).isEqualTo( new String[] { "e1", "e2" } ); + mojo.setExcludeJUnit5Engines(new String[] {"e1", "e2"}); + assertThat(mojo.getExcludeJUnit5Engines()).isEqualTo(new String[] {"e1", "e2"}); } } diff --git a/maven-failsafe-plugin/src/test/java/org/apache/maven/plugin/failsafe/JUnit4SuiteTest.java b/maven-failsafe-plugin/src/test/java/org/apache/maven/plugin/failsafe/JUnit4SuiteTest.java index 186803a0d3..9f08295c7c 100644 --- a/maven-failsafe-plugin/src/test/java/org/apache/maven/plugin/failsafe/JUnit4SuiteTest.java +++ b/maven-failsafe-plugin/src/test/java/org/apache/maven/plugin/failsafe/JUnit4SuiteTest.java @@ -1,3 +1,21 @@ +/* + * 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.maven.plugin.failsafe; /* @@ -31,17 +49,15 @@ * @author Tibor Digana (tibor17) * @since 2.21.0 */ -@SuiteClasses( { - IntegrationTestMojoTest.class, - MarshallerUnmarshallerTest.class, - RunResultTest.class, - VerifyMojoTest.class -} ) -@RunWith( Suite.class ) -public class JUnit4SuiteTest -{ - public static Test suite() - { - return new JUnit4TestAdapter( JUnit4SuiteTest.class ); +@SuiteClasses({ + IntegrationTestMojoTest.class, + MarshallerUnmarshallerTest.class, + RunResultTest.class, + VerifyMojoTest.class +}) +@RunWith(Suite.class) +public class JUnit4SuiteTest { + public static Test suite() { + return new JUnit4TestAdapter(JUnit4SuiteTest.class); } } diff --git a/maven-failsafe-plugin/src/test/java/org/apache/maven/plugin/failsafe/MarshallerUnmarshallerTest.java b/maven-failsafe-plugin/src/test/java/org/apache/maven/plugin/failsafe/MarshallerUnmarshallerTest.java index 20979fd194..5a266e2e6d 100644 --- a/maven-failsafe-plugin/src/test/java/org/apache/maven/plugin/failsafe/MarshallerUnmarshallerTest.java +++ b/maven-failsafe-plugin/src/test/java/org/apache/maven/plugin/failsafe/MarshallerUnmarshallerTest.java @@ -1,3 +1,21 @@ +/* + * 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.maven.plugin.failsafe; /* @@ -19,85 +37,74 @@ * under the License. */ +import java.io.File; + import org.apache.maven.plugin.failsafe.util.FailsafeSummaryXmlUtils; import org.apache.maven.surefire.api.suite.RunResult; import org.apache.maven.surefire.api.util.SureFireFileManager; import org.junit.Test; -import java.io.File; - import static org.assertj.core.api.Assertions.assertThat; /** * */ -public class MarshallerUnmarshallerTest -{ +public class MarshallerUnmarshallerTest { @Test - public void shouldUnmarshallExistingXmlFile() throws Exception - { - File xml = new File( "target/test-classes/org/apache/maven/plugin/failsafe/failsafe-summary.xml" ); - RunResult summary = FailsafeSummaryXmlUtils.toRunResult( xml ); - - assertThat( summary.getCompletedCount() ) - .isEqualTo( 7 ); - - assertThat( summary.getErrors() ) - .isEqualTo( 1 ); - - assertThat( summary.getFailures() ) - .isEqualTo( 2 ); - - assertThat( summary.getSkipped() ) - .isEqualTo( 3 ); - - assertThat( summary.getFailure() ) - .contains( "There was an error in the forked processtest " - + "subsystem#no method RuntimeException Hi There!" - ); - - assertThat( summary.getFailure() ) - .contains( "There was an error in the forked processtest " - + "subsystem#no method RuntimeException Hi There! $&>>" - + "\n\tat org.apache.maven.plugin.surefire.booterclient.ForkStarter" - + ".awaitResultsDone(ForkStarter.java:489)" - ); + public void shouldUnmarshallExistingXmlFile() throws Exception { + File xml = new File("target/test-classes/org/apache/maven/plugin/failsafe/failsafe-summary.xml"); + RunResult summary = FailsafeSummaryXmlUtils.toRunResult(xml); + + assertThat(summary.getCompletedCount()).isEqualTo(7); + + assertThat(summary.getErrors()).isEqualTo(1); + + assertThat(summary.getFailures()).isEqualTo(2); + + assertThat(summary.getSkipped()).isEqualTo(3); + + assertThat(summary.getFailure()) + .contains("There was an error in the forked processtest " + + "subsystem#no method RuntimeException Hi There!"); + + assertThat(summary.getFailure()) + .contains("There was an error in the forked processtest " + + "subsystem#no method RuntimeException Hi There! $&>>" + + "\n\tat org.apache.maven.plugin.surefire.booterclient.ForkStarter" + + ".awaitResultsDone(ForkStarter.java:489)"); } @Test - public void shouldMarshallAndUnmarshallSameXml() throws Exception - { - RunResult expected = - new RunResult( 7, 1, 2, 3, 2, - "There was an error in the forked processtest " - + "subsystem#no method RuntimeException Hi There! $&>>" - + "\n\tat org.apache.maven.plugin.surefire.booterclient.ForkStarter" - + ".awaitResultsDone(ForkStarter.java:489)", true ); + public void shouldMarshallAndUnmarshallSameXml() throws Exception { + RunResult expected = new RunResult( + 7, + 1, + 2, + 3, + 2, + "There was an error in the forked processtest " + + "subsystem#no method RuntimeException Hi There! $&>>" + + "\n\tat org.apache.maven.plugin.surefire.booterclient.ForkStarter" + + ".awaitResultsDone(ForkStarter.java:489)", + true); - File xml = SureFireFileManager.createTempFile( "failsafe-summary", ".xml" ); - FailsafeSummaryXmlUtils.writeSummary( expected, xml, false ); + File xml = SureFireFileManager.createTempFile("failsafe-summary", ".xml"); + FailsafeSummaryXmlUtils.writeSummary(expected, xml, false); - RunResult actual = FailsafeSummaryXmlUtils.toRunResult( xml ); + RunResult actual = FailsafeSummaryXmlUtils.toRunResult(xml); - assertThat( actual.getFailures() ) - .isEqualTo( expected.getFailures() ); + assertThat(actual.getFailures()).isEqualTo(expected.getFailures()); - assertThat( actual.isTimeout() ) - .isEqualTo( expected.isTimeout() ); + assertThat(actual.isTimeout()).isEqualTo(expected.isTimeout()); - assertThat( actual.getCompletedCount() ) - .isEqualTo( expected.getCompletedCount() ); + assertThat(actual.getCompletedCount()).isEqualTo(expected.getCompletedCount()); - assertThat( actual.getErrors() ) - .isEqualTo( expected.getErrors() ); + assertThat(actual.getErrors()).isEqualTo(expected.getErrors()); - assertThat( actual.getFailures() ) - .isEqualTo( expected.getFailures() ); + assertThat(actual.getFailures()).isEqualTo(expected.getFailures()); - assertThat( actual.getSkipped() ) - .isEqualTo( expected.getSkipped() ); + assertThat(actual.getSkipped()).isEqualTo(expected.getSkipped()); - assertThat( actual.getFailure() ) - .isEqualTo( expected.getFailure() ); + assertThat(actual.getFailure()).isEqualTo(expected.getFailure()); } } diff --git a/maven-failsafe-plugin/src/test/java/org/apache/maven/plugin/failsafe/RunResultTest.java b/maven-failsafe-plugin/src/test/java/org/apache/maven/plugin/failsafe/RunResultTest.java index 14f7d1762f..b395f4ce84 100644 --- a/maven-failsafe-plugin/src/test/java/org/apache/maven/plugin/failsafe/RunResultTest.java +++ b/maven-failsafe-plugin/src/test/java/org/apache/maven/plugin/failsafe/RunResultTest.java @@ -1,3 +1,21 @@ +/* + * 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.maven.plugin.failsafe; /* @@ -19,124 +37,97 @@ * under the License. */ +import java.io.File; + import org.apache.maven.plugin.failsafe.util.FailsafeSummaryXmlUtils; import org.apache.maven.surefire.api.suite.RunResult; import org.apache.maven.surefire.api.util.SureFireFileManager; import org.junit.Test; -import java.io.File; - import static org.assertj.core.api.Assertions.assertThat; /** * @author Tibor Digana (tibor17) * @since 2.20 */ -@SuppressWarnings( "checkstyle:magicnumber" ) -public class RunResultTest -{ +@SuppressWarnings("checkstyle:magicnumber") +public class RunResultTest { @Test - public void testAggregatedValues() - { + public void testAggregatedValues() { RunResult simple = getSimpleAggregate(); - assertThat( simple.getCompletedCount() ) - .isEqualTo( 20 ); + assertThat(simple.getCompletedCount()).isEqualTo(20); - assertThat( simple.getErrors() ) - .isEqualTo( 3 ); + assertThat(simple.getErrors()).isEqualTo(3); - assertThat( simple.getFailures() ) - .isEqualTo( 7 ); + assertThat(simple.getFailures()).isEqualTo(7); - assertThat( simple.getSkipped() ) - .isEqualTo( 4 ); + assertThat(simple.getSkipped()).isEqualTo(4); - assertThat( simple.getFlakes() ) - .isEqualTo( 2 ); + assertThat(simple.getFlakes()).isEqualTo(2); } @Test - public void testSerialization() - throws Exception - { - writeReadCheck( getSimpleAggregate() ); + public void testSerialization() throws Exception { + writeReadCheck(getSimpleAggregate()); } @Test - public void testFailures() - throws Exception - { - writeReadCheck( new RunResult( 0, 1, 2, 3, "stacktraceHere", false ) ); + public void testFailures() throws Exception { + writeReadCheck(new RunResult(0, 1, 2, 3, "stacktraceHere", false)); } @Test - public void testSkipped() - throws Exception - { - writeReadCheck( new RunResult( 3, 2, 1, 0, null, true ) ); + public void testSkipped() throws Exception { + writeReadCheck(new RunResult(3, 2, 1, 0, null, true)); } @Test - public void testAppendSerialization() - throws Exception - { + public void testAppendSerialization() throws Exception { RunResult simpleAggregate = getSimpleAggregate(); - RunResult additional = new RunResult( 2, 1, 2, 2, "msg " + ( (char) 0x0E01 ), true ); + RunResult additional = new RunResult(2, 1, 2, 2, "msg " + ((char) 0x0E01), true); - File summary = SureFireFileManager.createTempFile( "failsafe", "test" ); - FailsafeSummaryXmlUtils.writeSummary( simpleAggregate, summary, false ); - FailsafeSummaryXmlUtils.writeSummary( additional, summary, true ); - RunResult actual = FailsafeSummaryXmlUtils.toRunResult( summary ); + File summary = SureFireFileManager.createTempFile("failsafe", "test"); + FailsafeSummaryXmlUtils.writeSummary(simpleAggregate, summary, false); + FailsafeSummaryXmlUtils.writeSummary(additional, summary, true); + RunResult actual = FailsafeSummaryXmlUtils.toRunResult(summary); //noinspection ResultOfMethodCallIgnored summary.delete(); - RunResult expected = simpleAggregate.aggregate( additional ); + RunResult expected = simpleAggregate.aggregate(additional); - assertThat( expected.getCompletedCount() ) - .isEqualTo( 22 ); + assertThat(expected.getCompletedCount()).isEqualTo(22); - assertThat( expected.getErrors() ) - .isEqualTo( 4 ); + assertThat(expected.getErrors()).isEqualTo(4); - assertThat( expected.getFailures() ) - .isEqualTo( 9 ); + assertThat(expected.getFailures()).isEqualTo(9); - assertThat( expected.getSkipped() ) - .isEqualTo( 6 ); + assertThat(expected.getSkipped()).isEqualTo(6); - assertThat( expected.getFlakes() ) - .isEqualTo( 2 ); + assertThat(expected.getFlakes()).isEqualTo(2); - assertThat( expected.getFailure() ) - .isEqualTo( "msg " + ( (char) 0x0E01 ) ); + assertThat(expected.getFailure()).isEqualTo("msg " + ((char) 0x0E01)); - assertThat( expected.isTimeout() ) - .isTrue(); + assertThat(expected.isTimeout()).isTrue(); - assertThat( actual ) - .isEqualTo( expected ); + assertThat(actual).isEqualTo(expected); } - private void writeReadCheck( RunResult expected ) - throws Exception - { - File tmp = SureFireFileManager.createTempFile( "test", "xml" ); - FailsafeSummaryXmlUtils.fromRunResultToFile( expected, tmp ); + private void writeReadCheck(RunResult expected) throws Exception { + File tmp = SureFireFileManager.createTempFile("test", "xml"); + FailsafeSummaryXmlUtils.fromRunResultToFile(expected, tmp); - RunResult actual = FailsafeSummaryXmlUtils.toRunResult( tmp ); + RunResult actual = FailsafeSummaryXmlUtils.toRunResult(tmp); //noinspection ResultOfMethodCallIgnored tmp.delete(); - assertThat( actual ) - .isEqualTo( expected ); + assertThat(actual).isEqualTo(expected); } - private RunResult getSimpleAggregate() - { - RunResult resultOne = new RunResult( 10, 1, 3, 2, 1 ); - RunResult resultTwo = new RunResult( 10, 2, 4, 2, 1 ); - return resultOne.aggregate( resultTwo ); + private RunResult getSimpleAggregate() { + RunResult resultOne = new RunResult(10, 1, 3, 2, 1); + RunResult resultTwo = new RunResult(10, 2, 4, 2, 1); + return resultOne.aggregate(resultTwo); } } diff --git a/maven-failsafe-plugin/src/test/java/org/apache/maven/plugin/failsafe/VerifyMojoTest.java b/maven-failsafe-plugin/src/test/java/org/apache/maven/plugin/failsafe/VerifyMojoTest.java index 37bd3b733f..91422956be 100644 --- a/maven-failsafe-plugin/src/test/java/org/apache/maven/plugin/failsafe/VerifyMojoTest.java +++ b/maven-failsafe-plugin/src/test/java/org/apache/maven/plugin/failsafe/VerifyMojoTest.java @@ -1,3 +1,21 @@ +/* + * 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.maven.plugin.failsafe; /* @@ -19,9 +37,6 @@ * under the License. */ -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - import java.io.File; import java.io.UnsupportedEncodingException; import java.net.URL; @@ -37,72 +52,68 @@ import org.junit.Test; import org.junit.rules.TemporaryFolder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + /** */ -public class VerifyMojoTest -{ +public class VerifyMojoTest { private VerifyMojo mojo; @Rule public TemporaryFolder tempFolder = new TemporaryFolder(); @Before - public void init() throws UnsupportedEncodingException - { + public void init() throws UnsupportedEncodingException { mojo = new VerifyMojo(); - mojo.setTestClassesDirectory( tempFolder.getRoot() ); - mojo.setReportsDirectory( getTestBaseDir() ); + mojo.setTestClassesDirectory(tempFolder.getRoot()); + mojo.setReportsDirectory(getTestBaseDir()); } - private void setupExecuteMocks() - { - Logger logger = mock( Logger.class ); - when( logger.isErrorEnabled() ).thenReturn( true ); - when( logger.isWarnEnabled() ).thenReturn( true ); - when( logger.isInfoEnabled() ).thenReturn( true ); - when( logger.isDebugEnabled() ).thenReturn( false ); - mojo.setLogger( logger ); + private void setupExecuteMocks() { + Logger logger = mock(Logger.class); + when(logger.isErrorEnabled()).thenReturn(true); + when(logger.isWarnEnabled()).thenReturn(true); + when(logger.isInfoEnabled()).thenReturn(true); + when(logger.isDebugEnabled()).thenReturn(false); + mojo.setLogger(logger); - MavenSession session = mock( MavenSession.class ); - MavenExecutionRequest request = mock ( MavenExecutionRequest.class ); - when( request.isShowErrors() ).thenReturn( true ); - when( request.getReactorFailureBehavior() ).thenReturn( null ); - when( session.getRequest() ).thenReturn( request ); - mojo.setSession( session ); + MavenSession session = mock(MavenSession.class); + MavenExecutionRequest request = mock(MavenExecutionRequest.class); + when(request.isShowErrors()).thenReturn(true); + when(request.getReactorFailureBehavior()).thenReturn(null); + when(session.getRequest()).thenReturn(request); + mojo.setSession(session); } - private File getTestBaseDir() - throws UnsupportedEncodingException - { - URL resource = getClass().getResource( "/verify-mojo" ); + private File getTestBaseDir() throws UnsupportedEncodingException { + URL resource = getClass().getResource("/verify-mojo"); // URLDecoder.decode necessary for JDK 1.5+, where spaces are escaped to %20 - return new File( URLDecoder.decode( resource.getPath(), "UTF-8" ) ).getAbsoluteFile(); + return new File(URLDecoder.decode(resource.getPath(), "UTF-8")).getAbsoluteFile(); } - @Test( expected = MojoExecutionException.class ) - public void executeForForkError() throws MojoExecutionException, MojoFailureException, UnsupportedEncodingException - { + @Test(expected = MojoExecutionException.class) + public void executeForForkError() + throws MojoExecutionException, MojoFailureException, UnsupportedEncodingException { setupExecuteMocks(); - mojo.setSummaryFile( new File( getTestBaseDir(), "failsafe-summary-booter-fork-error.xml" ) ); + mojo.setSummaryFile(new File(getTestBaseDir(), "failsafe-summary-booter-fork-error.xml")); mojo.execute(); } - @Test( expected = MojoExecutionException.class ) - public void executeForForkErrorTestFailureIgnore() throws MojoExecutionException, MojoFailureException, - UnsupportedEncodingException - { + @Test(expected = MojoExecutionException.class) + public void executeForForkErrorTestFailureIgnore() + throws MojoExecutionException, MojoFailureException, UnsupportedEncodingException { setupExecuteMocks(); - mojo.setSummaryFile( new File( getTestBaseDir(), "failsafe-summary-booter-fork-error.xml" ) ); - mojo.setTestFailureIgnore( true ); + mojo.setSummaryFile(new File(getTestBaseDir(), "failsafe-summary-booter-fork-error.xml")); + mojo.setTestFailureIgnore(true); mojo.execute(); } @Test - public void executeForPassingTests() throws MojoExecutionException, MojoFailureException, - UnsupportedEncodingException - { + public void executeForPassingTests() + throws MojoExecutionException, MojoFailureException, UnsupportedEncodingException { setupExecuteMocks(); - mojo.setSummaryFile( new File( getTestBaseDir(), "failsafe-summary-success.xml" ) ); + mojo.setSummaryFile(new File(getTestBaseDir(), "failsafe-summary-success.xml")); mojo.execute(); } } diff --git a/maven-surefire-common/pom.xml b/maven-surefire-common/pom.xml index 100cc3da37..82abed6148 100644 --- a/maven-surefire-common/pom.xml +++ b/maven-surefire-common/pom.xml @@ -17,149 +17,149 @@ ~ specific language governing permissions and limitations ~ under the License. --> - - 4.0.0 + 4.0.0 - - org.apache.maven.surefire - surefire - 3.0.0-M10-SNAPSHOT - + + org.apache.maven.surefire + surefire + 3.0.0-M10-SNAPSHOT + - maven-surefire-common + maven-surefire-common - Maven Surefire Common - API used in Surefire and Failsafe MOJO. + Maven Surefire Common + API used in Surefire and Failsafe MOJO. - - - org.apache.maven.surefire - surefire-api - ${project.version} - - - org.apache.maven.surefire - surefire-extensions-api - ${project.version} - - - org.apache.maven.surefire - surefire-booter - ${project.version} - - - org.apache.maven - maven-core - provided - - - org.apache.maven.plugin-tools - maven-plugin-annotations - provided - - - org.apache.maven.shared - maven-common-artifact-filters - - - org.codehaus.plexus - plexus-java - - - org.fusesource.jansi - jansi - provided - - - org.apache.maven.surefire - surefire-shared-utils - ${surefire-shared-utils.version} - - - com.google.code.findbugs - jsr305 - provided - - - org.mockito - mockito-core - test - - - org.powermock - powermock-core - test - - - org.powermock - powermock-module-junit4 - test - - - org.powermock - powermock-api-mockito2 - test - - - org.jacoco - org.jacoco.agent - runtime - test - - + + + org.apache.maven.surefire + surefire-api + ${project.version} + + + org.apache.maven.surefire + surefire-extensions-api + ${project.version} + + + org.apache.maven.surefire + surefire-booter + ${project.version} + + + org.apache.maven + maven-core + provided + + + org.apache.maven.plugin-tools + maven-plugin-annotations + provided + + + org.apache.maven.shared + maven-common-artifact-filters + + + org.codehaus.plexus + plexus-java + + + org.fusesource.jansi + jansi + provided + + + org.apache.maven.surefire + surefire-shared-utils + ${surefire-shared-utils.version} + + + com.google.code.findbugs + jsr305 + provided + + + org.mockito + mockito-core + test + + + org.powermock + powermock-core + test + + + org.powermock + powermock-module-junit4 + test + + + org.powermock + powermock-api-mockito2 + test + + + org.jacoco + org.jacoco.agent + runtime + test + + - - - - org.jacoco - jacoco-maven-plugin - - - jacoco-instrumentation - - instrument - - - - restore-classes - - restore-instrumented-classes - - - - - - maven-surefire-plugin - - - org.apache.maven.surefire - surefire-shadefire - 3.0.0-M7 - - - - ${jvm.args.tests} - - **/JUnit4SuiteTest.java - - - ${project.build.directory}/jacoco.exec - - - - - org.codehaus.plexus - plexus-component-metadata - 2.1.1 - - - - generate-metadata - - - - - - + + + + org.jacoco + jacoco-maven-plugin + + + jacoco-instrumentation + + instrument + + + + restore-classes + + restore-instrumented-classes + + + + + + maven-surefire-plugin + + ${jvm.args.tests} + + **/JUnit4SuiteTest.java + + + ${project.build.directory}/jacoco.exec + + + + + org.apache.maven.surefire + surefire-shadefire + 3.0.0-M7 + + + + + + org.codehaus.plexus + plexus-component-metadata + 2.1.1 + + + + generate-metadata + + + + + + diff --git a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/AbstractSurefireMojo.java b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/AbstractSurefireMojo.java index 30709011fb..2c0365627b 100644 --- a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/AbstractSurefireMojo.java +++ b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/AbstractSurefireMojo.java @@ -1,6 +1,3 @@ -// CHECKSTYLE_OFF: FileLength|RegexpHeader -package org.apache.maven.plugin.surefire; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -10,7 +7,7 @@ * "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 + * 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 @@ -19,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.surefire; import javax.annotation.Nonnull; @@ -164,12 +162,9 @@ * @author Stephen Connolly * @version $Id: SurefirePlugin.java 945065 2010-05-17 10:26:22Z stephenc $ */ -public abstract class AbstractSurefireMojo - extends AbstractMojo - implements SurefireExecutionParameters -{ - private static final Map JAVA_9_MATCHER_OLD_NOTATION = singletonMap( "version", "[1.9,)" ); - private static final Map JAVA_9_MATCHER = singletonMap( "version", "[9,)" ); +public abstract class AbstractSurefireMojo extends AbstractMojo implements SurefireExecutionParameters { + private static final Map JAVA_9_MATCHER_OLD_NOTATION = singletonMap("version", "[1.9,)"); + private static final Map JAVA_9_MATCHER = singletonMap("version", "[9,)"); private static final Platform PLATFORM = new Platform(); private final ClasspathCache classpathCache = new ClasspathCache(); @@ -192,7 +187,7 @@ public abstract class AbstractSurefireMojo * * @since 2.12 */ - @Parameter( defaultValue = "${plugin}", readonly = true, required = true ) + @Parameter(defaultValue = "${plugin}", readonly = true, required = true) private PluginDescriptor pluginDescriptor; /** @@ -203,7 +198,7 @@ public abstract class AbstractSurefireMojo * * @since 2.4 */ - @Parameter( property = "skipTests", defaultValue = "false" ) + @Parameter(property = "skipTests", defaultValue = "false") protected boolean skipTests; /** @@ -213,7 +208,7 @@ public abstract class AbstractSurefireMojo * @deprecated Use skipTests instead. */ @Deprecated - @Parameter( property = "maven.test.skip.exec" ) + @Parameter(property = "maven.test.skip.exec") protected boolean skipExec; /** @@ -221,27 +216,27 @@ public abstract class AbstractSurefireMojo * the "maven.test.skip" property, because maven.test.skip disables both running the tests and compiling the tests. * Consider using the {@code skipTests} parameter instead. */ - @Parameter( property = "maven.test.skip", defaultValue = "false" ) + @Parameter(property = "maven.test.skip", defaultValue = "false") protected boolean skip; /** * The Maven Project Object. */ - @Parameter( defaultValue = "${project}", required = true, readonly = true ) + @Parameter(defaultValue = "${project}", required = true, readonly = true) private MavenProject project; /** * The base directory of the project being tested. This can be obtained in your integration test via * System.getProperty("basedir"). */ - @Parameter( defaultValue = "${basedir}", readonly = true, required = true ) + @Parameter(defaultValue = "${basedir}", readonly = true, required = true) protected File basedir; /** * The directory containing generated test classes of the project being tested. This will be included at the * beginning of the test classpath. * */ - @Parameter( defaultValue = "${project.build.testOutputDirectory}" ) + @Parameter(defaultValue = "${project.build.testOutputDirectory}") protected File testClassesDirectory; /** @@ -250,7 +245,7 @@ public abstract class AbstractSurefireMojo * * @since 2.6 */ - @Parameter( property = "maven.test.dependency.excludes" ) + @Parameter(property = "maven.test.dependency.excludes") private String[] classpathDependencyExcludes; /** @@ -267,7 +262,7 @@ public abstract class AbstractSurefireMojo * * @since 2.6 */ - @Parameter( defaultValue = "" ) + @Parameter(defaultValue = "") private String classpathDependencyScopeExclude; /** @@ -275,7 +270,7 @@ public abstract class AbstractSurefireMojo * * @since 2.4 */ - @Parameter( property = "maven.test.additionalClasspath" ) + @Parameter(property = "maven.test.additionalClasspath") private String[] additionalClasspathElements; /** @@ -284,14 +279,14 @@ public abstract class AbstractSurefireMojo * * @since 2.2 */ - @Parameter( defaultValue = "${project.build.testSourceDirectory}" ) + @Parameter(defaultValue = "${project.build.testSourceDirectory}") private File testSourceDirectory; /** * ArtifactRepository of the localRepository. To obtain the directory of localRepository in unit tests use * System.getProperty("localRepository"). */ - @Parameter( defaultValue = "${localRepository}", required = true, readonly = true ) + @Parameter(defaultValue = "${localRepository}", required = true, readonly = true) private ArtifactRepository localRepository; /** @@ -323,13 +318,13 @@ public abstract class AbstractSurefireMojo /** * Map of plugin artifacts. */ - @Parameter( property = "plugin.artifactMap", required = true, readonly = true ) + @Parameter(property = "plugin.artifactMap", required = true, readonly = true) private Map pluginArtifactMap; /** * Map of project artifacts. */ - @Parameter( property = "project.artifactMap", readonly = true, required = true ) + @Parameter(property = "project.artifactMap", readonly = true, required = true) private Map projectArtifactMap; /** @@ -338,7 +333,7 @@ public abstract class AbstractSurefireMojo * File TEST-testClassName-reportNameSuffix.xml has changed attributes 'testsuite'--'name' * and 'testcase'--'classname' - reportNameSuffix is added to the attribute value. */ - @Parameter( property = "surefire.reportNameSuffix", defaultValue = "" ) + @Parameter(property = "surefire.reportNameSuffix", defaultValue = "") private String reportNameSuffix; /** @@ -347,7 +342,7 @@ public abstract class AbstractSurefireMojo * * @since 2.3 */ - @Parameter( property = "maven.test.redirectTestOutputToFile", defaultValue = "false" ) + @Parameter(property = "maven.test.redirectTestOutputToFile", defaultValue = "false") private boolean redirectTestOutputToFile; /** @@ -355,7 +350,7 @@ public abstract class AbstractSurefireMojo * * @since 2.4 */ - @Parameter( property = "failIfNoTests", defaultValue = "false" ) + @Parameter(property = "failIfNoTests", defaultValue = "false") private boolean failIfNoTests; /** @@ -369,7 +364,7 @@ public abstract class AbstractSurefireMojo * * @since 2.20 */ - @Parameter( property = "tempDir", defaultValue = "surefire" ) + @Parameter(property = "tempDir", defaultValue = "surefire") private String tempDir; /** @@ -379,7 +374,7 @@ public abstract class AbstractSurefireMojo * * @since 2.1 */ - @Parameter( property = "jvm" ) + @Parameter(property = "jvm") private String jvm; /** @@ -398,7 +393,7 @@ public abstract class AbstractSurefireMojo * * @since 2.1 */ - @Parameter( property = "argLine" ) + @Parameter(property = "argLine") private String argLine; /** @@ -414,7 +409,7 @@ public abstract class AbstractSurefireMojo * * @since 2.1.3 */ - @Parameter( property = "basedir" ) + @Parameter(property = "basedir") private File workingDirectory; /** @@ -425,7 +420,7 @@ public abstract class AbstractSurefireMojo * * @since 2.1 */ - @Parameter( property = "childDelegation", defaultValue = "false" ) + @Parameter(property = "childDelegation", defaultValue = "false") private boolean childDelegation; /** @@ -441,7 +436,7 @@ public abstract class AbstractSurefireMojo * * @since 2.2 */ - @Parameter( property = "groups" ) + @Parameter(property = "groups") private String groups; /** @@ -457,7 +452,7 @@ public abstract class AbstractSurefireMojo * * @since 2.2 */ - @Parameter( property = "excludedGroups" ) + @Parameter(property = "excludedGroups") private String excludedGroups; /** @@ -465,7 +460,7 @@ public abstract class AbstractSurefireMojo * * @since 2.3.1 */ - @Parameter( property = "junitArtifactName", defaultValue = "junit:junit" ) + @Parameter(property = "junitArtifactName", defaultValue = "junit:junit") private String junitArtifactName; /** @@ -473,7 +468,7 @@ public abstract class AbstractSurefireMojo * * @since 2.3.1 */ - @Parameter( property = "testNGArtifactName", defaultValue = "org.testng:testng" ) + @Parameter(property = "testNGArtifactName", defaultValue = "org.testng:testng") private String testNGArtifactName; /** @@ -482,7 +477,7 @@ public abstract class AbstractSurefireMojo * * @since 2.2 */ - @Parameter( property = "threadCount" ) + @Parameter(property = "threadCount") private int threadCount; /** @@ -500,7 +495,7 @@ public abstract class AbstractSurefireMojo * * @since 2.14 */ - @Parameter( property = "forkCount", defaultValue = "1" ) + @Parameter(property = "forkCount", defaultValue = "1") private String forkCount; /** @@ -509,8 +504,7 @@ public abstract class AbstractSurefireMojo * * @since 2.13 */ - - @Parameter( property = "reuseForks", defaultValue = "true" ) + @Parameter(property = "reuseForks", defaultValue = "true") private boolean reuseForks; /** @@ -519,7 +513,7 @@ public abstract class AbstractSurefireMojo * * @since 2.5 */ - @Parameter( property = "perCoreThreadCount", defaultValue = "true" ) + @Parameter(property = "perCoreThreadCount", defaultValue = "true") private boolean perCoreThreadCount; /** @@ -529,7 +523,7 @@ public abstract class AbstractSurefireMojo * * @since 2.5 */ - @Parameter( property = "useUnlimitedThreads", defaultValue = "false" ) + @Parameter(property = "useUnlimitedThreads", defaultValue = "false") private boolean useUnlimitedThreads; /** @@ -555,7 +549,7 @@ public abstract class AbstractSurefireMojo * * @since 2.2 */ - @Parameter( property = "parallel" ) + @Parameter(property = "parallel") private String parallel; /** @@ -566,7 +560,7 @@ public abstract class AbstractSurefireMojo * * @since 2.17 */ - @Parameter( property = "parallelOptimized", defaultValue = "true" ) + @Parameter(property = "parallelOptimized", defaultValue = "true") private boolean parallelOptimized; /** @@ -585,7 +579,7 @@ public abstract class AbstractSurefireMojo * * @since 2.16 */ - @Parameter( property = "threadCountSuites", defaultValue = "0" ) + @Parameter(property = "threadCountSuites", defaultValue = "0") private int threadCountSuites; /** @@ -608,7 +602,7 @@ public abstract class AbstractSurefireMojo * * @since 2.16 */ - @Parameter( property = "threadCountClasses", defaultValue = "0" ) + @Parameter(property = "threadCountClasses", defaultValue = "0") private int threadCountClasses; /** @@ -630,7 +624,7 @@ public abstract class AbstractSurefireMojo * * @since 2.16 */ - @Parameter( property = "threadCountMethods", defaultValue = "0" ) + @Parameter(property = "threadCountMethods", defaultValue = "0") private int threadCountMethods; /** @@ -638,7 +632,7 @@ public abstract class AbstractSurefireMojo * * @since 2.2 */ - @Parameter( property = "trimStackTrace", defaultValue = "false" ) + @Parameter(property = "trimStackTrace", defaultValue = "false") private boolean trimStackTrace; /** @@ -646,10 +640,10 @@ public abstract class AbstractSurefireMojo * * @since 2.2 */ - @Parameter( defaultValue = "${project.pluginArtifactRepositories}", readonly = true, required = true ) + @Parameter(defaultValue = "${project.pluginArtifactRepositories}", readonly = true, required = true) private List remoteRepositories; - @Parameter( defaultValue = "${project.remoteArtifactRepositories}", required = true, readonly = true ) + @Parameter(defaultValue = "${project.remoteArtifactRepositories}", required = true, readonly = true) private List projectRemoteRepositories; /** @@ -659,7 +653,7 @@ public abstract class AbstractSurefireMojo * @since 2.2 */ @Deprecated // todo make readonly to handle system property - @Parameter( property = "disableXmlReport", defaultValue = "false" ) + @Parameter(property = "disableXmlReport", defaultValue = "false") private boolean disableXmlReport; /** @@ -668,13 +662,13 @@ public abstract class AbstractSurefireMojo * * @since 2.3.1 */ - @Parameter( property = "enableAssertions", defaultValue = "true" ) + @Parameter(property = "enableAssertions", defaultValue = "true") private boolean enableAssertions; /** * The current build session instance. */ - @Parameter( defaultValue = "${session}", required = true, readonly = true ) + @Parameter(defaultValue = "${session}", required = true, readonly = true) private MavenSession session; @Component @@ -685,20 +679,20 @@ public abstract class AbstractSurefireMojo * * @since 2.5 */ - @Parameter( property = "objectFactory" ) + @Parameter(property = "objectFactory") private String objectFactory; /** * Parallel Maven Execution. */ - @Parameter( defaultValue = "${session.parallel}", readonly = true ) + @Parameter(defaultValue = "${session.parallel}", readonly = true) private Boolean parallelMavenExecution; /** * Read-only parameter with value of Maven property project.build.directory. * @since 2.20 */ - @Parameter( defaultValue = "${project.build.directory}", readonly = true, required = true ) + @Parameter(defaultValue = "${project.build.directory}", readonly = true, required = true) private File projectBuildDirectory; /** @@ -729,7 +723,7 @@ public abstract class AbstractSurefireMojo * * @since 2.15 */ - @Parameter( property = "dependenciesToScan" ) + @Parameter(property = "dependenciesToScan") private String[] dependenciesToScan; /** @@ -800,7 +794,7 @@ public abstract class AbstractSurefireMojo public abstract File getIncludesFile(); @Override - public abstract void setIncludes( List includes ); + public abstract void setIncludes(List includes); public abstract File getExcludesFile(); @@ -821,18 +815,18 @@ public abstract class AbstractSurefireMojo public abstract File[] getSuiteXmlFiles(); - public abstract void setSuiteXmlFiles( File[] suiteXmlFiles ); + public abstract void setSuiteXmlFiles(File[] suiteXmlFiles); public abstract String getRunOrder(); - public abstract void setRunOrder( String runOrder ); + public abstract void setRunOrder(String runOrder); public abstract Long getRunOrderRandomSeed(); - public abstract void setRunOrderRandomSeed( Long runOrderRandomSeed ); + public abstract void setRunOrderRandomSeed(Long runOrderRandomSeed); - protected abstract void handleSummary( RunResult summary, Exception firstForkException ) - throws MojoExecutionException, MojoFailureException; + protected abstract void handleSummary(RunResult summary, Exception firstForkException) + throws MojoExecutionException, MojoFailureException; protected abstract boolean isSkipExecution(); @@ -842,7 +836,7 @@ protected abstract void handleSummary( RunResult summary, Exception firstForkExc protected abstract boolean useModulePath(); - protected abstract void setUseModulePath( boolean useModulePath ); + protected abstract void setUseModulePath(boolean useModulePath); protected abstract String getEnableProcessChecker(); @@ -853,13 +847,11 @@ protected abstract void handleSummary( RunResult summary, Exception firstForkExc * * @return non-null plugin artifact */ - protected Artifact getMojoArtifact() - { + protected Artifact getMojoArtifact() { return getPluginDescriptor().getPluginArtifact(); } - private String getDefaultExcludes() - { + private String getDefaultExcludes() { return "**/*$*"; } @@ -874,233 +866,186 @@ private String getDefaultExcludes() private volatile PluginConsoleLogger consoleLogger; @Override - public void execute() - throws MojoExecutionException, MojoFailureException - { + public void execute() throws MojoExecutionException, MojoFailureException { cli = commandLineOptions(); // Stuff that should have been final setupStuff(); - Platform platform = PLATFORM.withJdkExecAttributesForTests( getEffectiveJvm() ); - Thread shutdownThread = new Thread( platform::setShutdownState ); - addShutDownHook( shutdownThread ); - try - { - if ( verifyParameters() && !hasExecutedBefore() ) - { + Platform platform = PLATFORM.withJdkExecAttributesForTests(getEffectiveJvm()); + Thread shutdownThread = new Thread(platform::setShutdownState); + addShutDownHook(shutdownThread); + try { + if (verifyParameters() && !hasExecutedBefore()) { DefaultScanResult scan = scanForTestClasses(); - if ( !hasSuiteXmlFiles() && scan.isEmpty() ) - { - switch ( getEffectiveFailIfNoTests() ) - { + if (!hasSuiteXmlFiles() && scan.isEmpty()) { + switch (getEffectiveFailIfNoTests()) { case COULD_NOT_RUN_DEFAULT_TESTS: throw new MojoFailureException( - "No tests were executed! (Set -DfailIfNoTests=false to ignore this error.)" ); + "No tests were executed! (Set -DfailIfNoTests=false to ignore this error.)"); case COULD_NOT_RUN_SPECIFIED_TESTS: - throw new MojoFailureException( "No tests matching pattern \"" - + getSpecificTests().toString() - + "\" were executed! (Set " - + "-D" + getPluginName() - + ".failIfNoSpecifiedTests=false to ignore this error.)" ); + throw new MojoFailureException("No tests matching pattern \"" + + getSpecificTests().toString() + + "\" were executed! (Set " + + "-D" + getPluginName() + + ".failIfNoSpecifiedTests=false to ignore this error.)"); default: - handleSummary( noTestsRun(), null ); + handleSummary(noTestsRun(), null); return; } } logReportsDirectory(); - executeAfterPreconditionsChecked( scan, platform ); + executeAfterPreconditionsChecked(scan, platform); } - } - finally - { + } finally { platform.clearShutdownState(); - removeShutdownHook( shutdownThread ); + removeShutdownHook(shutdownThread); } } - void setLogger( Logger logger ) - { + void setLogger(Logger logger) { this.logger = logger; } @Nonnull - protected final PluginConsoleLogger getConsoleLogger() - { - if ( consoleLogger == null ) - { - synchronized ( this ) - { - if ( consoleLogger == null ) - { - consoleLogger = new PluginConsoleLogger( logger ); + protected final PluginConsoleLogger getConsoleLogger() { + if (consoleLogger == null) { + synchronized (this) { + if (consoleLogger == null) { + consoleLogger = new PluginConsoleLogger(logger); } } } return consoleLogger; } - private static Toolchain getToolchainMaven33x( Class toolchainManagerType, - T toolchainManager, - MavenSession session, - Map toolchainArgs ) - throws MojoFailureException - { + private static Toolchain getToolchainMaven33x( + Class toolchainManagerType, T toolchainManager, MavenSession session, Map toolchainArgs) + throws MojoFailureException { Method getToolchainsMethod = - tryGetMethod( toolchainManagerType, "getToolchains", MavenSession.class, String.class, Map.class ); - if ( getToolchainsMethod != null ) - { + tryGetMethod(toolchainManagerType, "getToolchains", MavenSession.class, String.class, Map.class); + if (getToolchainsMethod != null) { //noinspection unchecked - List tcs = invokeMethodWithArray( toolchainManager, - getToolchainsMethod, session, "jdk", toolchainArgs ); - if ( tcs.isEmpty() ) - { + List tcs = + invokeMethodWithArray(toolchainManager, getToolchainsMethod, session, "jdk", toolchainArgs); + if (tcs.isEmpty()) { throw new MojoFailureException( - "Requested toolchain specification did not match any configured toolchain: " + toolchainArgs ); + "Requested toolchain specification did not match any configured toolchain: " + toolchainArgs); } - return tcs.get( 0 ); + return tcs.get(0); } return null; } - //TODO remove the part with ToolchainManager lookup once we depend on - //3.0.9 (have it as prerequisite). Define as regular component field then. - private Toolchain getToolchain() throws MojoFailureException - { + // TODO remove the part with ToolchainManager lookup once we depend on + // 3.0.9 (have it as prerequisite). Define as regular component field then. + private Toolchain getToolchain() throws MojoFailureException { Toolchain tc = null; - if ( getJdkToolchain() != null ) - { - tc = getToolchainMaven33x( ToolchainManager.class, getToolchainManager(), getSession(), getJdkToolchain() ); + if (getJdkToolchain() != null) { + tc = getToolchainMaven33x(ToolchainManager.class, getToolchainManager(), getSession(), getJdkToolchain()); } - if ( tc == null ) - { - tc = getToolchainManager().getToolchainFromBuildContext( "jdk", getSession() ); + if (tc == null) { + tc = getToolchainManager().getToolchainFromBuildContext("jdk", getSession()); } return tc; } - private void setupStuff() throws MojoFailureException - { - surefireDependencyResolver = new SurefireDependencyResolver( getRepositorySystem(), - getConsoleLogger(), getLocalRepository(), + private void setupStuff() throws MojoFailureException { + surefireDependencyResolver = new SurefireDependencyResolver( + getRepositorySystem(), + getConsoleLogger(), + getLocalRepository(), getRemoteRepositories(), getProjectRemoteRepositories(), resolutionErrorHandler, getPluginName(), - getSession().isOffline() ); + getSession().isOffline()); - if ( getBooterArtifact() == null ) - { - throw new RuntimeException( "Unable to locate surefire-booter in the list of plugin artifacts" ); + if (getBooterArtifact() == null) { + throw new RuntimeException("Unable to locate surefire-booter in the list of plugin artifacts"); } - if ( getToolchainManager() != null ) - { + if (getToolchainManager() != null) { toolchain = getToolchain(); } } @Nonnull - private DefaultScanResult scanForTestClasses() - throws MojoFailureException - { + private DefaultScanResult scanForTestClasses() throws MojoFailureException { DefaultScanResult scan = scanDirectories(); DefaultScanResult scanDeps = scanDependencies(); - return scan.append( scanDeps ); + return scan.append(scanDeps); } - private DefaultScanResult scanDirectories() - throws MojoFailureException - { - DirectoryScanner scanner = new DirectoryScanner( getTestClassesDirectory(), getIncludedAndExcludedTests() ); + private DefaultScanResult scanDirectories() throws MojoFailureException { + DirectoryScanner scanner = new DirectoryScanner(getTestClassesDirectory(), getIncludedAndExcludedTests()); return scanner.scan(); } - List getProjectTestArtifacts() - { + List getProjectTestArtifacts() { return project.getTestArtifacts(); } - DefaultScanResult scanDependencies() throws MojoFailureException - { - if ( getDependenciesToScan() == null ) - { + DefaultScanResult scanDependencies() throws MojoFailureException { + if (getDependenciesToScan() == null) { return null; - } - else - { - try - { + } else { + try { DefaultScanResult result = null; - List dependenciesToScan = - filter( getProjectTestArtifacts(), asList( getDependenciesToScan() ) ); + List dependenciesToScan = filter(getProjectTestArtifacts(), asList(getDependenciesToScan())); - for ( Artifact artifact : dependenciesToScan ) - { + for (Artifact artifact : dependenciesToScan) { String type = artifact.getType(); File out = artifact.getFile(); - if ( out == null || !out.exists() - || !( "jar".equals( type ) || out.isDirectory() || out.getName().endsWith( ".jar" ) ) ) - { + if (out == null + || !out.exists() + || !("jar".equals(type) + || out.isDirectory() + || out.getName().endsWith(".jar"))) { continue; } - if ( out.isFile() ) - { + if (out.isFile()) { DependencyScanner scanner = - new DependencyScanner( singletonList( out ), getIncludedAndExcludedTests() ); - result = result == null ? scanner.scan() : result.append( scanner.scan() ); - } - else if ( out.isDirectory() ) - { - DirectoryScanner scanner = - new DirectoryScanner( out, getIncludedAndExcludedTests() ); - result = result == null ? scanner.scan() : result.append( scanner.scan() ); + new DependencyScanner(singletonList(out), getIncludedAndExcludedTests()); + result = result == null ? scanner.scan() : result.append(scanner.scan()); + } else if (out.isDirectory()) { + DirectoryScanner scanner = new DirectoryScanner(out, getIncludedAndExcludedTests()); + result = result == null ? scanner.scan() : result.append(scanner.scan()); } } return result; - } - catch ( Exception e ) - { - throw new MojoFailureException( e.getLocalizedMessage(), e ); + } catch (Exception e) { + throw new MojoFailureException(e.getLocalizedMessage(), e); } } } - boolean verifyParameters() - throws MojoFailureException, MojoExecutionException - { - setProperties( new SurefireProperties( getProperties() ) ); - if ( isSkipExecution() ) - { - getConsoleLogger().info( "Tests are skipped." ); + boolean verifyParameters() throws MojoFailureException, MojoExecutionException { + setProperties(new SurefireProperties(getProperties())); + if (isSkipExecution()) { + getConsoleLogger().info("Tests are skipped."); return false; } String jvmToUse = getJvm(); - if ( toolchain != null ) - { - getConsoleLogger().info( "Toolchain in maven-" + getPluginName() + "-plugin: " + toolchain ); - if ( jvmToUse != null ) - { - getConsoleLogger().warning( "Toolchains are ignored, 'jvm' parameter is set to " + jvmToUse ); + if (toolchain != null) { + getConsoleLogger().info("Toolchain in maven-" + getPluginName() + "-plugin: " + toolchain); + if (jvmToUse != null) { + getConsoleLogger().warning("Toolchains are ignored, 'jvm' parameter is set to " + jvmToUse); } } - if ( !getTestClassesDirectory().exists() - && ( getDependenciesToScan() == null || getDependenciesToScan().length == 0 ) ) - { - if ( getFailIfNoTests() ) - { - throw new MojoFailureException( "No tests to run!" ); + if (!getTestClassesDirectory().exists() + && (getDependenciesToScan() == null || getDependenciesToScan().length == 0)) { + if (getFailIfNoTests()) { + throw new MojoFailureException("No tests to run!"); } - getConsoleLogger().info( "No tests to run." ); - } - else - { + getConsoleLogger().info("No tests to run."); + } else { ensureEnableProcessChecker(); ensureWorkingDirectoryExists(); ensureParallelRunningCompatibility(); @@ -1117,465 +1062,381 @@ boolean verifyParameters() return true; } - private void warnIfForkCountIsZero() - { - if ( "0".equals( getForkCount() ) ) - { - getConsoleLogger().warning( "The parameter forkCount should likely not be 0. Forking a JVM for tests " - + "improves test accuracy. Ensure to have a >= 1." ); + private void warnIfForkCountIsZero() { + if ("0".equals(getForkCount())) { + getConsoleLogger() + .warning("The parameter forkCount should likely not be 0. Forking a JVM for tests " + + "improves test accuracy. Ensure to have a >= 1."); } } - private void executeAfterPreconditionsChecked( @Nonnull DefaultScanResult scanResult, @Nonnull Platform platform ) - throws MojoExecutionException, MojoFailureException - { + private void executeAfterPreconditionsChecked(@Nonnull DefaultScanResult scanResult, @Nonnull Platform platform) + throws MojoExecutionException, MojoFailureException { TestClassPath testClasspath = generateTestClasspath(); - List providers = createProviders( testClasspath ); - ResolvePathResultWrapper wrapper = findModuleDescriptor( platform.getJdkExecAttributesForTests().getJdkHome() ); + List providers = createProviders(testClasspath); + ResolvePathResultWrapper wrapper = + findModuleDescriptor(platform.getJdkExecAttributesForTests().getJdkHome()); RunResult current = noTestsRun(); Exception firstForkException = null; - for ( ProviderInfo provider : providers ) - { - try - { - current = - current.aggregate( executeProvider( provider, scanResult, testClasspath, platform, wrapper ) ); - } - catch ( SurefireBooterForkException | SurefireExecutionException | TestSetFailedException e ) - { - if ( firstForkException == null ) - { + for (ProviderInfo provider : providers) { + try { + current = current.aggregate(executeProvider(provider, scanResult, testClasspath, platform, wrapper)); + } catch (SurefireBooterForkException | SurefireExecutionException | TestSetFailedException e) { + if (firstForkException == null) { firstForkException = e; } } } - if ( firstForkException != null ) - { - current = failure( current, firstForkException ); + if (firstForkException != null) { + current = failure(current, firstForkException); } - handleSummary( current, firstForkException ); + handleSummary(current, firstForkException); } - protected List createProviders( TestClassPath testClasspath ) - throws MojoExecutionException - { + protected List createProviders(TestClassPath testClasspath) throws MojoExecutionException { Artifact junitDepArtifact = getJunitDepArtifact(); - return providerDetector.resolve( new DynamicProviderInfo( null ), - new JUnitPlatformProviderInfo( getJUnitPlatformRunnerArtifact(), getJUnit5Artifact(), testClasspath ), - new TestNgProviderInfo( getTestNgArtifact() ), - new JUnitCoreProviderInfo( getJunitArtifact(), junitDepArtifact ), - new JUnit4ProviderInfo( getJunitArtifact(), junitDepArtifact ), - new JUnit3ProviderInfo() ); + return providerDetector.resolve( + new DynamicProviderInfo(null), + new JUnitPlatformProviderInfo(getJUnitPlatformRunnerArtifact(), getJUnit5Artifact(), testClasspath), + new TestNgProviderInfo(getTestNgArtifact()), + new JUnitCoreProviderInfo(getJunitArtifact(), junitDepArtifact), + new JUnit4ProviderInfo(getJunitArtifact(), junitDepArtifact), + new JUnit3ProviderInfo()); } - private SurefireProperties setupProperties() - { + private SurefireProperties setupProperties() { SurefireProperties sysProps = null; - try - { - sysProps = SurefireProperties.loadProperties( getSystemPropertiesFile() ); - } - catch ( IOException e ) - { + try { + sysProps = SurefireProperties.loadProperties(getSystemPropertiesFile()); + } catch (IOException e) { String msg = "The file '" + getSystemPropertiesFile().getAbsolutePath() + "' can't be read."; - if ( getConsoleLogger().isDebugEnabled() ) - { - getConsoleLogger().debug( msg, e ); - } - else - { - getConsoleLogger().warning( msg ); - } - } - - SurefireProperties result = - SurefireProperties.calculateEffectiveProperties( getSystemProperties(), getSystemPropertyVariables(), - getUserProperties(), sysProps ); - - result.setProperty( "basedir", getBasedir().getAbsolutePath() ); - result.setProperty( "localRepository", getLocalRepository().getBasedir() ); - if ( isForking() ) - { - for ( Object o : result.propertiesThatCannotBeSetASystemProperties() ) - { - if ( getArgLine() == null || !getArgLine().contains( "-D" + o + "=" ) ) - { - getConsoleLogger().warning( o + " cannot be set as system property, use -D" - + o + "=... instead" - ); + if (getConsoleLogger().isDebugEnabled()) { + getConsoleLogger().debug(msg, e); + } else { + getConsoleLogger().warning(msg); + } + } + + SurefireProperties result = SurefireProperties.calculateEffectiveProperties( + getSystemProperties(), getSystemPropertyVariables(), getUserProperties(), sysProps); + + result.setProperty("basedir", getBasedir().getAbsolutePath()); + result.setProperty("localRepository", getLocalRepository().getBasedir()); + if (isForking()) { + for (Object o : result.propertiesThatCannotBeSetASystemProperties()) { + if (getArgLine() == null || !getArgLine().contains("-D" + o + "=")) { + getConsoleLogger() + .warning(o + " cannot be set as system property, use -D" + o + + "=... instead"); } } - for ( Object systemPropertyMatchingArgLine : systemPropertiesMatchingArgLine( result ) ) - { + for (Object systemPropertyMatchingArgLine : systemPropertiesMatchingArgLine(result)) { getConsoleLogger() - .warning( "The system property " - + systemPropertyMatchingArgLine - + " is configured twice! " - + "The property appears in and any of , " - + " or user property." - ); + .warning("The system property " + + systemPropertyMatchingArgLine + + " is configured twice! " + + "The property appears in and any of , " + + " or user property."); } - } - else - { - result.setProperty( "user.dir", getWorkingDirectory().getAbsolutePath() ); + } else { + result.setProperty("user.dir", getWorkingDirectory().getAbsolutePath()); } - if ( getConsoleLogger().isDebugEnabled() ) - { - showToLog( result, getConsoleLogger() ); + if (getConsoleLogger().isDebugEnabled()) { + showToLog(result, getConsoleLogger()); } return result; } - private Set systemPropertiesMatchingArgLine( SurefireProperties result ) - { + private Set systemPropertiesMatchingArgLine(SurefireProperties result) { Set intersection = new HashSet<>(); - if ( isNotBlank( getArgLine() ) ) - { - for ( Object systemProperty : result.getStringKeySet() ) - { - if ( getArgLine().contains( "-D" + systemProperty + "=" ) ) - { - intersection.add( systemProperty ); + if (isNotBlank(getArgLine())) { + for (Object systemProperty : result.getStringKeySet()) { + if (getArgLine().contains("-D" + systemProperty + "=")) { + intersection.add(systemProperty); } } Set ignored = result.propertiesThatCannotBeSetASystemProperties(); - intersection.removeAll( ignored ); + intersection.removeAll(ignored); } return intersection; } - private void showToLog( SurefireProperties props, ConsoleLogger log ) - { - for ( Object key : props.getStringKeySet() ) - { - String value = props.getProperty( (String) key ); - log.debug( "Setting system property [" + key + "]=[" + value + "]" ); + private void showToLog(SurefireProperties props, ConsoleLogger log) { + for (Object key : props.getStringKeySet()) { + String value = props.getProperty((String) key); + log.debug("Setting system property [" + key + "]=[" + value + "]"); } } @Nonnull - private RunResult executeProvider( @Nonnull ProviderInfo provider, @Nonnull DefaultScanResult scanResult, - @Nonnull TestClassPath testClasspathWrapper, @Nonnull Platform platform, - @Nonnull ResolvePathResultWrapper resolvedJavaModularityResult ) - throws MojoExecutionException, MojoFailureException, SurefireExecutionException, SurefireBooterForkException, - TestSetFailedException - { - getConsoleLogger().debug( "Using the provider " + provider.getProviderName() ); + private RunResult executeProvider( + @Nonnull ProviderInfo provider, + @Nonnull DefaultScanResult scanResult, + @Nonnull TestClassPath testClasspathWrapper, + @Nonnull Platform platform, + @Nonnull ResolvePathResultWrapper resolvedJavaModularityResult) + throws MojoExecutionException, MojoFailureException, SurefireExecutionException, + SurefireBooterForkException, TestSetFailedException { + getConsoleLogger().debug("Using the provider " + provider.getProviderName()); SurefireProperties effectiveProperties = setupProperties(); ClassLoaderConfiguration classLoaderConfiguration = getClassLoaderConfiguration(); provider.addProviderProperties(); RunOrderParameters runOrderParameters = - new RunOrderParameters( getRunOrder(), getStatisticsFile( getConfigChecksum() ), getRunOrderRandomSeed() ); - - if ( isNotForking() ) - { - Properties originalSystemProperties = (Properties) System.getProperties().clone(); - try - { - createCopyAndReplaceForkNumPlaceholder( effectiveProperties, 1 ).copyToSystemProperties(); - - InPluginVMSurefireStarter surefireStarter = createInprocessStarter( provider, classLoaderConfiguration, - runOrderParameters, scanResult, platform, testClasspathWrapper ); - return surefireStarter.runSuitesInProcess( scanResult ); - } - finally - { - System.setProperties( originalSystemProperties ); - } - } - else - { - ForkConfiguration forkConfiguration = createForkConfiguration( platform, resolvedJavaModularityResult ); - if ( getConsoleLogger().isDebugEnabled() ) - { - showMap( getEnvironmentVariables(), "environment variable" ); - showArray( getExcludedEnvironmentVariables(), "excluded environment variable" ); - } - - Properties originalSystemProperties = (Properties) System.getProperties().clone(); + new RunOrderParameters(getRunOrder(), getStatisticsFile(getConfigChecksum()), getRunOrderRandomSeed()); + + if (isNotForking()) { + Properties originalSystemProperties = + (Properties) System.getProperties().clone(); + try { + createCopyAndReplaceForkNumPlaceholder(effectiveProperties, 1).copyToSystemProperties(); + + InPluginVMSurefireStarter surefireStarter = createInprocessStarter( + provider, + classLoaderConfiguration, + runOrderParameters, + scanResult, + platform, + testClasspathWrapper); + return surefireStarter.runSuitesInProcess(scanResult); + } finally { + System.setProperties(originalSystemProperties); + } + } else { + ForkConfiguration forkConfiguration = createForkConfiguration(platform, resolvedJavaModularityResult); + if (getConsoleLogger().isDebugEnabled()) { + showMap(getEnvironmentVariables(), "environment variable"); + showArray(getExcludedEnvironmentVariables(), "excluded environment variable"); + } + + Properties originalSystemProperties = + (Properties) System.getProperties().clone(); ForkStarter forkStarter = null; - try - { - forkStarter = createForkStarter( provider, forkConfiguration, classLoaderConfiguration, - runOrderParameters, getConsoleLogger(), scanResult, - testClasspathWrapper, platform, resolvedJavaModularityResult ); - - return forkStarter.run( effectiveProperties, scanResult ); - } - catch ( SurefireBooterForkException e ) - { + try { + forkStarter = createForkStarter( + provider, + forkConfiguration, + classLoaderConfiguration, + runOrderParameters, + getConsoleLogger(), + scanResult, + testClasspathWrapper, + platform, + resolvedJavaModularityResult); + + return forkStarter.run(effectiveProperties, scanResult); + } catch (SurefireBooterForkException e) { forkStarter.killOrphanForks(); throw e; - } - finally - { - System.setProperties( originalSystemProperties ); - cleanupForkConfiguration( forkConfiguration ); + } finally { + System.setProperties(originalSystemProperties); + cleanupForkConfiguration(forkConfiguration); } } } public static SurefireProperties createCopyAndReplaceForkNumPlaceholder( - SurefireProperties effectiveSystemProperties, int threadNumber ) - { - SurefireProperties filteredProperties = new SurefireProperties( ( KeyValueSource) effectiveSystemProperties ); - for ( Entry entry : effectiveSystemProperties.entrySet() ) - { - if ( entry.getValue() instanceof String ) - { + SurefireProperties effectiveSystemProperties, int threadNumber) { + SurefireProperties filteredProperties = new SurefireProperties((KeyValueSource) effectiveSystemProperties); + for (Entry entry : effectiveSystemProperties.entrySet()) { + if (entry.getValue() instanceof String) { String value = (String) entry.getValue(); - filteredProperties.put( entry.getKey(), replaceThreadNumberPlaceholders( value, threadNumber ) ); + filteredProperties.put(entry.getKey(), replaceThreadNumberPlaceholders(value, threadNumber)); } } return filteredProperties; } - protected void cleanupForkConfiguration( ForkConfiguration forkConfiguration ) - { - if ( !getConsoleLogger().isDebugEnabled() && forkConfiguration != null ) - { + protected void cleanupForkConfiguration(ForkConfiguration forkConfiguration) { + if (!getConsoleLogger().isDebugEnabled() && forkConfiguration != null) { File tempDirectory = forkConfiguration.getTempDirectory(); - try - { - FileUtils.deleteDirectory( tempDirectory ); - } - catch ( IOException e ) - { + try { + FileUtils.deleteDirectory(tempDirectory); + } catch (IOException e) { getConsoleLogger() - .warning( "Could not delete temp directory " + tempDirectory + " because " + e.getMessage() ); + .warning("Could not delete temp directory " + tempDirectory + " because " + e.getMessage()); } } } - protected void logReportsDirectory() - { - logDebugOrCliShowErrors( - capitalizeFirstLetter( getPluginName() ) + " report directory: " + getReportsDirectory() ); + protected void logReportsDirectory() { + logDebugOrCliShowErrors(capitalizeFirstLetter(getPluginName()) + " report directory: " + getReportsDirectory()); } - public RepositorySystem getRepositorySystem() - { + public RepositorySystem getRepositorySystem() { return repositorySystem; } - public void setRepositorySystem( RepositorySystem repositorySystem ) - { + public void setRepositorySystem(RepositorySystem repositorySystem) { this.repositorySystem = repositorySystem; } - private boolean existsModuleDescriptor( ResolvePathResultWrapper resolvedJavaModularityResult ) - { + private boolean existsModuleDescriptor(ResolvePathResultWrapper resolvedJavaModularityResult) { return resolvedJavaModularityResult.getResolvePathResult() != null; } - private ResolvePathResultWrapper findModuleDescriptor( File jdkHome ) - { - ResolvePathResultWrapper test = findModuleDescriptor( jdkHome, getTestClassesDirectory(), false ); - return test.getResolvePathResult() == null ? findModuleDescriptor( jdkHome, getMainBuildPath(), true ) : test; + private ResolvePathResultWrapper findModuleDescriptor(File jdkHome) { + ResolvePathResultWrapper test = findModuleDescriptor(jdkHome, getTestClassesDirectory(), false); + return test.getResolvePathResult() == null ? findModuleDescriptor(jdkHome, getMainBuildPath(), true) : test; } - private ResolvePathResultWrapper findModuleDescriptor( File jdkHome, File buildPath, boolean isMainDescriptor ) - { + private ResolvePathResultWrapper findModuleDescriptor(File jdkHome, File buildPath, boolean isMainDescriptor) { boolean isJpmsModule = - buildPath.isDirectory() ? new File( buildPath, "module-info.class" ).exists() : isModule( buildPath ); + buildPath.isDirectory() ? new File(buildPath, "module-info.class").exists() : isModule(buildPath); - if ( !isJpmsModule ) - { - return new ResolvePathResultWrapper( null, isMainDescriptor ); + if (!isJpmsModule) { + return new ResolvePathResultWrapper(null, isMainDescriptor); } - try - { - ResolvePathRequest request = ResolvePathRequest.ofFile( buildPath ).setJdkHome( jdkHome ); - ResolvePathResult result = getLocationManager().resolvePath( request ); + try { + ResolvePathRequest request = ResolvePathRequest.ofFile(buildPath).setJdkHome(jdkHome); + ResolvePathResult result = getLocationManager().resolvePath(request); boolean isEmpty = result.getModuleNameSource() == null; - return new ResolvePathResultWrapper( isEmpty ? null : result, isMainDescriptor ); - } - catch ( Exception e ) - { - return new ResolvePathResultWrapper( null, isMainDescriptor ); + return new ResolvePathResultWrapper(isEmpty ? null : result, isMainDescriptor); + } catch (Exception e) { + return new ResolvePathResultWrapper(null, isMainDescriptor); } } - private static boolean isModule( File jar ) - { - try ( ZipFile zip = new ZipFile( jar ) ) - { - return zip.getEntry( "module-info.class" ) != null; - } - catch ( IOException e ) - { + private static boolean isModule(File jar) { + try (ZipFile zip = new ZipFile(jar)) { + return zip.getEntry("module-info.class") != null; + } catch (IOException e) { return false; } } - private boolean canExecuteProviderWithModularPath( @Nonnull Platform platform, - @Nonnull ResolvePathResultWrapper resolvedJavaModularityResult ) - { + private boolean canExecuteProviderWithModularPath( + @Nonnull Platform platform, @Nonnull ResolvePathResultWrapper resolvedJavaModularityResult) { return useModulePath() && platform.getJdkExecAttributesForTests().isJava9AtLeast() - && existsModuleDescriptor( resolvedJavaModularityResult ); + && existsModuleDescriptor(resolvedJavaModularityResult); } /** * Converts old TestNG configuration parameters over to new properties based configuration * method. (if any are defined the old way) */ - private void convertTestNGParameters() throws MojoExecutionException - { - if ( this.getParallel() != null ) - { - getProperties().setProperty( ProviderParameterNames.PARALLEL_PROP, this.getParallel() ); + private void convertTestNGParameters() throws MojoExecutionException { + if (this.getParallel() != null) { + getProperties().setProperty(ProviderParameterNames.PARALLEL_PROP, this.getParallel()); } convertGroupParameters(); - if ( this.getThreadCount() > 0 ) - { - getProperties().setProperty( ProviderParameterNames.THREADCOUNT_PROP, - Integer.toString( this.getThreadCount() ) ); + if (this.getThreadCount() > 0) { + getProperties() + .setProperty(ProviderParameterNames.THREADCOUNT_PROP, Integer.toString(this.getThreadCount())); } - if ( this.getObjectFactory() != null ) - { - getProperties().setProperty( "objectfactory", this.getObjectFactory() ); + if (this.getObjectFactory() != null) { + getProperties().setProperty("objectfactory", this.getObjectFactory()); } - if ( this.getTestClassesDirectory() != null ) - { - getProperties().setProperty( "testng.test.classpath", getTestClassesDirectory().getAbsolutePath() ); + if (this.getTestClassesDirectory() != null) { + getProperties() + .setProperty( + "testng.test.classpath", getTestClassesDirectory().getAbsolutePath()); } Artifact testNgArtifact = getTestNgArtifact(); - if ( testNgArtifact != null ) - { - DefaultArtifactVersion defaultArtifactVersion = new DefaultArtifactVersion( testNgArtifact.getVersion() ); - getProperties().setProperty( "testng.configurator", getConfiguratorName( defaultArtifactVersion, - getConsoleLogger() - ) - ); - } - } - - private static String getConfiguratorName( ArtifactVersion version, PluginConsoleLogger log ) - throws MojoExecutionException - { - try - { - VersionRange range = VersionRange.createFromVersionSpec( "[4.7,5.2)" ); - if ( range.containsVersion( version ) ) - { + if (testNgArtifact != null) { + DefaultArtifactVersion defaultArtifactVersion = new DefaultArtifactVersion(testNgArtifact.getVersion()); + getProperties() + .setProperty( + "testng.configurator", getConfiguratorName(defaultArtifactVersion, getConsoleLogger())); + } + } + + private static String getConfiguratorName(ArtifactVersion version, PluginConsoleLogger log) + throws MojoExecutionException { + try { + VersionRange range = VersionRange.createFromVersionSpec("[4.7,5.2)"); + if (range.containsVersion(version)) { return "org.apache.maven.surefire.testng.conf.TestNG4751Configurator"; } - range = VersionRange.createFromVersionSpec( "[5.2,5.3)" ); - if ( range.containsVersion( version ) ) - { + range = VersionRange.createFromVersionSpec("[5.2,5.3)"); + if (range.containsVersion(version)) { return "org.apache.maven.surefire.testng.conf.TestNG52Configurator"; } - range = VersionRange.createFromVersionSpec( "[5.3,5.10)" ); - if ( range.containsVersion( version ) ) - { + range = VersionRange.createFromVersionSpec("[5.3,5.10)"); + if (range.containsVersion(version)) { return "org.apache.maven.surefire.testng.conf.TestNGMapConfigurator"; } - range = VersionRange.createFromVersionSpec( "[5.10,5.13)" ); - if ( range.containsVersion( version ) ) - { + range = VersionRange.createFromVersionSpec("[5.10,5.13)"); + if (range.containsVersion(version)) { return "org.apache.maven.surefire.testng.conf.TestNG510Configurator"; } - range = VersionRange.createFromVersionSpec( "[5.13,5.14.1)" ); - if ( range.containsVersion( version ) ) - { + range = VersionRange.createFromVersionSpec("[5.13,5.14.1)"); + if (range.containsVersion(version)) { return "org.apache.maven.surefire.testng.conf.TestNG513Configurator"; } - range = VersionRange.createFromVersionSpec( "[5.14.1,5.14.3)" ); - if ( range.containsVersion( version ) ) - { - log.warning( "The 'reporter' or 'listener' may not work properly in TestNG 5.14.1 and 5.14.2." ); + range = VersionRange.createFromVersionSpec("[5.14.1,5.14.3)"); + if (range.containsVersion(version)) { + log.warning("The 'reporter' or 'listener' may not work properly in TestNG 5.14.1 and 5.14.2."); return "org.apache.maven.surefire.testng.conf.TestNG5141Configurator"; } - range = VersionRange.createFromVersionSpec( "[5.14.3,6.0)" ); - if ( range.containsVersion( version ) ) - { - if ( version.equals( new DefaultArtifactVersion( "[5.14.3,5.14.5]" ) ) ) - { - throw new MojoExecutionException( "TestNG 5.14.3-5.14.5 is not supported. " - + "System dependency org.testng:guice missed path." ); + range = VersionRange.createFromVersionSpec("[5.14.3,6.0)"); + if (range.containsVersion(version)) { + if (version.equals(new DefaultArtifactVersion("[5.14.3,5.14.5]"))) { + throw new MojoExecutionException("TestNG 5.14.3-5.14.5 is not supported. " + + "System dependency org.testng:guice missed path."); } return "org.apache.maven.surefire.testng.conf.TestNG5143Configurator"; } - range = VersionRange.createFromVersionSpec( "[6.0,7.4.0)" ); - if ( range.containsVersion( version ) ) - { + range = VersionRange.createFromVersionSpec("[6.0,7.4.0)"); + if (range.containsVersion(version)) { return "org.apache.maven.surefire.testng.conf.TestNG60Configurator"; } - range = VersionRange.createFromVersionSpec( "[7.4.0,)" ); - if ( range.containsVersion( version ) ) - { + range = VersionRange.createFromVersionSpec("[7.4.0,)"); + if (range.containsVersion(version)) { return "org.apache.maven.surefire.testng.conf.TestNG740Configurator"; } - throw new MojoExecutionException( "Unknown TestNG version " + version ); - } - catch ( InvalidVersionSpecificationException invsex ) - { - throw new MojoExecutionException( "Bug in plugin. Please report it with the attached stacktrace", invsex ); + throw new MojoExecutionException("Unknown TestNG version " + version); + } catch (InvalidVersionSpecificationException invsex) { + throw new MojoExecutionException("Bug in plugin. Please report it with the attached stacktrace", invsex); } } - - private void convertGroupParameters() - { - if ( this.getExcludedGroups() != null ) - { - getProperties().setProperty( ProviderParameterNames.TESTNG_EXCLUDEDGROUPS_PROP, this.getExcludedGroups() ); + private void convertGroupParameters() { + if (this.getExcludedGroups() != null) { + getProperties().setProperty(ProviderParameterNames.TESTNG_EXCLUDEDGROUPS_PROP, this.getExcludedGroups()); } - if ( this.getGroups() != null ) - { - getProperties().setProperty( ProviderParameterNames.TESTNG_GROUPS_PROP, this.getGroups() ); + if (this.getGroups() != null) { + getProperties().setProperty(ProviderParameterNames.TESTNG_GROUPS_PROP, this.getGroups()); } } - private void convertJunitEngineParameters() - { - if ( getIncludeJUnit5Engines() != null && getIncludeJUnit5Engines().length != 0 ) - { - getProperties() - .setProperty( INCLUDE_JUNIT5_ENGINES_PROP, join( getIncludeJUnit5Engines() ) ); + private void convertJunitEngineParameters() { + if (getIncludeJUnit5Engines() != null && getIncludeJUnit5Engines().length != 0) { + getProperties().setProperty(INCLUDE_JUNIT5_ENGINES_PROP, join(getIncludeJUnit5Engines())); } - if ( getExcludeJUnit5Engines() != null && getExcludeJUnit5Engines().length != 0 ) - { - getProperties() - .setProperty( EXCLUDE_JUNIT5_ENGINES_PROP, join( getExcludeJUnit5Engines() ) ); + if (getExcludeJUnit5Engines() != null && getExcludeJUnit5Engines().length != 0) { + getProperties().setProperty(EXCLUDE_JUNIT5_ENGINES_PROP, join(getExcludeJUnit5Engines())); } } - private static String join( String[] array ) - { + private static String join(String[] array) { StringBuilder stringBuilder = new StringBuilder(); - for ( int i = 0, length = array.length; i < length; i++ ) - { - stringBuilder.append( array[i] ); - if ( i < length - 1 ) - { - stringBuilder.append( ',' ); + for (int i = 0, length = array.length; i < length; i++) { + stringBuilder.append(array[i]); + if (i < length - 1) { + stringBuilder.append(','); } } return stringBuilder.toString(); } - protected boolean isAnyConcurrencySelected() - { + protected boolean isAnyConcurrencySelected() { return getParallel() != null && !getParallel().trim().isEmpty(); } - protected boolean isAnyGroupsSelected() - { + protected boolean isAnyGroupsSelected() { return this.getGroups() != null || this.getExcludedGroups() != null; } @@ -1583,253 +1444,232 @@ protected boolean isAnyGroupsSelected() * Converts old JUnit configuration parameters over to new properties based configuration * method. (if any are defined the old way) */ - private void convertJunitCoreParameters() throws MojoExecutionException - { - checkThreadCountEntity( getThreadCountSuites(), "suites" ); - checkThreadCountEntity( getThreadCountClasses(), "classes" ); - checkThreadCountEntity( getThreadCountMethods(), "methods" ); - - String usedParallel = ( getParallel() != null ) ? getParallel() : "none"; - - if ( !"none".equals( usedParallel ) ) - { - checkNonForkedThreads( parallel ); - } - - getProperties().setProperty( ProviderParameterNames.PARALLEL_PROP, usedParallel ); - if ( this.getThreadCount() > 0 ) - { - getProperties().setProperty( ProviderParameterNames.THREADCOUNT_PROP, - Integer.toString( getThreadCount() ) ); - } - getProperties().setProperty( "perCoreThreadCount", Boolean.toString( getPerCoreThreadCount() ) ); - getProperties().setProperty( "useUnlimitedThreads", Boolean.toString( getUseUnlimitedThreads() ) ); - getProperties().setProperty( ProviderParameterNames.THREADCOUNTSUITES_PROP, - Integer.toString( getThreadCountSuites() ) ); - getProperties().setProperty( ProviderParameterNames.THREADCOUNTCLASSES_PROP, - Integer.toString( getThreadCountClasses() ) ); - getProperties().setProperty( ProviderParameterNames.THREADCOUNTMETHODS_PROP, - Integer.toString( getThreadCountMethods() ) ); - getProperties().setProperty( ProviderParameterNames.PARALLEL_TIMEOUT_PROP, - Double.toString( getParallelTestsTimeoutInSeconds() ) ); - getProperties().setProperty( ProviderParameterNames.PARALLEL_TIMEOUTFORCED_PROP, - Double.toString( getParallelTestsTimeoutForcedInSeconds() ) ); - getProperties().setProperty( ProviderParameterNames.PARALLEL_OPTIMIZE_PROP, - Boolean.toString( isParallelOptimized() ) ); + private void convertJunitCoreParameters() throws MojoExecutionException { + checkThreadCountEntity(getThreadCountSuites(), "suites"); + checkThreadCountEntity(getThreadCountClasses(), "classes"); + checkThreadCountEntity(getThreadCountMethods(), "methods"); + + String usedParallel = (getParallel() != null) ? getParallel() : "none"; + + if (!"none".equals(usedParallel)) { + checkNonForkedThreads(parallel); + } + + getProperties().setProperty(ProviderParameterNames.PARALLEL_PROP, usedParallel); + if (this.getThreadCount() > 0) { + getProperties().setProperty(ProviderParameterNames.THREADCOUNT_PROP, Integer.toString(getThreadCount())); + } + getProperties().setProperty("perCoreThreadCount", Boolean.toString(getPerCoreThreadCount())); + getProperties().setProperty("useUnlimitedThreads", Boolean.toString(getUseUnlimitedThreads())); + getProperties() + .setProperty(ProviderParameterNames.THREADCOUNTSUITES_PROP, Integer.toString(getThreadCountSuites())); + getProperties() + .setProperty(ProviderParameterNames.THREADCOUNTCLASSES_PROP, Integer.toString(getThreadCountClasses())); + getProperties() + .setProperty(ProviderParameterNames.THREADCOUNTMETHODS_PROP, Integer.toString(getThreadCountMethods())); + getProperties() + .setProperty( + ProviderParameterNames.PARALLEL_TIMEOUT_PROP, + Double.toString(getParallelTestsTimeoutInSeconds())); + getProperties() + .setProperty( + ProviderParameterNames.PARALLEL_TIMEOUTFORCED_PROP, + Double.toString(getParallelTestsTimeoutForcedInSeconds())); + getProperties() + .setProperty(ProviderParameterNames.PARALLEL_OPTIMIZE_PROP, Boolean.toString(isParallelOptimized())); String message = "parallel='" + usedParallel + '\'' - + ", perCoreThreadCount=" + getPerCoreThreadCount() - + ", threadCount=" + getThreadCount() - + ", useUnlimitedThreads=" + getUseUnlimitedThreads() - + ", threadCountSuites=" + getThreadCountSuites() - + ", threadCountClasses=" + getThreadCountClasses() - + ", threadCountMethods=" + getThreadCountMethods() - + ", parallelOptimized=" + isParallelOptimized(); - - logDebugOrCliShowErrors( message ); - } - - private void checkNonForkedThreads( String parallel ) throws MojoExecutionException - { - if ( "suites".equals( parallel ) ) - { - if ( !( getUseUnlimitedThreads() || getThreadCount() > 0 ^ getThreadCountSuites() > 0 ) ) - { + + ", perCoreThreadCount=" + getPerCoreThreadCount() + + ", threadCount=" + getThreadCount() + + ", useUnlimitedThreads=" + getUseUnlimitedThreads() + + ", threadCountSuites=" + getThreadCountSuites() + + ", threadCountClasses=" + getThreadCountClasses() + + ", threadCountMethods=" + getThreadCountMethods() + + ", parallelOptimized=" + isParallelOptimized(); + + logDebugOrCliShowErrors(message); + } + + private void checkNonForkedThreads(String parallel) throws MojoExecutionException { + if ("suites".equals(parallel)) { + if (!(getUseUnlimitedThreads() || getThreadCount() > 0 ^ getThreadCountSuites() > 0)) { throw new MojoExecutionException( - "Use threadCount or threadCountSuites > 0 or useUnlimitedThreads=true for parallel='suites'" ); + "Use threadCount or threadCountSuites > 0 or useUnlimitedThreads=true for parallel='suites'"); } - setThreadCountClasses( 0 ); - setThreadCountMethods( 0 ); - } - else if ( "classes".equals( parallel ) ) - { - if ( !( getUseUnlimitedThreads() || getThreadCount() > 0 ^ getThreadCountClasses() > 0 ) ) - { + setThreadCountClasses(0); + setThreadCountMethods(0); + } else if ("classes".equals(parallel)) { + if (!(getUseUnlimitedThreads() || getThreadCount() > 0 ^ getThreadCountClasses() > 0)) { throw new MojoExecutionException( - "Use threadCount or threadCountClasses > 0 or useUnlimitedThreads=true for parallel='classes'" - ); + "Use threadCount or threadCountClasses > 0 or useUnlimitedThreads=true for parallel='classes'"); } - setThreadCountSuites( 0 ); - setThreadCountMethods( 0 ); - } - else if ( "methods".equals( parallel ) ) - { - if ( !( getUseUnlimitedThreads() || getThreadCount() > 0 ^ getThreadCountMethods() > 0 ) ) - { + setThreadCountSuites(0); + setThreadCountMethods(0); + } else if ("methods".equals(parallel)) { + if (!(getUseUnlimitedThreads() || getThreadCount() > 0 ^ getThreadCountMethods() > 0)) { throw new MojoExecutionException( - "Use threadCount or threadCountMethods > 0 or useUnlimitedThreads=true for parallel='methods'" - ); + "Use threadCount or threadCountMethods > 0 or useUnlimitedThreads=true for parallel='methods'"); } - setThreadCountSuites( 0 ); - setThreadCountClasses( 0 ); - } - else if ( "suitesAndClasses".equals( parallel ) ) - { - if ( !( getUseUnlimitedThreads() + setThreadCountSuites(0); + setThreadCountClasses(0); + } else if ("suitesAndClasses".equals(parallel)) { + if (!(getUseUnlimitedThreads() || onlyThreadCount() - || getThreadCountSuites() > 0 && getThreadCountClasses() > 0 - && getThreadCount() == 0 && getThreadCountMethods() == 0 - || getThreadCount() > 0 && getThreadCountSuites() > 0 && getThreadCountClasses() > 0 - && getThreadCountMethods() == 0 - || getThreadCount() > 0 && getThreadCountSuites() > 0 && getThreadCount() > getThreadCountSuites() - && getThreadCountClasses() == 0 && getThreadCountMethods() == 0 ) ) - { - throw new MojoExecutionException( "Use useUnlimitedThreads=true, " + || getThreadCountSuites() > 0 + && getThreadCountClasses() > 0 + && getThreadCount() == 0 + && getThreadCountMethods() == 0 + || getThreadCount() > 0 + && getThreadCountSuites() > 0 + && getThreadCountClasses() > 0 + && getThreadCountMethods() == 0 + || getThreadCount() > 0 + && getThreadCountSuites() > 0 + && getThreadCount() > getThreadCountSuites() + && getThreadCountClasses() == 0 + && getThreadCountMethods() == 0)) { + throw new MojoExecutionException("Use useUnlimitedThreads=true, " + "or only threadCount > 0, " + "or (threadCountSuites > 0 and threadCountClasses > 0), " + "or (threadCount > 0 and threadCountSuites > 0 and threadCountClasses > 0) " + "or (threadCount > 0 and threadCountSuites > 0 and threadCount > threadCountSuites) " - + "for parallel='suitesAndClasses' or 'both'" ); + + "for parallel='suitesAndClasses' or 'both'"); } - setThreadCountMethods( 0 ); - } - else if ( "suitesAndMethods".equals( parallel ) ) - { - if ( !( getUseUnlimitedThreads() + setThreadCountMethods(0); + } else if ("suitesAndMethods".equals(parallel)) { + if (!(getUseUnlimitedThreads() || onlyThreadCount() - || getThreadCountSuites() > 0 && getThreadCountMethods() > 0 - && getThreadCount() == 0 && getThreadCountClasses() == 0 - || getThreadCount() > 0 && getThreadCountSuites() > 0 && getThreadCountMethods() > 0 - && getThreadCountClasses() == 0 - || getThreadCount() > 0 && getThreadCountSuites() > 0 && getThreadCount() > getThreadCountSuites() - && getThreadCountClasses() == 0 && getThreadCountMethods() == 0 ) ) - { - throw new MojoExecutionException( "Use useUnlimitedThreads=true, " + || getThreadCountSuites() > 0 + && getThreadCountMethods() > 0 + && getThreadCount() == 0 + && getThreadCountClasses() == 0 + || getThreadCount() > 0 + && getThreadCountSuites() > 0 + && getThreadCountMethods() > 0 + && getThreadCountClasses() == 0 + || getThreadCount() > 0 + && getThreadCountSuites() > 0 + && getThreadCount() > getThreadCountSuites() + && getThreadCountClasses() == 0 + && getThreadCountMethods() == 0)) { + throw new MojoExecutionException("Use useUnlimitedThreads=true, " + "or only threadCount > 0, " + "or (threadCountSuites > 0 and threadCountMethods > 0), " + "or (threadCount > 0 and threadCountSuites > 0 and threadCountMethods > 0), " + "or (threadCount > 0 and threadCountSuites > 0 and threadCount > threadCountSuites) " - + "for parallel='suitesAndMethods'" ); + + "for parallel='suitesAndMethods'"); } - setThreadCountClasses( 0 ); - } - else if ( "both".equals( parallel ) || "classesAndMethods".equals( parallel ) ) - { - if ( !( getUseUnlimitedThreads() + setThreadCountClasses(0); + } else if ("both".equals(parallel) || "classesAndMethods".equals(parallel)) { + if (!(getUseUnlimitedThreads() || onlyThreadCount() - || getThreadCountClasses() > 0 && getThreadCountMethods() > 0 - && getThreadCount() == 0 && getThreadCountSuites() == 0 - || getThreadCount() > 0 && getThreadCountClasses() > 0 && getThreadCountMethods() > 0 - && getThreadCountSuites() == 0 - || getThreadCount() > 0 && getThreadCountClasses() > 0 && getThreadCount() > getThreadCountClasses() - && getThreadCountSuites() == 0 && getThreadCountMethods() == 0 ) ) - { - throw new MojoExecutionException( "Use useUnlimitedThreads=true, " + || getThreadCountClasses() > 0 + && getThreadCountMethods() > 0 + && getThreadCount() == 0 + && getThreadCountSuites() == 0 + || getThreadCount() > 0 + && getThreadCountClasses() > 0 + && getThreadCountMethods() > 0 + && getThreadCountSuites() == 0 + || getThreadCount() > 0 + && getThreadCountClasses() > 0 + && getThreadCount() > getThreadCountClasses() + && getThreadCountSuites() == 0 + && getThreadCountMethods() == 0)) { + throw new MojoExecutionException("Use useUnlimitedThreads=true, " + "or only threadCount > 0, " + "or (threadCountClasses > 0 and threadCountMethods > 0), " + "or (threadCount > 0 and threadCountClasses > 0 and threadCountMethods > 0), " + "or (threadCount > 0 and threadCountClasses > 0 and threadCount > threadCountClasses) " - + "for parallel='both' or parallel='classesAndMethods'" ); + + "for parallel='both' or parallel='classesAndMethods'"); } - setThreadCountSuites( 0 ); - } - else if ( "all".equals( parallel ) ) - { - if ( !( getUseUnlimitedThreads() + setThreadCountSuites(0); + } else if ("all".equals(parallel)) { + if (!(getUseUnlimitedThreads() || onlyThreadCount() || getThreadCountSuites() > 0 && getThreadCountClasses() > 0 && getThreadCountMethods() > 0 - || getThreadCount() > 0 && getThreadCountSuites() > 0 && getThreadCountClasses() > 0 - && getThreadCountMethods() == 0 - && getThreadCount() > ( getThreadCountSuites() + getThreadCountClasses() ) ) ) - { - throw new MojoExecutionException( "Use useUnlimitedThreads=true, " + || getThreadCount() > 0 + && getThreadCountSuites() > 0 + && getThreadCountClasses() > 0 + && getThreadCountMethods() == 0 + && getThreadCount() > (getThreadCountSuites() + getThreadCountClasses()))) { + throw new MojoExecutionException("Use useUnlimitedThreads=true, " + "or only threadCount > 0, " + "or (threadCountSuites > 0 and threadCountClasses > 0 and threadCountMethods > 0), " + "or every thread-count is specified, " + "or (threadCount > 0 and threadCountSuites > 0 and threadCountClasses > 0 " + "and threadCount > threadCountSuites + threadCountClasses) " - + "for parallel='all'" ); + + "for parallel='all'"); } - } - else - { - throw new MojoExecutionException( "Illegal parallel='" + parallel + "'" ); + } else { + throw new MojoExecutionException("Illegal parallel='" + parallel + "'"); } } - private boolean onlyThreadCount() - { - return getThreadCount() > 0 && getThreadCountSuites() == 0 && getThreadCountClasses() == 0 + private boolean onlyThreadCount() { + return getThreadCount() > 0 + && getThreadCountSuites() == 0 + && getThreadCountClasses() == 0 && getThreadCountMethods() == 0; } - private static void checkThreadCountEntity( int count, String entity ) - throws MojoExecutionException - { - if ( count < 0 ) - { - throw new MojoExecutionException( - "parallel maven execution does not allow negative thread-count" + entity ); + private static void checkThreadCountEntity(int count, String entity) throws MojoExecutionException { + if (count < 0) { + throw new MojoExecutionException("parallel maven execution does not allow negative thread-count" + entity); } } - private boolean isJunit47Compatible( Artifact artifact ) - { - return isWithinVersionSpec( artifact, "[4.7,)" ); + private boolean isJunit47Compatible(Artifact artifact) { + return isWithinVersionSpec(artifact, "[4.7,)"); } - private boolean isAnyJunit4( Artifact artifact ) - { - return isWithinVersionSpec( artifact, "[4.0,)" ); + private boolean isAnyJunit4(Artifact artifact) { + return isWithinVersionSpec(artifact, "[4.0,)"); } - protected boolean isForking() - { + protected boolean isForking() { return 0 < getEffectiveForkCount(); } - private List getRunOrders() - { + private List getRunOrders() { String runOrderString = getRunOrder(); - RunOrder[] runOrder = runOrderString == null ? RunOrder.DEFAULT : RunOrder.valueOfMulti( runOrderString ); - return asList( runOrder ); + RunOrder[] runOrder = runOrderString == null ? RunOrder.DEFAULT : RunOrder.valueOfMulti(runOrderString); + return asList(runOrder); } - private boolean requiresRunHistory() - { + private boolean requiresRunHistory() { final List runOrders = getRunOrders(); - return runOrders.contains( RunOrder.BALANCED ) || runOrders.contains( RunOrder.FAILEDFIRST ); + return runOrders.contains(RunOrder.BALANCED) || runOrders.contains(RunOrder.FAILEDFIRST); } - private PluginFailureReason getEffectiveFailIfNoTests() - { - if ( isSpecificTestSpecified() ) - { + private PluginFailureReason getEffectiveFailIfNoTests() { + if (isSpecificTestSpecified()) { return getFailIfNoSpecifiedTests() ? COULD_NOT_RUN_SPECIFIED_TESTS : NONE; - } - else - { + } else { return getFailIfNoTests() ? COULD_NOT_RUN_DEFAULT_TESTS : NONE; } } - private ProviderConfiguration createProviderConfiguration( RunOrderParameters runOrderParameters ) - throws MojoExecutionException, MojoFailureException - { + private ProviderConfiguration createProviderConfiguration(RunOrderParameters runOrderParameters) + throws MojoExecutionException, MojoFailureException { final ReporterConfiguration reporterConfiguration = - new ReporterConfiguration( getReportsDirectory(), isTrimStackTrace() ); + new ReporterConfiguration(getReportsDirectory(), isTrimStackTrace()); final Artifact testNgArtifact = getTestNgArtifact(); final boolean isTestNg = testNgArtifact != null; final TestArtifactInfo testNg = - isTestNg ? new TestArtifactInfo( testNgArtifact.getVersion(), testNgArtifact.getClassifier() ) : null; - final TestRequest testSuiteDefinition = new TestRequest( suiteXmlFiles(), - getTestSourceDirectory(), - getSpecificTests(), - getRerunFailingTestsCount() ); + isTestNg ? new TestArtifactInfo(testNgArtifact.getVersion(), testNgArtifact.getClassifier()) : null; + final TestRequest testSuiteDefinition = new TestRequest( + suiteXmlFiles(), getTestSourceDirectory(), getSpecificTests(), getRerunFailingTestsCount()); final boolean actualFailIfNoTests; DirectoryScannerParameters directoryScannerParameters = null; - if ( hasSuiteXmlFiles() && !isSpecificTestSpecified() ) - { + if (hasSuiteXmlFiles() && !isSpecificTestSpecified()) { actualFailIfNoTests = getFailIfNoTests(); - if ( !isTestNg ) - { - throw new MojoExecutionException( "suiteXmlFiles is configured, but there is no TestNG dependency" ); + if (!isTestNg) { + throw new MojoExecutionException("suiteXmlFiles is configured, but there is no TestNG dependency"); } - } - else - { + } else { // @todo remove these three params and use DirectoryScannerParameters to pass into DirectoryScanner only // @todo or remove it in next major version :: 3.0 // @todo remove deprecated methods in ProviderParameters => included|excluded|specificTests not needed here @@ -1839,136 +1679,141 @@ private ProviderConfiguration createProviderConfiguration( RunOrderParameters ru // Collections.emptyList(); behaves same List specificTests = Collections.emptyList(); - directoryScannerParameters = - new DirectoryScannerParameters( getTestClassesDirectory(), actualIncludes, actualExcludes, - specificTests, getRunOrder() ); + directoryScannerParameters = new DirectoryScannerParameters( + getTestClassesDirectory(), actualIncludes, actualExcludes, specificTests, getRunOrder()); } - Map providerProperties = toStringProperties( getProperties() ); + Map providerProperties = toStringProperties(getProperties()); - return new ProviderConfiguration( directoryScannerParameters, runOrderParameters, - reporterConfiguration, - testNg, // Not really used in provider. Limited to de/serializer. - testSuiteDefinition, providerProperties, null, - false, cli, getSkipAfterFailureCount(), - Shutdown.parameterOf( getShutdown() ), - getForkedProcessExitTimeoutInSeconds() ); + return new ProviderConfiguration( + directoryScannerParameters, + runOrderParameters, + reporterConfiguration, + testNg, // Not really used in provider. Limited to de/serializer. + testSuiteDefinition, + providerProperties, + null, + false, + cli, + getSkipAfterFailureCount(), + Shutdown.parameterOf(getShutdown()), + getForkedProcessExitTimeoutInSeconds()); } - private static Map toStringProperties( Properties properties ) - { - Map h = new ConcurrentHashMap<>( properties.size() ); - for ( Enumeration e = properties.keys() ; e.hasMoreElements() ; ) - { + private static Map toStringProperties(Properties properties) { + Map h = new ConcurrentHashMap<>(properties.size()); + for (Enumeration e = properties.keys(); e.hasMoreElements(); ) { Object k = e.nextElement(); - Object v = properties.get( k ); - if ( k.getClass() == String.class && v.getClass() == String.class ) - { - h.put( (String) k, (String) v ); + Object v = properties.get(k); + if (k.getClass() == String.class && v.getClass() == String.class) { + h.put((String) k, (String) v); } } return h; } - private File getStatisticsFile( String configurationHash ) - { - return new File( getBasedir(), ".surefire-" + configurationHash ); + private File getStatisticsFile(String configurationHash) { + return new File(getBasedir(), ".surefire-" + configurationHash); } - private StartupConfiguration createStartupConfiguration( @Nonnull ProviderInfo provider, boolean isForking, - @Nonnull ClassLoaderConfiguration classLoaderConfiguration, - @Nonnull DefaultScanResult scanResult, - @Nonnull TestClassPath testClasspathWrapper, - @Nonnull Platform platform, - @Nonnull ResolvePathResultWrapper resolvedJavaModularity ) - throws MojoExecutionException - { - try - { - if ( isForking && canExecuteProviderWithModularPath( platform, resolvedJavaModularity ) ) - { + private StartupConfiguration createStartupConfiguration( + @Nonnull ProviderInfo provider, + boolean isForking, + @Nonnull ClassLoaderConfiguration classLoaderConfiguration, + @Nonnull DefaultScanResult scanResult, + @Nonnull TestClassPath testClasspathWrapper, + @Nonnull Platform platform, + @Nonnull ResolvePathResultWrapper resolvedJavaModularity) + throws MojoExecutionException { + try { + if (isForking && canExecuteProviderWithModularPath(platform, resolvedJavaModularity)) { File jdkHome = platform.getJdkExecAttributesForTests().getJdkHome(); - return newStartupConfigWithModularPath( classLoaderConfiguration, provider, resolvedJavaModularity, - scanResult, jdkHome.getAbsolutePath(), testClasspathWrapper ); - } - else - { - return newStartupConfigWithClasspath( classLoaderConfiguration, provider, testClasspathWrapper ); + return newStartupConfigWithModularPath( + classLoaderConfiguration, + provider, + resolvedJavaModularity, + scanResult, + jdkHome.getAbsolutePath(), + testClasspathWrapper); + } else { + return newStartupConfigWithClasspath(classLoaderConfiguration, provider, testClasspathWrapper); } - } - catch ( IOException e ) - { - throw new MojoExecutionException( e.getMessage(), e ); + } catch (IOException e) { + throw new MojoExecutionException(e.getMessage(), e); } } private StartupConfiguration newStartupConfigWithClasspath( - @Nonnull ClassLoaderConfiguration classLoaderConfiguration, @Nonnull ProviderInfo providerInfo, - @Nonnull TestClassPath testClasspathWrapper ) throws MojoExecutionException - { + @Nonnull ClassLoaderConfiguration classLoaderConfiguration, + @Nonnull ProviderInfo providerInfo, + @Nonnull TestClassPath testClasspathWrapper) + throws MojoExecutionException { Classpath testClasspath = testClasspathWrapper.toClasspath(); Set providerArtifacts = providerInfo.getProviderClasspath(); String providerName = providerInfo.getProviderName(); - Classpath providerClasspath = classpathCache.getCachedClassPath( providerName ); - if ( providerClasspath == null ) - { - providerClasspath = classpathCache.setCachedClasspath( providerName, providerArtifacts ); - } - - getConsoleLogger().debug( testClasspath.getLogMessage( "test classpath:" ) ); - getConsoleLogger().debug( providerClasspath.getLogMessage( "provider classpath:" ) ); - getConsoleLogger().debug( testClasspath.getCompactLogMessage( "test(compact) classpath:" ) ); - getConsoleLogger().debug( providerClasspath.getCompactLogMessage( "provider(compact) classpath:" ) ); - - Artifact[] additionalInProcArtifacts = { getCommonArtifact(), getBooterArtifact(), getExtensionsArtifact(), - getApiArtifact(), getSpiArtifact(), getLoggerApiArtifact(), getSurefireSharedUtilsArtifact() }; - Set inProcArtifacts = retainInProcArtifactsUnique( providerArtifacts, additionalInProcArtifacts ); - Classpath inProcClasspath = createInProcClasspath( providerClasspath, inProcArtifacts ); - getConsoleLogger().debug( inProcClasspath.getLogMessage( "in-process classpath:" ) ); - getConsoleLogger().debug( inProcClasspath.getCompactLogMessage( "in-process(compact) classpath:" ) ); - - ClasspathConfiguration classpathConfiguration = new ClasspathConfiguration( testClasspath, providerClasspath, - inProcClasspath, effectiveIsEnableAssertions(), isChildDelegation() ); - ProviderRequirements forkRequirements = new ProviderRequirements( false, false, false ); - return new StartupConfiguration( providerName, classpathConfiguration, classLoaderConfiguration, - ProcessCheckerType.toEnum( getEnableProcessChecker() ), providerInfo.getJpmsArguments( forkRequirements ) ); - } - - private static Set retainInProcArtifactsUnique( Set providerArtifacts, - Artifact... inPluginArtifacts ) - { + Classpath providerClasspath = classpathCache.getCachedClassPath(providerName); + if (providerClasspath == null) { + providerClasspath = classpathCache.setCachedClasspath(providerName, providerArtifacts); + } + + getConsoleLogger().debug(testClasspath.getLogMessage("test classpath:")); + getConsoleLogger().debug(providerClasspath.getLogMessage("provider classpath:")); + getConsoleLogger().debug(testClasspath.getCompactLogMessage("test(compact) classpath:")); + getConsoleLogger().debug(providerClasspath.getCompactLogMessage("provider(compact) classpath:")); + + Artifact[] additionalInProcArtifacts = { + getCommonArtifact(), + getBooterArtifact(), + getExtensionsArtifact(), + getApiArtifact(), + getSpiArtifact(), + getLoggerApiArtifact(), + getSurefireSharedUtilsArtifact() + }; + Set inProcArtifacts = retainInProcArtifactsUnique(providerArtifacts, additionalInProcArtifacts); + Classpath inProcClasspath = createInProcClasspath(providerClasspath, inProcArtifacts); + getConsoleLogger().debug(inProcClasspath.getLogMessage("in-process classpath:")); + getConsoleLogger().debug(inProcClasspath.getCompactLogMessage("in-process(compact) classpath:")); + + ClasspathConfiguration classpathConfiguration = new ClasspathConfiguration( + testClasspath, providerClasspath, inProcClasspath, effectiveIsEnableAssertions(), isChildDelegation()); + ProviderRequirements forkRequirements = new ProviderRequirements(false, false, false); + return new StartupConfiguration( + providerName, + classpathConfiguration, + classLoaderConfiguration, + ProcessCheckerType.toEnum(getEnableProcessChecker()), + providerInfo.getJpmsArguments(forkRequirements)); + } + + private static Set retainInProcArtifactsUnique( + Set providerArtifacts, Artifact... inPluginArtifacts) { Set result = new LinkedHashSet<>(); - for ( Artifact inPluginArtifact : inPluginArtifacts ) - { + for (Artifact inPluginArtifact : inPluginArtifacts) { boolean contains = false; - for ( Artifact providerArtifact : providerArtifacts ) - { - if ( hasGroupArtifactId( providerArtifact.getGroupId(), providerArtifact.getArtifactId(), - inPluginArtifact ) ) - { + for (Artifact providerArtifact : providerArtifacts) { + if (hasGroupArtifactId( + providerArtifact.getGroupId(), providerArtifact.getArtifactId(), inPluginArtifact)) { contains = true; break; } } - if ( !contains ) - { - result.add( inPluginArtifact ); + if (!contains) { + result.add(inPluginArtifact); } } return result; } - private static boolean hasGroupArtifactId( String groupId, String artifactId, Artifact artifact ) - { - return groupId.equals( artifact.getGroupId() ) && artifactId.equals( artifact.getArtifactId() ); + private static boolean hasGroupArtifactId(String groupId, String artifactId, Artifact artifact) { + return groupId.equals(artifact.getGroupId()) && artifactId.equals(artifact.getArtifactId()); } - private static Classpath createInProcClasspath( Classpath providerClasspath, Set newArtifacts ) - { + private static Classpath createInProcClasspath(Classpath providerClasspath, Set newArtifacts) { Classpath inprocClasspath = providerClasspath.clone(); - for ( Artifact newArtifact : newArtifacts ) - { - inprocClasspath = inprocClasspath.addClassPathElementUrl( newArtifact.getFile().getAbsolutePath() ); + for (Artifact newArtifact : newArtifacts) { + inprocClasspath = + inprocClasspath.addClassPathElementUrl(newArtifact.getFile().getAbsolutePath()); } return inprocClasspath; } @@ -1977,203 +1822,203 @@ private static Classpath createInProcClasspath( Classpath providerClasspath, Set * For testing purposes - Mockito. * @return plexus component */ - private LocationManager getLocationManager() - { + private LocationManager getLocationManager() { return locationManager; } private StartupConfiguration newStartupConfigWithModularPath( - @Nonnull ClassLoaderConfiguration classLoaderConfiguration, @Nonnull ProviderInfo providerInfo, - @Nonnull ResolvePathResultWrapper moduleDescriptor, @Nonnull DefaultScanResult scanResult, - @Nonnull String javaHome, @Nonnull TestClassPath testClasspathWrapper ) - throws MojoExecutionException, IOException - { + @Nonnull ClassLoaderConfiguration classLoaderConfiguration, + @Nonnull ProviderInfo providerInfo, + @Nonnull ResolvePathResultWrapper moduleDescriptor, + @Nonnull DefaultScanResult scanResult, + @Nonnull String javaHome, + @Nonnull TestClassPath testClasspathWrapper) + throws MojoExecutionException, IOException { boolean isMainDescriptor = moduleDescriptor.isMainModuleDescriptor(); - JavaModuleDescriptor javaModuleDescriptor = moduleDescriptor.getResolvePathResult().getModuleDescriptor(); + JavaModuleDescriptor javaModuleDescriptor = + moduleDescriptor.getResolvePathResult().getModuleDescriptor(); SortedSet packages = new TreeSet<>(); Classpath testClasspath = testClasspathWrapper.toClasspath(); Set providerArtifacts = providerInfo.getProviderClasspath(); String providerName = providerInfo.getProviderName(); - Classpath providerClasspath = classpathCache.getCachedClassPath( providerName ); - if ( providerClasspath == null ) - { - providerClasspath = classpathCache.setCachedClasspath( providerName, providerArtifacts ); + Classpath providerClasspath = classpathCache.getCachedClassPath(providerName); + if (providerClasspath == null) { + providerClasspath = classpathCache.setCachedClasspath(providerName, providerArtifacts); } final ProviderRequirements providerRequirements; final Classpath testModulepath; - if ( isMainDescriptor ) - { - providerRequirements = new ProviderRequirements( true, true, false ); - ResolvePathsRequest req = ResolvePathsRequest.ofStrings( testClasspath.getClassPath() ) - .setIncludeAllProviders( true ) - .setJdkHome( javaHome ) - .setIncludeStatic( true ) - .setModuleDescriptor( javaModuleDescriptor ); - - ResolvePathsResult result = getLocationManager().resolvePaths( req ); - for ( Entry entry : result.getPathExceptions().entrySet() ) - { + if (isMainDescriptor) { + providerRequirements = new ProviderRequirements(true, true, false); + ResolvePathsRequest req = ResolvePathsRequest.ofStrings(testClasspath.getClassPath()) + .setIncludeAllProviders(true) + .setJdkHome(javaHome) + .setIncludeStatic(true) + .setModuleDescriptor(javaModuleDescriptor); + + ResolvePathsResult result = getLocationManager().resolvePaths(req); + for (Entry entry : result.getPathExceptions().entrySet()) { // Probably JDK version < 9. Other known causes: passing a non-jar or a corrupted jar. - getConsoleLogger() - .warning( "Exception for '" + entry.getKey() + "'.", entry.getValue() ); + getConsoleLogger().warning("Exception for '" + entry.getKey() + "'.", entry.getValue()); } - testClasspath = new Classpath( result.getClasspathElements() ); - testModulepath = new Classpath( result.getModulepathElements().keySet() ); + testClasspath = new Classpath(result.getClasspathElements()); + testModulepath = new Classpath(result.getModulepathElements().keySet()); - for ( String className : scanResult.getClasses() ) - { - packages.add( substringBeforeLast( className, "." ) ); + for (String className : scanResult.getClasses()) { + packages.add(substringBeforeLast(className, ".")); } - } - else - { - providerRequirements = new ProviderRequirements( true, false, true ); + } else { + providerRequirements = new ProviderRequirements(true, false, true); testModulepath = testClasspath; testClasspath = emptyClasspath(); } - getConsoleLogger().debug( "main module descriptor name: " + javaModuleDescriptor.name() ); + getConsoleLogger().debug("main module descriptor name: " + javaModuleDescriptor.name()); - ModularClasspath modularClasspath = new ModularClasspath( javaModuleDescriptor.name(), - testModulepath.getClassPath(), packages, isMainDescriptor ? getTestClassesDirectory() : null, - isMainDescriptor ); + ModularClasspath modularClasspath = new ModularClasspath( + javaModuleDescriptor.name(), + testModulepath.getClassPath(), + packages, + isMainDescriptor ? getTestClassesDirectory() : null, + isMainDescriptor); - Artifact[] additionalInProcArtifacts = { getCommonArtifact(), getBooterArtifact(), getExtensionsArtifact(), - getApiArtifact(), getSpiArtifact(), getLoggerApiArtifact(), getSurefireSharedUtilsArtifact() }; - Set inProcArtifacts = retainInProcArtifactsUnique( providerArtifacts, additionalInProcArtifacts ); - Classpath inProcClasspath = createInProcClasspath( providerClasspath, inProcArtifacts ); + Artifact[] additionalInProcArtifacts = { + getCommonArtifact(), + getBooterArtifact(), + getExtensionsArtifact(), + getApiArtifact(), + getSpiArtifact(), + getLoggerApiArtifact(), + getSurefireSharedUtilsArtifact() + }; + Set inProcArtifacts = retainInProcArtifactsUnique(providerArtifacts, additionalInProcArtifacts); + Classpath inProcClasspath = createInProcClasspath(providerClasspath, inProcArtifacts); - ModularClasspathConfiguration classpathConfiguration = new ModularClasspathConfiguration( modularClasspath, - testClasspath, providerClasspath, inProcClasspath, effectiveIsEnableAssertions(), isChildDelegation() ); + ModularClasspathConfiguration classpathConfiguration = new ModularClasspathConfiguration( + modularClasspath, + testClasspath, + providerClasspath, + inProcClasspath, + effectiveIsEnableAssertions(), + isChildDelegation()); - getConsoleLogger().debug( testClasspath.getLogMessage( "test classpath:" ) ); - getConsoleLogger().debug( testModulepath.getLogMessage( "test modulepath:" ) ); - getConsoleLogger().debug( providerClasspath.getLogMessage( "provider classpath:" ) ); - getConsoleLogger().debug( testClasspath.getCompactLogMessage( "test(compact) classpath:" ) ); - getConsoleLogger().debug( testModulepath.getCompactLogMessage( "test(compact) modulepath:" ) ); - getConsoleLogger().debug( providerClasspath.getCompactLogMessage( "provider(compact) classpath:" ) ); - getConsoleLogger().debug( inProcClasspath.getLogMessage( "in-process classpath:" ) ); - getConsoleLogger().debug( inProcClasspath.getCompactLogMessage( "in-process(compact) classpath:" ) ); + getConsoleLogger().debug(testClasspath.getLogMessage("test classpath:")); + getConsoleLogger().debug(testModulepath.getLogMessage("test modulepath:")); + getConsoleLogger().debug(providerClasspath.getLogMessage("provider classpath:")); + getConsoleLogger().debug(testClasspath.getCompactLogMessage("test(compact) classpath:")); + getConsoleLogger().debug(testModulepath.getCompactLogMessage("test(compact) modulepath:")); + getConsoleLogger().debug(providerClasspath.getCompactLogMessage("provider(compact) classpath:")); + getConsoleLogger().debug(inProcClasspath.getLogMessage("in-process classpath:")); + getConsoleLogger().debug(inProcClasspath.getCompactLogMessage("in-process(compact) classpath:")); - ProcessCheckerType processCheckerType = ProcessCheckerType.toEnum( getEnableProcessChecker() ); - List jpmsArgs = providerInfo.getJpmsArguments( providerRequirements ); - return new StartupConfiguration( providerName, classpathConfiguration, classLoaderConfiguration, - processCheckerType, jpmsArgs ); + ProcessCheckerType processCheckerType = ProcessCheckerType.toEnum(getEnableProcessChecker()); + List jpmsArgs = providerInfo.getJpmsArguments(providerRequirements); + return new StartupConfiguration( + providerName, classpathConfiguration, classLoaderConfiguration, processCheckerType, jpmsArgs); } - private Artifact getCommonArtifact() - { - return getPluginArtifactMap().get( "org.apache.maven.surefire:maven-surefire-common" ); + private Artifact getCommonArtifact() { + return getPluginArtifactMap().get("org.apache.maven.surefire:maven-surefire-common"); } - private Artifact getExtensionsArtifact() - { - return getPluginArtifactMap().get( "org.apache.maven.surefire:surefire-extensions-api" ); + private Artifact getExtensionsArtifact() { + return getPluginArtifactMap().get("org.apache.maven.surefire:surefire-extensions-api"); } - private Artifact getSpiArtifact() - { - return getPluginArtifactMap().get( "org.apache.maven.surefire:surefire-extensions-spi" ); + private Artifact getSpiArtifact() { + return getPluginArtifactMap().get("org.apache.maven.surefire:surefire-extensions-spi"); } - private Artifact getApiArtifact() - { - return getPluginArtifactMap().get( "org.apache.maven.surefire:surefire-api" ); + private Artifact getApiArtifact() { + return getPluginArtifactMap().get("org.apache.maven.surefire:surefire-api"); } - private Artifact getSurefireSharedUtilsArtifact() - { - return getPluginArtifactMap().get( "org.apache.maven.surefire:surefire-shared-utils" ); + private Artifact getSurefireSharedUtilsArtifact() { + return getPluginArtifactMap().get("org.apache.maven.surefire:surefire-shared-utils"); } - private Artifact getLoggerApiArtifact() - { - return getPluginArtifactMap().get( "org.apache.maven.surefire:surefire-logger-api" ); + private Artifact getLoggerApiArtifact() { + return getPluginArtifactMap().get("org.apache.maven.surefire:surefire-logger-api"); } - private Artifact getBooterArtifact() - { - return getPluginArtifactMap().get( "org.apache.maven.surefire:surefire-booter" ); + private Artifact getBooterArtifact() { + return getPluginArtifactMap().get("org.apache.maven.surefire:surefire-booter"); } - private Artifact getShadefireArtifact() - { - return getPluginArtifactMap().get( "org.apache.maven.surefire:surefire-shadefire" ); + private Artifact getShadefireArtifact() { + return getPluginArtifactMap().get("org.apache.maven.surefire:surefire-shadefire"); } - private StartupReportConfiguration getStartupReportConfiguration( String configChecksum, boolean isForking ) - { - SurefireStatelessReporter xmlReporter = - statelessTestsetReporter == null - ? new SurefireStatelessReporter( /*todo call def. constr.*/ isDisableXmlReport(), "3.0" ) - : statelessTestsetReporter; + private StartupReportConfiguration getStartupReportConfiguration(String configChecksum, boolean isForking) { + SurefireStatelessReporter xmlReporter = statelessTestsetReporter == null + ? new SurefireStatelessReporter(/*todo call def. constr.*/ isDisableXmlReport(), "3.0") + : statelessTestsetReporter; - xmlReporter.setDisable( isDisableXmlReport() ); // todo change to Boolean in the version 3.0.0-M6 + xmlReporter.setDisable(isDisableXmlReport()); // todo change to Boolean in the version 3.0.0-M6 SurefireConsoleOutputReporter outReporter = consoleOutputReporter == null ? new SurefireConsoleOutputReporter() : consoleOutputReporter; - SurefireStatelessTestsetInfoReporter testsetReporter = - statelessTestsetInfoReporter == null - ? new SurefireStatelessTestsetInfoReporter() : statelessTestsetInfoReporter; - - return new StartupReportConfiguration( isUseFile(), isPrintSummary(), getReportFormat(), - isRedirectTestOutputToFile(), - getReportsDirectory(), isTrimStackTrace(), getReportNameSuffix(), - getStatisticsFile( configChecksum ), requiresRunHistory(), - getRerunFailingTestsCount(), getReportSchemaLocation(), getEncoding(), - isForking, xmlReporter, outReporter, testsetReporter ); + SurefireStatelessTestsetInfoReporter testsetReporter = statelessTestsetInfoReporter == null + ? new SurefireStatelessTestsetInfoReporter() + : statelessTestsetInfoReporter; + + return new StartupReportConfiguration( + isUseFile(), + isPrintSummary(), + getReportFormat(), + isRedirectTestOutputToFile(), + getReportsDirectory(), + isTrimStackTrace(), + getReportNameSuffix(), + getStatisticsFile(configChecksum), + requiresRunHistory(), + getRerunFailingTestsCount(), + getReportSchemaLocation(), + getEncoding(), + isForking, + xmlReporter, + outReporter, + testsetReporter); + } + + private boolean isSpecificTestSpecified() { + return isNotBlank(getTest()); } - private boolean isSpecificTestSpecified() - { - return isNotBlank( getTest() ); - } - - @Nonnull private List readListFromFile( @Nonnull final File file ) - { - getConsoleLogger().debug( "Reading list from: " + file ); + @Nonnull + private List readListFromFile(@Nonnull final File file) { + getConsoleLogger().debug("Reading list from: " + file); - if ( !file.exists() ) - { - throw new RuntimeException( "Failed to load list from file: " + file ); + if (!file.exists()) { + throw new RuntimeException("Failed to load list from file: " + file); } - try - { - List list = FileUtils.loadFile( file ); + try { + List list = FileUtils.loadFile(file); - if ( getConsoleLogger().isDebugEnabled() ) - { - getConsoleLogger().debug( "List contents:" ); - for ( String entry : list ) - { - getConsoleLogger().debug( " " + entry ); + if (getConsoleLogger().isDebugEnabled()) { + getConsoleLogger().debug("List contents:"); + for (String entry : list) { + getConsoleLogger().debug(" " + entry); } } return list; - } - catch ( IOException e ) - { - throw new RuntimeException( "Failed to load list from file: " + file, e ); + } catch (IOException e) { + throw new RuntimeException("Failed to load list from file: " + file, e); } } @Nonnull - private List getExcludedScanList() - throws MojoFailureException - { - return getExcludeList( true ); + private List getExcludedScanList() throws MojoFailureException { + return getExcludeList(true); } @Nonnull - private List getExcludeList() - throws MojoFailureException - { - return getExcludeList( false ); + private List getExcludeList() throws MojoFailureException { + return getExcludeList(false); } /** @@ -2184,51 +2029,38 @@ private List getExcludeList() * @throws MojoFailureException if the excludes breaks a pattern format */ @Nonnull - private List getExcludeList( boolean asScanList ) - throws MojoFailureException - { + private List getExcludeList(boolean asScanList) throws MojoFailureException { List excludes; - if ( isSpecificTestSpecified() ) - { + if (isSpecificTestSpecified()) { excludes = Collections.emptyList(); - } - else - { + } else { excludes = new ArrayList<>(); - if ( asScanList ) - { - if ( getExcludes() != null ) - { - excludes.addAll( getExcludes() ); + if (asScanList) { + if (getExcludes() != null) { + excludes.addAll(getExcludes()); } - checkMethodFilterInIncludesExcludes( excludes ); + checkMethodFilterInIncludesExcludes(excludes); } - if ( getExcludesFile() != null ) - { - excludes.addAll( readListFromFile( getExcludesFile() ) ); + if (getExcludesFile() != null) { + excludes.addAll(readListFromFile(getExcludesFile())); } - if ( asScanList && excludes.isEmpty() ) - { - excludes = Collections.singletonList( getDefaultExcludes() ); + if (asScanList && excludes.isEmpty()) { + excludes = Collections.singletonList(getDefaultExcludes()); } } - return filterNulls( excludes ); + return filterNulls(excludes); } @Nonnull - private List getIncludedScanList() - throws MojoFailureException - { - return getIncludeList( true ); + private List getIncludedScanList() throws MojoFailureException { + return getIncludeList(true); } @Nonnull - private List getIncludeList() - throws MojoFailureException - { - return getIncludeList( false ); + private List getIncludeList() throws MojoFailureException { + return getIncludeList(false); } /** @@ -2239,84 +2071,61 @@ private List getIncludeList() * @throws MojoFailureException if the includes breaks a pattern format */ @Nonnull - private List getIncludeList( boolean asScanList ) - throws MojoFailureException - { + private List getIncludeList(boolean asScanList) throws MojoFailureException { final List includes = new ArrayList<>(); - if ( isSpecificTestSpecified() ) - { - addAll( includes, split( getTest(), "," ) ); - } - else - { - if ( asScanList ) - { - if ( getIncludes() != null ) - { - includes.addAll( getIncludes() ); + if (isSpecificTestSpecified()) { + addAll(includes, split(getTest(), ",")); + } else { + if (asScanList) { + if (getIncludes() != null) { + includes.addAll(getIncludes()); } - checkMethodFilterInIncludesExcludes( includes ); + checkMethodFilterInIncludesExcludes(includes); } - if ( getIncludesFile() != null ) - { - includes.addAll( readListFromFile( getIncludesFile() ) ); + if (getIncludesFile() != null) { + includes.addAll(readListFromFile(getIncludesFile())); } - if ( asScanList && includes.isEmpty() ) - { - addAll( includes, getDefaultIncludes() ); + if (asScanList && includes.isEmpty()) { + addAll(includes, getDefaultIncludes()); } } - return filterNulls( includes ); + return filterNulls(includes); } - private void checkMethodFilterInIncludesExcludes( Iterable patterns ) - throws MojoFailureException - { - for ( String pattern : patterns ) - { - if ( pattern != null && pattern.contains( "#" ) ) - { - throw new MojoFailureException( "Method filter prohibited in includes|excludes parameter: " - + pattern ); + private void checkMethodFilterInIncludesExcludes(Iterable patterns) throws MojoFailureException { + for (String pattern : patterns) { + if (pattern != null && pattern.contains("#")) { + throw new MojoFailureException("Method filter prohibited in includes|excludes parameter: " + pattern); } } } - private TestListResolver getIncludedAndExcludedTests() - throws MojoFailureException - { - if ( includedExcludedTests == null ) - { - includedExcludedTests = new TestListResolver( getIncludedScanList(), getExcludedScanList() ); - getConsoleLogger().debug( "Resolved included and excluded patterns: " + includedExcludedTests ); + private TestListResolver getIncludedAndExcludedTests() throws MojoFailureException { + if (includedExcludedTests == null) { + includedExcludedTests = new TestListResolver(getIncludedScanList(), getExcludedScanList()); + getConsoleLogger().debug("Resolved included and excluded patterns: " + includedExcludedTests); } return includedExcludedTests; } - public TestListResolver getSpecificTests() - throws MojoFailureException - { - if ( specificTests == null ) - { - specificTests = new TestListResolver( getIncludeList(), getExcludeList() ); + public TestListResolver getSpecificTests() throws MojoFailureException { + if (specificTests == null) { + specificTests = new TestListResolver(getIncludeList(), getExcludeList()); } return specificTests; } - @Nonnull private List filterNulls( @Nonnull List toFilter ) - { - List result = new ArrayList<>( toFilter.size() ); - for ( String item : toFilter ) - { - if ( item != null ) - { + @Nonnull + private List filterNulls(@Nonnull List toFilter) { + List result = new ArrayList<>(toFilter.size()); + for (String item : toFilter) { + if (item != null) { item = item.trim(); - if ( !item.isEmpty() ) - { - result.add( item ); + if (!item.isEmpty()) { + result.add(item); } } } @@ -2324,139 +2133,142 @@ public TestListResolver getSpecificTests() return result; } - private Artifact getTestNgArtifact() - throws MojoExecutionException - { - Artifact artifact = getProjectArtifactMap().get( getTestNGArtifactName() ); + private Artifact getTestNgArtifact() throws MojoExecutionException { + Artifact artifact = getProjectArtifactMap().get(getTestNGArtifactName()); Artifact projectArtifact = project.getArtifact(); String projectArtifactName = projectArtifact.getGroupId() + ":" + projectArtifact.getArtifactId(); - if ( artifact != null ) - { + if (artifact != null) { VersionRange range = createVersionRange(); - if ( !range.containsVersion( new DefaultArtifactVersion( artifact.getVersion() ) ) ) - { + if (!range.containsVersion(new DefaultArtifactVersion(artifact.getVersion()))) { throw new MojoExecutionException( - "TestNG support requires version 4.7 or above. You have declared version " - + artifact.getVersion() ); + "TestNG support requires version 4.7 or above. You have declared version " + + artifact.getVersion()); } - } - else if ( projectArtifactName.equals( getTestNGArtifactName() ) ) - { + } else if (projectArtifactName.equals(getTestNGArtifactName())) { artifact = projectArtifact; } return artifact; - } - private VersionRange createVersionRange() - { - try - { - return VersionRange.createFromVersionSpec( "[4.7,)" ); - } - catch ( InvalidVersionSpecificationException e ) - { - throw new RuntimeException( e ); + private VersionRange createVersionRange() { + try { + return VersionRange.createFromVersionSpec("[4.7,)"); + } catch (InvalidVersionSpecificationException e) { + throw new RuntimeException(e); } } - private Artifact getJunitArtifact() - { - Artifact artifact = getProjectArtifactMap().get( getJunitArtifactName() ); + private Artifact getJunitArtifact() { + Artifact artifact = getProjectArtifactMap().get(getJunitArtifactName()); Artifact projectArtifact = project.getArtifact(); String projectArtifactName = projectArtifact.getGroupId() + ":" + projectArtifact.getArtifactId(); - if ( artifact == null && projectArtifactName.equals( getJunitArtifactName() ) ) - { + if (artifact == null && projectArtifactName.equals(getJunitArtifactName())) { artifact = projectArtifact; } return artifact; } - private Artifact getJunitDepArtifact() - { - return getProjectArtifactMap().get( "junit:junit-dep" ); + private Artifact getJunitDepArtifact() { + return getProjectArtifactMap().get("junit:junit-dep"); } - private Artifact getJUnitPlatformRunnerArtifact() - { - return getProjectArtifactMap().get( "org.junit.platform:junit-platform-runner" ); + private Artifact getJUnitPlatformRunnerArtifact() { + return getProjectArtifactMap().get("org.junit.platform:junit-platform-runner"); } - private Artifact getJUnit5Artifact() - { - Artifact artifact = getPluginArtifactMap().get( "org.junit.platform:junit-platform-engine" ); - if ( artifact == null ) - { - return getProjectArtifactMap().get( "org.junit.platform:junit-platform-commons" ); + private Artifact getJUnit5Artifact() { + Artifact artifact = getPluginArtifactMap().get("org.junit.platform:junit-platform-engine"); + if (artifact == null) { + return getProjectArtifactMap().get("org.junit.platform:junit-platform-commons"); } return artifact; } - private ForkStarter createForkStarter( @Nonnull ProviderInfo provider, @Nonnull ForkConfiguration forkConfiguration, - @Nonnull ClassLoaderConfiguration classLoaderConfiguration, - @Nonnull RunOrderParameters runOrderParameters, @Nonnull ConsoleLogger log, - @Nonnull DefaultScanResult scanResult, - @Nonnull TestClassPath testClasspathWrapper, @Nonnull Platform platform, - @Nonnull ResolvePathResultWrapper resolvedJavaModularityResult ) - throws MojoExecutionException, MojoFailureException - { - StartupConfiguration startupConfiguration = createStartupConfiguration( provider, true, - classLoaderConfiguration, scanResult, testClasspathWrapper, platform, resolvedJavaModularityResult ); + private ForkStarter createForkStarter( + @Nonnull ProviderInfo provider, + @Nonnull ForkConfiguration forkConfiguration, + @Nonnull ClassLoaderConfiguration classLoaderConfiguration, + @Nonnull RunOrderParameters runOrderParameters, + @Nonnull ConsoleLogger log, + @Nonnull DefaultScanResult scanResult, + @Nonnull TestClassPath testClasspathWrapper, + @Nonnull Platform platform, + @Nonnull ResolvePathResultWrapper resolvedJavaModularityResult) + throws MojoExecutionException, MojoFailureException { + StartupConfiguration startupConfiguration = createStartupConfiguration( + provider, + true, + classLoaderConfiguration, + scanResult, + testClasspathWrapper, + platform, + resolvedJavaModularityResult); String configChecksum = getConfigChecksum(); - StartupReportConfiguration startupReportConfiguration = getStartupReportConfiguration( configChecksum, true ); - ProviderConfiguration providerConfiguration = createProviderConfiguration( runOrderParameters ); - return new ForkStarter( providerConfiguration, startupConfiguration, forkConfiguration, - getForkedProcessTimeoutInSeconds(), startupReportConfiguration, log ); - } - - private InPluginVMSurefireStarter createInprocessStarter( @Nonnull ProviderInfo provider, - @Nonnull ClassLoaderConfiguration classLoaderConfig, - @Nonnull RunOrderParameters runOrderParameters, - @Nonnull DefaultScanResult scanResult, - @Nonnull Platform platform, - @Nonnull TestClassPath testClasspathWrapper ) - throws MojoExecutionException, MojoFailureException - { - StartupConfiguration startupConfiguration = createStartupConfiguration( provider, false, classLoaderConfig, - scanResult, testClasspathWrapper, platform, new ResolvePathResultWrapper( null, true ) ); + StartupReportConfiguration startupReportConfiguration = getStartupReportConfiguration(configChecksum, true); + ProviderConfiguration providerConfiguration = createProviderConfiguration(runOrderParameters); + return new ForkStarter( + providerConfiguration, + startupConfiguration, + forkConfiguration, + getForkedProcessTimeoutInSeconds(), + startupReportConfiguration, + log); + } + + private InPluginVMSurefireStarter createInprocessStarter( + @Nonnull ProviderInfo provider, + @Nonnull ClassLoaderConfiguration classLoaderConfig, + @Nonnull RunOrderParameters runOrderParameters, + @Nonnull DefaultScanResult scanResult, + @Nonnull Platform platform, + @Nonnull TestClassPath testClasspathWrapper) + throws MojoExecutionException, MojoFailureException { + StartupConfiguration startupConfiguration = createStartupConfiguration( + provider, + false, + classLoaderConfig, + scanResult, + testClasspathWrapper, + platform, + new ResolvePathResultWrapper(null, true)); String configChecksum = getConfigChecksum(); - StartupReportConfiguration startupReportConfiguration = getStartupReportConfiguration( configChecksum, false ); - ProviderConfiguration providerConfiguration = createProviderConfiguration( runOrderParameters ); - return new InPluginVMSurefireStarter( startupConfiguration, providerConfiguration, startupReportConfiguration, - getConsoleLogger(), platform ); + StartupReportConfiguration startupReportConfiguration = getStartupReportConfiguration(configChecksum, false); + ProviderConfiguration providerConfiguration = createProviderConfiguration(runOrderParameters); + return new InPluginVMSurefireStarter( + startupConfiguration, providerConfiguration, startupReportConfiguration, getConsoleLogger(), platform); } // todo this is in separate method and can be better tested than whole method createForkConfiguration() @Nonnull - private ForkNodeFactory getForkNodeFactory() - { + private ForkNodeFactory getForkNodeFactory() { ForkNodeFactory forkNode = getForkNode(); return forkNode == null ? new LegacyForkNodeFactory() : forkNode; } @Nonnull - private ForkConfiguration createForkConfiguration( @Nonnull Platform platform, - @Nonnull ResolvePathResultWrapper resolvedJavaModularityResult ) - throws MojoExecutionException - { + private ForkConfiguration createForkConfiguration( + @Nonnull Platform platform, @Nonnull ResolvePathResultWrapper resolvedJavaModularityResult) + throws MojoExecutionException { File tmpDir = getSurefireTempDir(); Artifact shadeFire = getShadefireArtifact(); - Classpath bootClasspath = getArtifactClasspath( shadeFire != null ? shadeFire : getBooterArtifact() ); + Classpath bootClasspath = getArtifactClasspath(shadeFire != null ? shadeFire : getBooterArtifact()); ForkNodeFactory forkNode = getForkNodeFactory(); - getConsoleLogger().debug( "Found implementation of fork node factory: " + forkNode.getClass().getName() ); + getConsoleLogger() + .debug("Found implementation of fork node factory: " + + forkNode.getClass().getName()); - if ( canExecuteProviderWithModularPath( platform, resolvedJavaModularityResult ) ) - { - return new ModularClasspathForkConfiguration( bootClasspath, + if (canExecuteProviderWithModularPath(platform, resolvedJavaModularityResult)) { + return new ModularClasspathForkConfiguration( + bootClasspath, tmpDir, getEffectiveDebugForkedProcess(), getWorkingDirectory() != null ? getWorkingDirectory() : getBasedir(), @@ -2469,11 +2281,10 @@ private ForkConfiguration createForkConfiguration( @Nonnull Platform platform, reuseForks, platform, getConsoleLogger(), - forkNode ); - } - else if ( getClassLoaderConfiguration().isManifestOnlyJarRequestedAndUsable() ) - { - return new JarManifestForkConfiguration( bootClasspath, + forkNode); + } else if (getClassLoaderConfiguration().isManifestOnlyJarRequestedAndUsable()) { + return new JarManifestForkConfiguration( + bootClasspath, tmpDir, getEffectiveDebugForkedProcess(), getWorkingDirectory() != null ? getWorkingDirectory() : getBasedir(), @@ -2486,11 +2297,10 @@ else if ( getClassLoaderConfiguration().isManifestOnlyJarRequestedAndUsable() ) reuseForks, platform, getConsoleLogger(), - forkNode ); - } - else - { - return new ClasspathForkConfiguration( bootClasspath, + forkNode); + } else { + return new ClasspathForkConfiguration( + bootClasspath, tmpDir, getEffectiveDebugForkedProcess(), getWorkingDirectory() != null ? getWorkingDirectory() : getBasedir(), @@ -2503,139 +2313,115 @@ else if ( getClassLoaderConfiguration().isManifestOnlyJarRequestedAndUsable() ) reuseForks, platform, getConsoleLogger(), - forkNode ); + forkNode); } } - private void ensureEnableProcessChecker() throws MojoFailureException - { - if ( !ProcessCheckerType.isValid( getEnableProcessChecker() ) ) - { - throw new MojoFailureException( "Unexpected value '" + private void ensureEnableProcessChecker() throws MojoFailureException { + if (!ProcessCheckerType.isValid(getEnableProcessChecker())) { + throw new MojoFailureException("Unexpected value '" + getEnableProcessChecker() - + "' in the configuration parameter 'enableProcessChecker'." ); + + "' in the configuration parameter 'enableProcessChecker'."); } } - @SuppressWarnings( "checkstyle:emptyblock" ) - protected int getEffectiveForkCount() - { - if ( effectiveForkCount < 0 ) - { - try - { - effectiveForkCount = convertWithCoreCount( forkCount ); - } - catch ( NumberFormatException ignored ) - { + @SuppressWarnings("checkstyle:emptyblock") + protected int getEffectiveForkCount() { + if (effectiveForkCount < 0) { + try { + effectiveForkCount = convertWithCoreCount(forkCount); + } catch (NumberFormatException ignored) { } - if ( effectiveForkCount < 0 ) - { - throw new IllegalArgumentException( "Fork count " + forkCount.trim() + " is not a legal value." ); + if (effectiveForkCount < 0) { + throw new IllegalArgumentException("Fork count " + forkCount.trim() + " is not a legal value."); } } return effectiveForkCount; } - protected int convertWithCoreCount( String count ) - { + protected int convertWithCoreCount(String count) { String trimmed = count.trim(); - if ( trimmed.endsWith( "C" ) ) - { - double multiplier = Double.parseDouble( trimmed.substring( 0, trimmed.length() - 1 ) ); - double calculated = multiplier * ( (double) Runtime.getRuntime().availableProcessors() ); - return calculated > 0d ? Math.max( (int) calculated, 1 ) : 0; - } - else - { - return parseInt( trimmed ); + if (trimmed.endsWith("C")) { + double multiplier = Double.parseDouble(trimmed.substring(0, trimmed.length() - 1)); + double calculated = multiplier * ((double) Runtime.getRuntime().availableProcessors()); + return calculated > 0d ? Math.max((int) calculated, 1) : 0; + } else { + return parseInt(trimmed); } } - private String getEffectiveDebugForkedProcess() - { + private String getEffectiveDebugForkedProcess() { String debugForkedProcess = getDebugForkedProcess(); - if ( "true".equals( debugForkedProcess ) ) - { + if ("true".equals(debugForkedProcess)) { return "-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=localhost:5005"; } return debugForkedProcess; } - private JdkAttributes getEffectiveJvm() throws MojoFailureException - { - if ( isNotEmpty( getJvm() ) ) - { - File pathToJava = new File( getJvm() ).getAbsoluteFile(); - if ( !endsWithJavaPath( pathToJava.getPath() ) ) - { - throw new MojoFailureException( "Given path does not end with java executor \"" - + pathToJava.getPath() + "\"." ); + private JdkAttributes getEffectiveJvm() throws MojoFailureException { + if (isNotEmpty(getJvm())) { + File pathToJava = new File(getJvm()).getAbsoluteFile(); + if (!endsWithJavaPath(pathToJava.getPath())) { + throw new MojoFailureException( + "Given path does not end with java executor \"" + pathToJava.getPath() + "\"."); } - if ( !( pathToJava.isFile() - || "java".equals( pathToJava.getName() ) && pathToJava.getParentFile().isDirectory() ) ) - { - throw new MojoFailureException( "Given path to java executor does not exist \"" - + pathToJava.getPath() + "\"." ); + if (!(pathToJava.isFile() + || "java".equals(pathToJava.getName()) + && pathToJava.getParentFile().isDirectory())) { + throw new MojoFailureException( + "Given path to java executor does not exist \"" + pathToJava.getPath() + "\"."); } - File jdkHome = toJdkHomeFromJvmExec( pathToJava.getPath() ); - if ( jdkHome == null ) - { - getConsoleLogger().warning( "Cannot determine JAVA_HOME of jvm exec path " + pathToJava ); - } - else if ( !getEnvironmentVariables().containsKey( "JAVA_HOME" ) ) - { - getEnvironmentVariables().put( "JAVA_HOME", jdkHome.getAbsolutePath() ); + File jdkHome = toJdkHomeFromJvmExec(pathToJava.getPath()); + if (jdkHome == null) { + getConsoleLogger().warning("Cannot determine JAVA_HOME of jvm exec path " + pathToJava); + } else if (!getEnvironmentVariables().containsKey("JAVA_HOME")) { + getEnvironmentVariables().put("JAVA_HOME", jdkHome.getAbsolutePath()); } - BigDecimal version = jdkHome == null ? null : toJdkVersionFromReleaseFile( jdkHome ); - boolean javaVersion9 = version == null ? isJava9AtLeast( pathToJava.getPath() ) : isJava9AtLeast( version ); - return new JdkAttributes( pathToJava, jdkHome, javaVersion9 ); + BigDecimal version = jdkHome == null ? null : toJdkVersionFromReleaseFile(jdkHome); + boolean javaVersion9 = version == null ? isJava9AtLeast(pathToJava.getPath()) : isJava9AtLeast(version); + return new JdkAttributes(pathToJava, jdkHome, javaVersion9); } - if ( toolchain != null ) - { - String jvmToUse = toolchain.findTool( "java" ); - if ( isNotEmpty( jvmToUse ) ) - { + if (toolchain != null) { + String jvmToUse = toolchain.findTool("java"); + if (isNotEmpty(jvmToUse)) { boolean javaVersion9 = false; String jdkHome = null; - if ( toolchain instanceof DefaultToolchain ) - { + if (toolchain instanceof DefaultToolchain) { DefaultToolchain defaultToolchain = (DefaultToolchain) toolchain; - javaVersion9 = defaultToolchain.matchesRequirements( JAVA_9_MATCHER ) - || defaultToolchain.matchesRequirements( JAVA_9_MATCHER_OLD_NOTATION ); + javaVersion9 = defaultToolchain.matchesRequirements(JAVA_9_MATCHER) + || defaultToolchain.matchesRequirements(JAVA_9_MATCHER_OLD_NOTATION); } - if ( toolchain instanceof DefaultJavaToolChain ) - { + if (toolchain instanceof DefaultJavaToolChain) { DefaultJavaToolChain defaultJavaToolChain = (DefaultJavaToolChain) toolchain; - if ( !getEnvironmentVariables().containsKey( "JAVA_HOME" ) ) - { + if (!getEnvironmentVariables().containsKey("JAVA_HOME")) { jdkHome = defaultJavaToolChain.getJavaHome(); - getEnvironmentVariables().put( "JAVA_HOME", jdkHome ); + getEnvironmentVariables().put("JAVA_HOME", jdkHome); } } - if ( !javaVersion9 ) - { - javaVersion9 = isJava9AtLeast( jvmToUse ); + if (!javaVersion9) { + javaVersion9 = isJava9AtLeast(jvmToUse); } - return new JdkAttributes( new File( jvmToUse ), - jdkHome == null ? toJdkHomeFromJvmExec( jvmToUse ) : new File( jdkHome ), javaVersion9 ); + return new JdkAttributes( + new File(jvmToUse), + jdkHome == null ? toJdkHomeFromJvmExec(jvmToUse) : new File(jdkHome), + javaVersion9); } } // use the same JVM as the one used to run Maven (the "java.home" one) - String jvmToUse = System.getProperty( "java.home" ) + File.separator + "bin" + File.separator + "java"; - getConsoleLogger().debug( "Using JVM: " + jvmToUse + " with Java version " + JAVA_RECENT ); + String jvmToUse = System.getProperty("java.home") + File.separator + "bin" + File.separator + "java"; + getConsoleLogger().debug("Using JVM: " + jvmToUse + " with Java version " + JAVA_RECENT); - return new JdkAttributes( jvmToUse, isBuiltInJava9AtLeast() ); + return new JdkAttributes(jvmToUse, isBuiltInJava9AtLeast()); } /** @@ -2643,23 +2429,16 @@ else if ( !getEnvironmentVariables().containsKey( "JAVA_HOME" ) ) * * @return A file pointing to the location of surefire's own temp files */ - File getSurefireTempDir() - { + File getSurefireTempDir() { File result = IS_OS_WINDOWS ? createSurefireBootDirectoryInTemp() : createSurefireBootDirectoryInBuild(); - try - { + try { File canonical = result.getCanonicalFile(); - if ( !result.equals( canonical ) ) - { - getConsoleLogger() - .debug( "Canonicalized tempDir path '" + result + "' to '" + canonical + "'" ); + if (!result.equals(canonical)) { + getConsoleLogger().debug("Canonicalized tempDir path '" + result + "' to '" + canonical + "'"); } return canonical; - } - catch ( IOException e ) - { - getConsoleLogger() - .error( "Could not canonicalize tempDir path '" + result + "'", e ); + } catch (IOException e) { + getConsoleLogger().error("Could not canonicalize tempDir path '" + result + "'", e); } return result; } @@ -2669,111 +2448,105 @@ File getSurefireTempDir() * * @return The checksum */ - private String getConfigChecksum() - { + private String getConfigChecksum() { ChecksumCalculator checksum = new ChecksumCalculator(); - checksum.add( getPluginName() ); - checksum.add( isSkipTests() ); - checksum.add( isSkipExec() ); - checksum.add( isSkip() ); - checksum.add( getTestClassesDirectory() ); - checksum.add( getMainBuildPath() ); - checksum.add( getClasspathDependencyExcludes() ); - checksum.add( getClasspathDependencyScopeExclude() ); - checksum.add( getAdditionalClasspathElements() ); - checksum.add( getReportsDirectory() ); - checksum.add( getProjectBuildDirectory() ); - checksum.add( getTestSourceDirectory() ); - checksum.add( getTest() ); - checksum.add( getIncludes() ); - checksum.add( getSkipAfterFailureCount() ); - checksum.add( getShutdown() ); - checksum.add( getExcludes() ); - checksum.add( getLocalRepository() ); - checksum.add( getSystemProperties() ); - checksum.add( getSystemPropertyVariables() ); - checksum.add( getSystemPropertiesFile() ); - checksum.add( getProperties() ); - checksum.add( isPrintSummary() ); - checksum.add( getReportFormat() ); - checksum.add( getReportNameSuffix() ); - checksum.add( isUseFile() ); - checksum.add( isRedirectTestOutputToFile() ); - checksum.add( getForkCount() ); - checksum.add( isReuseForks() ); - checksum.add( getJvm() ); - checksum.add( getArgLine() ); - checksum.add( getDebugForkedProcess() ); - checksum.add( getForkedProcessTimeoutInSeconds() ); - checksum.add( getParallelTestsTimeoutInSeconds() ); - checksum.add( getParallelTestsTimeoutForcedInSeconds() ); - checksum.add( getEnvironmentVariables() ); - checksum.add( getExcludedEnvironmentVariables() ); - checksum.add( getWorkingDirectory() ); - checksum.add( isChildDelegation() ); - checksum.add( getGroups() ); - checksum.add( getExcludedGroups() ); - checksum.add( getIncludeJUnit5Engines() ); - checksum.add( getExcludeJUnit5Engines() ); - checksum.add( getSuiteXmlFiles() ); - checksum.add( getJunitArtifact() ); - checksum.add( getTestNGArtifactName() ); - checksum.add( getThreadCount() ); - checksum.add( getThreadCountSuites() ); - checksum.add( getThreadCountClasses() ); - checksum.add( getThreadCountMethods() ); - checksum.add( getPerCoreThreadCount() ); - checksum.add( getUseUnlimitedThreads() ); - checksum.add( getParallel() ); - checksum.add( isParallelOptimized() ); - checksum.add( isTrimStackTrace() ); - checksum.add( getRemoteRepositories() ); - checksum.add( getProjectRemoteRepositories() ); - checksum.add( isDisableXmlReport() ); - checksum.add( isUseSystemClassLoader() ); - checksum.add( isUseManifestOnlyJar() ); - checksum.add( getEncoding() ); - checksum.add( isEnableAssertions() ); - checksum.add( getObjectFactory() ); - checksum.add( getFailIfNoTests() ); - checksum.add( getRunOrder() ); - checksum.add( getDependenciesToScan() ); - checksum.add( getForkedProcessExitTimeoutInSeconds() ); - checksum.add( getRerunFailingTestsCount() ); - checksum.add( getTempDir() ); - checksum.add( useModulePath() ); - checksum.add( getEnableProcessChecker() ); - addPluginSpecificChecksumItems( checksum ); + checksum.add(getPluginName()); + checksum.add(isSkipTests()); + checksum.add(isSkipExec()); + checksum.add(isSkip()); + checksum.add(getTestClassesDirectory()); + checksum.add(getMainBuildPath()); + checksum.add(getClasspathDependencyExcludes()); + checksum.add(getClasspathDependencyScopeExclude()); + checksum.add(getAdditionalClasspathElements()); + checksum.add(getReportsDirectory()); + checksum.add(getProjectBuildDirectory()); + checksum.add(getTestSourceDirectory()); + checksum.add(getTest()); + checksum.add(getIncludes()); + checksum.add(getSkipAfterFailureCount()); + checksum.add(getShutdown()); + checksum.add(getExcludes()); + checksum.add(getLocalRepository()); + checksum.add(getSystemProperties()); + checksum.add(getSystemPropertyVariables()); + checksum.add(getSystemPropertiesFile()); + checksum.add(getProperties()); + checksum.add(isPrintSummary()); + checksum.add(getReportFormat()); + checksum.add(getReportNameSuffix()); + checksum.add(isUseFile()); + checksum.add(isRedirectTestOutputToFile()); + checksum.add(getForkCount()); + checksum.add(isReuseForks()); + checksum.add(getJvm()); + checksum.add(getArgLine()); + checksum.add(getDebugForkedProcess()); + checksum.add(getForkedProcessTimeoutInSeconds()); + checksum.add(getParallelTestsTimeoutInSeconds()); + checksum.add(getParallelTestsTimeoutForcedInSeconds()); + checksum.add(getEnvironmentVariables()); + checksum.add(getExcludedEnvironmentVariables()); + checksum.add(getWorkingDirectory()); + checksum.add(isChildDelegation()); + checksum.add(getGroups()); + checksum.add(getExcludedGroups()); + checksum.add(getIncludeJUnit5Engines()); + checksum.add(getExcludeJUnit5Engines()); + checksum.add(getSuiteXmlFiles()); + checksum.add(getJunitArtifact()); + checksum.add(getTestNGArtifactName()); + checksum.add(getThreadCount()); + checksum.add(getThreadCountSuites()); + checksum.add(getThreadCountClasses()); + checksum.add(getThreadCountMethods()); + checksum.add(getPerCoreThreadCount()); + checksum.add(getUseUnlimitedThreads()); + checksum.add(getParallel()); + checksum.add(isParallelOptimized()); + checksum.add(isTrimStackTrace()); + checksum.add(getRemoteRepositories()); + checksum.add(getProjectRemoteRepositories()); + checksum.add(isDisableXmlReport()); + checksum.add(isUseSystemClassLoader()); + checksum.add(isUseManifestOnlyJar()); + checksum.add(getEncoding()); + checksum.add(isEnableAssertions()); + checksum.add(getObjectFactory()); + checksum.add(getFailIfNoTests()); + checksum.add(getRunOrder()); + checksum.add(getDependenciesToScan()); + checksum.add(getForkedProcessExitTimeoutInSeconds()); + checksum.add(getRerunFailingTestsCount()); + checksum.add(getTempDir()); + checksum.add(useModulePath()); + checksum.add(getEnableProcessChecker()); + addPluginSpecificChecksumItems(checksum); return checksum.getSha1(); } - protected void addPluginSpecificChecksumItems( ChecksumCalculator checksum ) - { + protected void addPluginSpecificChecksumItems(ChecksumCalculator checksum) {} - } - - protected boolean hasExecutedBefore() - { + protected boolean hasExecutedBefore() { // A tribute to Linus Torvalds String configChecksum = getConfigChecksum(); - @SuppressWarnings( "unchecked" ) Map pluginContext = getPluginContext(); - if ( pluginContext.containsKey( configChecksum ) ) - { + @SuppressWarnings("unchecked") + Map pluginContext = getPluginContext(); + if (pluginContext.containsKey(configChecksum)) { getConsoleLogger() - .info( "Skipping execution of surefire because it has already been run for this configuration" ); + .info("Skipping execution of surefire because it has already been run for this configuration"); return true; } - pluginContext.put( configChecksum, configChecksum ); + pluginContext.put(configChecksum, configChecksum); return false; } @Nonnull - protected ClassLoaderConfiguration getClassLoaderConfiguration() - { + protected ClassLoaderConfiguration getClassLoaderConfiguration() { return isForking() - ? new ClassLoaderConfiguration( isUseSystemClassLoader(), isUseManifestOnlyJar() ) - : new ClassLoaderConfiguration( false, false ); + ? new ClassLoaderConfiguration(isUseSystemClassLoader(), isUseManifestOnlyJar()) + : new ClassLoaderConfiguration(false, false); } /** @@ -2781,25 +2554,23 @@ protected ClassLoaderConfiguration getClassLoaderConfiguration() * * @return the classpath elements */ - private TestClassPath generateTestClasspath() - { + private TestClassPath generateTestClasspath() { Set classpathArtifacts = getProject().getArtifacts(); - if ( getClasspathDependencyScopeExclude() != null && !getClasspathDependencyScopeExclude().isEmpty() ) - { - ArtifactFilter dependencyFilter = new ScopeArtifactFilter( getClasspathDependencyScopeExclude() ); - classpathArtifacts = filterArtifacts( classpathArtifacts, dependencyFilter ); + if (getClasspathDependencyScopeExclude() != null + && !getClasspathDependencyScopeExclude().isEmpty()) { + ArtifactFilter dependencyFilter = new ScopeArtifactFilter(getClasspathDependencyScopeExclude()); + classpathArtifacts = filterArtifacts(classpathArtifacts, dependencyFilter); } - if ( getClasspathDependencyExcludes() != null ) - { - List excludedDependencies = asList( getClasspathDependencyExcludes() ); - ArtifactFilter dependencyFilter = new PatternIncludesArtifactFilter( excludedDependencies ); - classpathArtifacts = filterArtifacts( classpathArtifacts, dependencyFilter ); + if (getClasspathDependencyExcludes() != null) { + List excludedDependencies = asList(getClasspathDependencyExcludes()); + ArtifactFilter dependencyFilter = new PatternIncludesArtifactFilter(excludedDependencies); + classpathArtifacts = filterArtifacts(classpathArtifacts, dependencyFilter); } - return new TestClassPath( classpathArtifacts, getMainBuildPath(), - getTestClassesDirectory(), getAdditionalClasspathElements() ); + return new TestClassPath( + classpathArtifacts, getMainBuildPath(), getTestClassesDirectory(), getAdditionalClasspathElements()); } /** @@ -2809,383 +2580,297 @@ private TestClassPath generateTestClasspath() * @param filter The filter to apply * @return The filtered result */ - private static Set filterArtifacts( Set artifacts, ArtifactFilter filter ) - { + private static Set filterArtifacts(Set artifacts, ArtifactFilter filter) { Set filteredArtifacts = new LinkedHashSet<>(); - for ( Artifact artifact : artifacts ) - { - if ( !filter.include( artifact ) ) - { - filteredArtifacts.add( artifact ); + for (Artifact artifact : artifacts) { + if (!filter.include(artifact)) { + filteredArtifacts.add(artifact); } } return filteredArtifacts; } - private void showMap( Map map, String setting ) - { - for ( Object o : map.keySet() ) - { + private void showMap(Map map, String setting) { + for (Object o : map.keySet()) { String key = (String) o; - String value = (String) map.get( key ); - getConsoleLogger().debug( "Setting " + setting + " [" + key + "]=[" + value + "]" ); + String value = (String) map.get(key); + getConsoleLogger().debug("Setting " + setting + " [" + key + "]=[" + value + "]"); } } - private void showArray( T[] array, String setting ) - { - for ( T e : array ) - { - getConsoleLogger().debug( "Setting " + setting + " [" + e + "]" ); + private void showArray(T[] array, String setting) { + for (T e : array) { + getConsoleLogger().debug("Setting " + setting + " [" + e + "]"); } } - private Classpath getArtifactClasspath( Artifact surefireArtifact ) throws MojoExecutionException - { - Classpath existing = classpathCache.getCachedClassPath( surefireArtifact.getArtifactId() ); - if ( existing == null ) - { + private Classpath getArtifactClasspath(Artifact surefireArtifact) throws MojoExecutionException { + Classpath existing = classpathCache.getCachedClassPath(surefireArtifact.getArtifactId()); + if (existing == null) { List items = new ArrayList<>(); - Set booterArtifacts = - surefireDependencyResolver.resolvePluginArtifact( surefireArtifact ).getArtifacts(); - for ( Artifact artifact : booterArtifacts ) - { - getConsoleLogger().debug( - "Adding to " + getPluginName() + " booter test classpath: " + artifact.getFile().getAbsolutePath() - + " Scope: " + artifact.getScope() ); - items.add( artifact.getFile().getAbsolutePath() ); - } - existing = new Classpath( items ); - classpathCache.setCachedClasspath( surefireArtifact.getArtifactId(), existing ); + Set booterArtifacts = surefireDependencyResolver + .resolvePluginArtifact(surefireArtifact) + .getArtifacts(); + for (Artifact artifact : booterArtifacts) { + getConsoleLogger() + .debug("Adding to " + getPluginName() + " booter test classpath: " + + artifact.getFile().getAbsolutePath() + " Scope: " + artifact.getScope()); + items.add(artifact.getFile().getAbsolutePath()); + } + existing = new Classpath(items); + classpathCache.setCachedClasspath(surefireArtifact.getArtifactId(), existing); } return existing; } - private Properties getUserProperties() - { + private Properties getUserProperties() { return getSession().getUserProperties(); } - private void ensureWorkingDirectoryExists() - throws MojoFailureException - { - if ( getWorkingDirectory() == null ) - { - throw new MojoFailureException( "workingDirectory cannot be null" ); + private void ensureWorkingDirectoryExists() throws MojoFailureException { + if (getWorkingDirectory() == null) { + throw new MojoFailureException("workingDirectory cannot be null"); } - if ( isForking() ) - { + if (isForking()) { // Postpone directory creation till forked JVM creation // see ForkConfiguration.createCommandLine return; } - if ( !getWorkingDirectory().exists() ) - { - if ( !getWorkingDirectory().mkdirs() ) - { - throw new MojoFailureException( "Cannot create workingDirectory " + getWorkingDirectory() ); + if (!getWorkingDirectory().exists()) { + if (!getWorkingDirectory().mkdirs()) { + throw new MojoFailureException("Cannot create workingDirectory " + getWorkingDirectory()); } } - if ( !getWorkingDirectory().isDirectory() ) - { + if (!getWorkingDirectory().isDirectory()) { throw new MojoFailureException( - "workingDirectory " + getWorkingDirectory() + " exists and is not a directory" ); + "workingDirectory " + getWorkingDirectory() + " exists and is not a directory"); } } - private void ensureParallelRunningCompatibility() - throws MojoFailureException - { - if ( isMavenParallel() && isNotForking() ) - { - throw new MojoFailureException( "parallel maven execution is not compatible with surefire forkCount 0" ); + private void ensureParallelRunningCompatibility() throws MojoFailureException { + if (isMavenParallel() && isNotForking()) { + throw new MojoFailureException("parallel maven execution is not compatible with surefire forkCount 0"); } } - private void warnIfUselessUseSystemClassLoaderParameter() - { - if ( isUseSystemClassLoader() && isNotForking() ) - { - getConsoleLogger().warning( "useSystemClassLoader setting has no effect when not forking" ); + private void warnIfUselessUseSystemClassLoaderParameter() { + if (isUseSystemClassLoader() && isNotForking()) { + getConsoleLogger().warning("useSystemClassLoader setting has no effect when not forking"); } } - private boolean isNotForking() - { + private boolean isNotForking() { return !isForking(); } - private List commandLineOptions() - { - return SurefireHelper.commandLineOptions( getSession(), getConsoleLogger() ); + private List commandLineOptions() { + return SurefireHelper.commandLineOptions(getSession(), getConsoleLogger()); } - private void warnIfDefunctGroupsCombinations() - throws MojoFailureException, MojoExecutionException - { - if ( isAnyGroupsSelected() ) - { - if ( getTestNgArtifact() == null ) - { + private void warnIfDefunctGroupsCombinations() throws MojoFailureException, MojoExecutionException { + if (isAnyGroupsSelected()) { + if (getTestNgArtifact() == null) { Artifact junitArtifact = getJunitArtifact(); - boolean junit47Compatible = isJunit47Compatible( junitArtifact ); + boolean junit47Compatible = isJunit47Compatible(junitArtifact); boolean junit5PlatformCompatible = getJUnit5Artifact() != null; - if ( !junit47Compatible && !junit5PlatformCompatible ) - { - if ( junitArtifact != null ) - { - throw new MojoFailureException( "groups/excludedGroups are specified but JUnit version on " - + "classpath is too old to support groups. " - + "Check your dependency:tree to see if your project " - + "is picking up an old junit version" ); + if (!junit47Compatible && !junit5PlatformCompatible) { + if (junitArtifact != null) { + throw new MojoFailureException("groups/excludedGroups are specified but JUnit version on " + + "classpath is too old to support groups. " + + "Check your dependency:tree to see if your project " + + "is picking up an old junit version"); } - throw new MojoFailureException( "groups/excludedGroups require TestNG, JUnit48+ or JUnit 5 " - + "(a specific engine required on classpath) on project test classpath" ); + throw new MojoFailureException("groups/excludedGroups require TestNG, JUnit48+ or JUnit 5 " + + "(a specific engine required on classpath) on project test classpath"); } } - } } - private void warnIfRerunClashes() - throws MojoFailureException - { - if ( getRerunFailingTestsCount() < 0 ) - { - throw new MojoFailureException( "Parameter \"rerunFailingTestsCount\" should not be negative." ); + private void warnIfRerunClashes() throws MojoFailureException { + if (getRerunFailingTestsCount() < 0) { + throw new MojoFailureException("Parameter \"rerunFailingTestsCount\" should not be negative."); } - if ( getSkipAfterFailureCount() < 0 ) - { - throw new MojoFailureException( "Parameter \"skipAfterFailureCount\" should not be negative." ); + if (getSkipAfterFailureCount() < 0) { + throw new MojoFailureException("Parameter \"skipAfterFailureCount\" should not be negative."); } } - private void warnIfWrongShutdownValue() - throws MojoFailureException - { - if ( !Shutdown.isKnown( getShutdown() ) ) - { - throw new MojoFailureException( "Parameter \"shutdown\" should have values " + Shutdown.listParameters() ); + private void warnIfWrongShutdownValue() throws MojoFailureException { + if (!Shutdown.isKnown(getShutdown())) { + throw new MojoFailureException("Parameter \"shutdown\" should have values " + Shutdown.listParameters()); } } - private void warnIfNotApplicableSkipAfterFailureCount() - throws MojoFailureException - { + private void warnIfNotApplicableSkipAfterFailureCount() throws MojoFailureException { int skipAfterFailureCount = getSkipAfterFailureCount(); - if ( skipAfterFailureCount < 0 ) - { - throw new MojoFailureException( "Parameter \"skipAfterFailureCount\" should not be negative." ); - } - else if ( skipAfterFailureCount > 0 ) - { - try - { + if (skipAfterFailureCount < 0) { + throw new MojoFailureException("Parameter \"skipAfterFailureCount\" should not be negative."); + } else if (skipAfterFailureCount > 0) { + try { Artifact testng = getTestNgArtifact(); - if ( testng != null ) - { - VersionRange range = VersionRange.createFromVersionSpec( "[5.10,)" ); - if ( !range.containsVersion( new DefaultArtifactVersion( testng.getVersion() ) ) ) - { + if (testng != null) { + VersionRange range = VersionRange.createFromVersionSpec("[5.10,)"); + if (!range.containsVersion(new DefaultArtifactVersion(testng.getVersion()))) { throw new MojoFailureException( - "Parameter \"skipAfterFailureCount\" expects TestNG Version 5.10 or higher. " - + "java.lang.NoClassDefFoundError: org/testng/IInvokedMethodListener" ); + "Parameter \"skipAfterFailureCount\" expects TestNG Version 5.10 or higher. " + + "java.lang.NoClassDefFoundError: org/testng/IInvokedMethodListener"); } - } - else - { + } else { // TestNG is dependent on JUnit Artifact junit = getJunitArtifact(); - if ( junit != null ) - { - VersionRange range = VersionRange.createFromVersionSpec( "[4.0,)" ); - if ( !range.containsVersion( new DefaultArtifactVersion( junit.getVersion() ) ) ) - { + if (junit != null) { + VersionRange range = VersionRange.createFromVersionSpec("[4.0,)"); + if (!range.containsVersion(new DefaultArtifactVersion(junit.getVersion()))) { throw new MojoFailureException( - "Parameter \"skipAfterFailureCount\" expects JUnit Version 4.0 or higher. " - + "java.lang.NoSuchMethodError: " - + "org.junit.runner.notification.RunNotifier.pleaseStop()V" ); + "Parameter \"skipAfterFailureCount\" expects JUnit Version 4.0 or higher. " + + "java.lang.NoSuchMethodError: " + + "org.junit.runner.notification.RunNotifier.pleaseStop()V"); } } } - } - catch ( MojoExecutionException e ) - { - throw new MojoFailureException( e.getLocalizedMessage() ); - } - catch ( InvalidVersionSpecificationException e ) - { - throw new RuntimeException( e ); + } catch (MojoExecutionException e) { + throw new MojoFailureException(e.getLocalizedMessage()); + } catch (InvalidVersionSpecificationException e) { + throw new RuntimeException(e); } } } - private void warnIfIllegalTempDir() throws MojoFailureException - { - if ( isEmpty( getTempDir() ) ) - { - throw new MojoFailureException( "Parameter 'tempDir' should not be blank string." ); + private void warnIfIllegalTempDir() throws MojoFailureException { + if (isEmpty(getTempDir())) { + throw new MojoFailureException("Parameter 'tempDir' should not be blank string."); } } - protected void warnIfIllegalFailOnFlakeCount() throws MojoFailureException - { + protected void warnIfIllegalFailOnFlakeCount() throws MojoFailureException {} - } - - private void printDefaultSeedIfNecessary() - { - if ( getRunOrder().equals( RunOrder.RANDOM.name() ) ) - { - if ( getRunOrderRandomSeed() == null ) - { - setRunOrderRandomSeed( System.nanoTime() ); + private void printDefaultSeedIfNecessary() { + if (getRunOrder().equals(RunOrder.RANDOM.name())) { + if (getRunOrderRandomSeed() == null) { + setRunOrderRandomSeed(System.nanoTime()); } - getConsoleLogger().info( - "Tests will run in random order. To reproduce ordering use flag -D" - + getPluginName() + ".runOrder.random.seed=" + getRunOrderRandomSeed() ); + getConsoleLogger() + .info("Tests will run in random order. To reproduce ordering use flag -D" + getPluginName() + + ".runOrder.random.seed=" + getRunOrderRandomSeed()); } } - final class TestNgProviderInfo - implements ProviderInfo - { + final class TestNgProviderInfo implements ProviderInfo { private final Artifact testNgArtifact; - TestNgProviderInfo( Artifact testNgArtifact ) - { + TestNgProviderInfo(Artifact testNgArtifact) { this.testNgArtifact = testNgArtifact; } @Override - @Nonnull public String getProviderName() - { + @Nonnull + public String getProviderName() { return "org.apache.maven.surefire.testng.TestNGProvider"; } @Override - public boolean isApplicable() - { + public boolean isApplicable() { return testNgArtifact != null; } @Override - public void addProviderProperties() throws MojoExecutionException - { + public void addProviderProperties() throws MojoExecutionException { convertTestNGParameters(); } @Nonnull @Override - public List getJpmsArguments( @Nonnull ProviderRequirements forkRequirements ) - { + public List getJpmsArguments(@Nonnull ProviderRequirements forkRequirements) { return emptyList(); } @Override @Nonnull - public Set getProviderClasspath() throws MojoExecutionException - { + public Set getProviderClasspath() throws MojoExecutionException { Artifact surefireArtifact = getBooterArtifact(); String version = surefireArtifact.getBaseVersion(); - return surefireDependencyResolver.getProviderClasspath( "surefire-testng", version ); + return surefireDependencyResolver.getProviderClasspath("surefire-testng", version); } } - final class JUnit3ProviderInfo - implements ProviderInfo - { + final class JUnit3ProviderInfo implements ProviderInfo { @Override - @Nonnull public String getProviderName() - { + @Nonnull + public String getProviderName() { return "org.apache.maven.surefire.junit.JUnit3Provider"; } @Override - public boolean isApplicable() - { + public boolean isApplicable() { return true; } @Override - public void addProviderProperties() - { - } + public void addProviderProperties() {} @Nonnull @Override - public List getJpmsArguments( @Nonnull ProviderRequirements forkRequirements ) - { + public List getJpmsArguments(@Nonnull ProviderRequirements forkRequirements) { return emptyList(); } @Override @Nonnull - public Set getProviderClasspath() throws MojoExecutionException - { + public Set getProviderClasspath() throws MojoExecutionException { // add the JUnit provider as default - it doesn't require JUnit to be present, // since it supports POJO tests. String version = getBooterArtifact().getBaseVersion(); - return surefireDependencyResolver.getProviderClasspath( "surefire-junit3", version ); + return surefireDependencyResolver.getProviderClasspath("surefire-junit3", version); } } - final class JUnit4ProviderInfo - implements ProviderInfo - { + final class JUnit4ProviderInfo implements ProviderInfo { private final Artifact junitArtifact; private final Artifact junitDepArtifact; - JUnit4ProviderInfo( Artifact junitArtifact, Artifact junitDepArtifact ) - { + JUnit4ProviderInfo(Artifact junitArtifact, Artifact junitDepArtifact) { this.junitArtifact = junitArtifact; this.junitDepArtifact = junitDepArtifact; } @Override - @Nonnull public String getProviderName() - { + @Nonnull + public String getProviderName() { return "org.apache.maven.surefire.junit4.JUnit4Provider"; } @Override - public boolean isApplicable() - { - return junitDepArtifact != null || isAnyJunit4( junitArtifact ); + public boolean isApplicable() { + return junitDepArtifact != null || isAnyJunit4(junitArtifact); } @Override - public void addProviderProperties() - { - } + public void addProviderProperties() {} @Nonnull @Override - public List getJpmsArguments( @Nonnull ProviderRequirements forkRequirements ) - { + public List getJpmsArguments(@Nonnull ProviderRequirements forkRequirements) { return emptyList(); } @Override @Nonnull - public Set getProviderClasspath() throws MojoExecutionException - { + public Set getProviderClasspath() throws MojoExecutionException { String version = getBooterArtifact().getBaseVersion(); - return surefireDependencyResolver.getProviderClasspath( "surefire-junit4", version ); + return surefireDependencyResolver.getProviderClasspath("surefire-junit4", version); } } - final class JUnitPlatformProviderInfo - implements ProviderInfo - { + final class JUnitPlatformProviderInfo implements ProviderInfo { private static final String PROVIDER_DEP_GID = "org.junit.platform"; private static final String PROVIDER_DEP_AID = "junit-platform-launcher"; @@ -3193,9 +2878,10 @@ final class JUnitPlatformProviderInfo private final Artifact junitPlatformArtifact; private final TestClassPath testClasspath; - JUnitPlatformProviderInfo( Artifact junitPlatformRunnerArtifact, Artifact junitPlatformArtifact, - @Nonnull TestClassPath testClasspath ) - { + JUnitPlatformProviderInfo( + Artifact junitPlatformRunnerArtifact, + Artifact junitPlatformArtifact, + @Nonnull TestClassPath testClasspath) { this.junitPlatformRunnerArtifact = junitPlatformRunnerArtifact; this.junitPlatformArtifact = junitPlatformArtifact; this.testClasspath = testClasspath; @@ -3203,154 +2889,136 @@ final class JUnitPlatformProviderInfo @Override @Nonnull - public String getProviderName() - { + public String getProviderName() { return "org.apache.maven.surefire.junitplatform.JUnitPlatformProvider"; } @Override - public boolean isApplicable() - { + public boolean isApplicable() { return junitPlatformRunnerArtifact == null && junitPlatformArtifact != null; } @Override - public void addProviderProperties() - { + public void addProviderProperties() { convertGroupParameters(); convertJunitEngineParameters(); } @Nonnull @Override - public List getJpmsArguments( @Nonnull ProviderRequirements forkRequirements ) - { + public List getJpmsArguments(@Nonnull ProviderRequirements forkRequirements) { boolean hasTestDescriptor = forkRequirements.isModularPath() && forkRequirements.hasTestModuleDescriptor(); return hasTestDescriptor ? getJpmsArgs() : Collections.emptyList(); } @Override @Nonnull - public Set getProviderClasspath() throws MojoExecutionException - { + public Set getProviderClasspath() throws MojoExecutionException { String surefireVersion = getBooterArtifact().getBaseVersion(); Map providerArtifacts = - surefireDependencyResolver.getProviderClasspathAsMap( "surefire-junit-platform", surefireVersion ); + surefireDependencyResolver.getProviderClasspathAsMap("surefire-junit-platform", surefireVersion); Map testDeps = testClasspath.getTestDependencies(); Plugin plugin = getPluginDescriptor().getPlugin(); Map pluginDeps = - surefireDependencyResolver.resolvePluginDependencies( plugin, getPluginArtifactMap() ); + surefireDependencyResolver.resolvePluginDependencies(plugin, getPluginArtifactMap()); - if ( hasDependencyPlatformEngine( pluginDeps ) ) - { - providerArtifacts.putAll( pluginDeps ); - } - else - { + if (hasDependencyPlatformEngine(pluginDeps)) { + providerArtifacts.putAll(pluginDeps); + } else { String engineVersion = null; - if ( hasDependencyJupiterAPI( testDeps ) - && !testDeps.containsKey( "org.junit.jupiter:junit-jupiter-engine" ) ) - { + if (hasDependencyJupiterAPI(testDeps) + && !testDeps.containsKey("org.junit.jupiter:junit-jupiter-engine")) { String engineGroupId = "org.junit.jupiter"; String engineArtifactId = "junit-jupiter-engine"; String engineCoordinates = engineGroupId + ":" + engineArtifactId; String api = "org.junit.jupiter:junit-jupiter-api"; - engineVersion = testDeps.get( api ).getBaseVersion(); - getConsoleLogger().debug( "Test dependencies contain " - + api + ". Resolving " + engineCoordinates + ":" + engineVersion ); - addEngineByApi( engineGroupId, engineArtifactId, engineVersion, providerArtifacts ); + engineVersion = testDeps.get(api).getBaseVersion(); + getConsoleLogger() + .debug("Test dependencies contain " + api + ". Resolving " + engineCoordinates + ":" + + engineVersion); + addEngineByApi(engineGroupId, engineArtifactId, engineVersion, providerArtifacts); } - if ( ( testDeps.containsKey( "junit:junit" ) || testDeps.containsKey( "junit:junit-dep" ) ) - && !testDeps.containsKey( "org.junit.vintage:junit-vintage-engine" ) ) - { + if ((testDeps.containsKey("junit:junit") || testDeps.containsKey("junit:junit-dep")) + && !testDeps.containsKey("org.junit.vintage:junit-vintage-engine")) { String engineGroupId = "org.junit.vintage"; String engineArtifactId = "junit-vintage-engine"; String engineCoordinates = engineGroupId + ":" + engineArtifactId; - if ( engineVersion != null ) - { - getConsoleLogger().debug( "Test dependencies contain JUnit4. Resolving " - + engineCoordinates + ":" + engineVersion ); - addEngineByApi( engineGroupId, engineArtifactId, engineVersion, providerArtifacts ); + if (engineVersion != null) { + getConsoleLogger() + .debug("Test dependencies contain JUnit4. Resolving " + engineCoordinates + ":" + + engineVersion); + addEngineByApi(engineGroupId, engineArtifactId, engineVersion, providerArtifacts); } } } - narrowDependencies( providerArtifacts, testDeps ); - alignProviderVersions( providerArtifacts ); + narrowDependencies(providerArtifacts, testDeps); + alignProviderVersions(providerArtifacts); - return new LinkedHashSet<>( providerArtifacts.values() ); + return new LinkedHashSet<>(providerArtifacts.values()); } - private List getJpmsArgs() - { + private List getJpmsArgs() { List args = new ArrayList<>(); - args.add( new String[] { - "--add-opens", - "org.junit.platform.commons/org.junit.platform.commons.util=ALL-UNNAMED" - } ); + args.add(new String[] { + "--add-opens", "org.junit.platform.commons/org.junit.platform.commons.util=ALL-UNNAMED" + }); - args.add( new String[] { - "--add-opens", - "org.junit.platform.commons/org.junit.platform.commons.logging=ALL-UNNAMED" - } ); + args.add(new String[] { + "--add-opens", "org.junit.platform.commons/org.junit.platform.commons.logging=ALL-UNNAMED" + }); return args; } - private void addEngineByApi( String engineGroupId, String engineArtifactId, String engineVersion, - Map providerArtifacts ) throws MojoExecutionException - { - for ( Artifact dep : resolve( engineGroupId, engineArtifactId, engineVersion, null, "jar" ) ) - { + private void addEngineByApi( + String engineGroupId, + String engineArtifactId, + String engineVersion, + Map providerArtifacts) + throws MojoExecutionException { + for (Artifact dep : resolve(engineGroupId, engineArtifactId, engineVersion, null, "jar")) { String key = dep.getGroupId() + ":" + dep.getArtifactId(); - providerArtifacts.put( key, dep ); + providerArtifacts.put(key, dep); } } - private void narrowDependencies( Map providerArtifacts, - Map testDependencies ) - { - providerArtifacts.keySet().removeAll( testDependencies.keySet() ); + private void narrowDependencies( + Map providerArtifacts, Map testDependencies) { + providerArtifacts.keySet().removeAll(testDependencies.keySet()); } - private void alignProviderVersions( Map providerArtifacts ) throws MojoExecutionException - { + private void alignProviderVersions(Map providerArtifacts) throws MojoExecutionException { String version = junitPlatformArtifact.getBaseVersion(); - for ( Artifact launcherArtifact : resolve( PROVIDER_DEP_GID, PROVIDER_DEP_AID, version, null, "jar" ) ) - { + for (Artifact launcherArtifact : resolve(PROVIDER_DEP_GID, PROVIDER_DEP_AID, version, null, "jar")) { String key = launcherArtifact.getGroupId() + ":" + launcherArtifact.getArtifactId(); - if ( providerArtifacts.containsKey( key ) ) - { - providerArtifacts.put( key, launcherArtifact ); + if (providerArtifacts.containsKey(key)) { + providerArtifacts.put(key, launcherArtifact); } } } - private Set resolve( String g, String a, String v, String c, String t ) throws MojoExecutionException - { + private Set resolve(String g, String a, String v, String c, String t) throws MojoExecutionException { ArtifactHandler handler = junitPlatformArtifact.getArtifactHandler(); - Artifact artifact = new DefaultArtifact( g, a, v, null, t, c, handler ); - getConsoleLogger().debug( "Resolving artifact " + g + ":" + a + ":" + v ); - Set r = surefireDependencyResolver.resolveProjectArtifact( artifact ).getArtifacts(); - getConsoleLogger().debug( "Resolved artifact " + g + ":" + a + ":" + v + " to " + r ); + Artifact artifact = new DefaultArtifact(g, a, v, null, t, c, handler); + getConsoleLogger().debug("Resolving artifact " + g + ":" + a + ":" + v); + Set r = + surefireDependencyResolver.resolveProjectArtifact(artifact).getArtifacts(); + getConsoleLogger().debug("Resolved artifact " + g + ":" + a + ":" + v + " to " + r); return r; } - private boolean hasDependencyJupiterAPI( Map dependencies ) - { - return dependencies.containsKey( "org.junit.jupiter:junit-jupiter-api" ); + private boolean hasDependencyJupiterAPI(Map dependencies) { + return dependencies.containsKey("org.junit.jupiter:junit-jupiter-api"); } - private boolean hasDependencyPlatformEngine( Map dependencies ) - { - for ( Entry dependency : dependencies.entrySet() ) - { - if ( dependency.getKey().equals( "org.junit.platform:junit-platform-engine" ) ) - { + private boolean hasDependencyPlatformEngine(Map dependencies) { + for (Entry dependency : dependencies.entrySet()) { + if (dependency.getKey().equals("org.junit.platform:junit-platform-engine")) { return true; } } @@ -3359,41 +3027,35 @@ private boolean hasDependencyPlatformEngine( Map dependencies } } - final class JUnitCoreProviderInfo - implements ProviderInfo - { + final class JUnitCoreProviderInfo implements ProviderInfo { private final Artifact junitArtifact; private final Artifact junitDepArtifact; - JUnitCoreProviderInfo( Artifact junitArtifact, Artifact junitDepArtifact ) - { + JUnitCoreProviderInfo(Artifact junitArtifact, Artifact junitDepArtifact) { this.junitArtifact = junitArtifact; this.junitDepArtifact = junitDepArtifact; } @Override - @Nonnull public String getProviderName() - { + @Nonnull + public String getProviderName() { return "org.apache.maven.surefire.junitcore.JUnitCoreProvider"; } - private boolean is47CompatibleJunitDep() - { - return isJunit47Compatible( junitDepArtifact ); + private boolean is47CompatibleJunitDep() { + return isJunit47Compatible(junitDepArtifact); } @Override - public boolean isApplicable() - { - final boolean isJunitArtifact47 = isAnyJunit4( junitArtifact ) && isJunit47Compatible( junitArtifact ); + public boolean isApplicable() { + final boolean isJunitArtifact47 = isAnyJunit4(junitArtifact) && isJunit47Compatible(junitArtifact); final boolean isAny47ProvidersForces = isAnyConcurrencySelected() || isAnyGroupsSelected(); - return isAny47ProvidersForces && ( isJunitArtifact47 || is47CompatibleJunitDep() ); + return isAny47ProvidersForces && (isJunitArtifact47 || is47CompatibleJunitDep()); } @Override - public void addProviderProperties() throws MojoExecutionException - { + public void addProviderProperties() throws MojoExecutionException { convertJunitCoreParameters(); convertGroupParameters(); convertJunitEngineParameters(); @@ -3401,55 +3063,46 @@ public void addProviderProperties() throws MojoExecutionException @Nonnull @Override - public List getJpmsArguments( @Nonnull ProviderRequirements forkRequirements ) - { + public List getJpmsArguments(@Nonnull ProviderRequirements forkRequirements) { return emptyList(); } @Override @Nonnull - public Set getProviderClasspath() throws MojoExecutionException - { + public Set getProviderClasspath() throws MojoExecutionException { String version = getBooterArtifact().getBaseVersion(); - return surefireDependencyResolver.getProviderClasspath( "surefire-junit47", version ); + return surefireDependencyResolver.getProviderClasspath("surefire-junit47", version); } } /** * Provides the Provider information for manually configured providers. */ - final class DynamicProviderInfo - implements ConfigurableProviderInfo - { + final class DynamicProviderInfo implements ConfigurableProviderInfo { final String providerName; - DynamicProviderInfo( String providerName ) - { + DynamicProviderInfo(String providerName) { this.providerName = providerName; } @Override - public ProviderInfo instantiate( String providerName ) - { - return new DynamicProviderInfo( providerName ); + public ProviderInfo instantiate(String providerName) { + return new DynamicProviderInfo(providerName); } @Override @Nonnull - public String getProviderName() - { + public String getProviderName() { return providerName; } @Override - public boolean isApplicable() - { + public boolean isApplicable() { return true; } @Override - public void addProviderProperties() throws MojoExecutionException - { + public void addProviderProperties() throws MojoExecutionException { // Ok this is a bit lazy. convertJunitCoreParameters(); convertTestNGParameters(); @@ -3457,73 +3110,60 @@ public void addProviderProperties() throws MojoExecutionException @Nonnull @Override - public List getJpmsArguments( @Nonnull ProviderRequirements forkRequirements ) - { + public List getJpmsArguments(@Nonnull ProviderRequirements forkRequirements) { return emptyList(); } @Override @Nonnull - public Set getProviderClasspath() throws MojoExecutionException - { + public Set getProviderClasspath() throws MojoExecutionException { Plugin plugin = getPluginDescriptor().getPlugin(); Map providerArtifacts = - surefireDependencyResolver.resolvePluginDependencies( plugin, getPluginArtifactMap() ); - return new LinkedHashSet<>( providerArtifacts.values() ); + surefireDependencyResolver.resolvePluginDependencies(plugin, getPluginArtifactMap()); + return new LinkedHashSet<>(providerArtifacts.values()); } } - File createSurefireBootDirectoryInBuild() - { - File tmp = new File( getProjectBuildDirectory(), getTempDir() ); + File createSurefireBootDirectoryInBuild() { + File tmp = new File(getProjectBuildDirectory(), getTempDir()); //noinspection ResultOfMethodCallIgnored tmp.mkdirs(); return tmp; } - File createSurefireBootDirectoryInTemp() - { - try - { - return Files.createTempDirectory( getTempDir() ).toFile(); - } - catch ( IOException e ) - { + File createSurefireBootDirectoryInTemp() { + try { + return Files.createTempDirectory(getTempDir()).toFile(); + } catch (IOException e) { return createSurefireBootDirectoryInBuild(); } } @Override - public ArtifactRepository getLocalRepository() - { + public ArtifactRepository getLocalRepository() { return localRepository; } @Override - public void setLocalRepository( ArtifactRepository localRepository ) - { + public void setLocalRepository(ArtifactRepository localRepository) { this.localRepository = localRepository; } - public Properties getSystemProperties() - { + public Properties getSystemProperties() { return systemProperties; } - @SuppressWarnings( "UnusedDeclaration" ) - public void setSystemProperties( Properties systemProperties ) - { + @SuppressWarnings("UnusedDeclaration") + public void setSystemProperties(Properties systemProperties) { this.systemProperties = systemProperties; } - public Map getSystemPropertyVariables() - { + public Map getSystemPropertyVariables() { return systemPropertyVariables; } - @SuppressWarnings( "UnusedDeclaration" ) - public void setSystemPropertyVariables( Map systemPropertyVariables ) - { + @SuppressWarnings("UnusedDeclaration") + public void setSystemPropertyVariables(Map systemPropertyVariables) { this.systemPropertyVariables = systemPropertyVariables; } @@ -3534,508 +3174,410 @@ public void setSystemPropertyVariables( Map systemPropertyVariab */ public abstract File getSystemPropertiesFile(); - @SuppressWarnings( "UnusedDeclaration" ) - public abstract void setSystemPropertiesFile( File systemPropertiesFile ); + @SuppressWarnings("UnusedDeclaration") + public abstract void setSystemPropertiesFile(File systemPropertiesFile); - private Properties getProperties() - { + private Properties getProperties() { return properties; } - public void setProperties( Properties properties ) - { + public void setProperties(Properties properties) { this.properties = properties; } - public Map getPluginArtifactMap() - { + public Map getPluginArtifactMap() { return pluginArtifactMap; } - @SuppressWarnings( "UnusedDeclaration" ) - public void setPluginArtifactMap( Map pluginArtifactMap ) - { + @SuppressWarnings("UnusedDeclaration") + public void setPluginArtifactMap(Map pluginArtifactMap) { this.pluginArtifactMap = pluginArtifactMap; } - public Map getProjectArtifactMap() - { + public Map getProjectArtifactMap() { return projectArtifactMap; } - @SuppressWarnings( "UnusedDeclaration" ) - public void setProjectArtifactMap( Map projectArtifactMap ) - { + @SuppressWarnings("UnusedDeclaration") + public void setProjectArtifactMap(Map projectArtifactMap) { this.projectArtifactMap = projectArtifactMap; } - public String getReportNameSuffix() - { + public String getReportNameSuffix() { return reportNameSuffix; } - @SuppressWarnings( "UnusedDeclaration" ) - public void setReportNameSuffix( String reportNameSuffix ) - { + @SuppressWarnings("UnusedDeclaration") + public void setReportNameSuffix(String reportNameSuffix) { this.reportNameSuffix = reportNameSuffix; } - - public boolean isRedirectTestOutputToFile() - { + public boolean isRedirectTestOutputToFile() { return redirectTestOutputToFile; } - @SuppressWarnings( "UnusedDeclaration" ) - public void setRedirectTestOutputToFile( boolean redirectTestOutputToFile ) - { + @SuppressWarnings("UnusedDeclaration") + public void setRedirectTestOutputToFile(boolean redirectTestOutputToFile) { this.redirectTestOutputToFile = redirectTestOutputToFile; } - - public boolean getFailIfNoTests() - { + public boolean getFailIfNoTests() { return failIfNoTests; } - public void setFailIfNoTests( boolean failIfNoTests ) - { + public void setFailIfNoTests(boolean failIfNoTests) { this.failIfNoTests = failIfNoTests; } - public String getJvm() - { + public String getJvm() { return jvm; } - public String getArgLine() - { + public String getArgLine() { return argLine; } - @SuppressWarnings( "UnusedDeclaration" ) - public void setArgLine( String argLine ) - { + @SuppressWarnings("UnusedDeclaration") + public void setArgLine(String argLine) { this.argLine = argLine; } - - public Map getEnvironmentVariables() - { + public Map getEnvironmentVariables() { return environmentVariables; } - @SuppressWarnings( "UnusedDeclaration" ) - public void setEnvironmentVariables( Map environmentVariables ) - { + @SuppressWarnings("UnusedDeclaration") + public void setEnvironmentVariables(Map environmentVariables) { this.environmentVariables = environmentVariables; } - public File getWorkingDirectory() - { + public File getWorkingDirectory() { return workingDirectory; } - @SuppressWarnings( "UnusedDeclaration" ) - public void setWorkingDirectory( File workingDirectory ) - { + @SuppressWarnings("UnusedDeclaration") + public void setWorkingDirectory(File workingDirectory) { this.workingDirectory = workingDirectory; } - public boolean isChildDelegation() - { + public boolean isChildDelegation() { return childDelegation; } - @SuppressWarnings( "UnusedDeclaration" ) - public void setChildDelegation( boolean childDelegation ) - { + @SuppressWarnings("UnusedDeclaration") + public void setChildDelegation(boolean childDelegation) { this.childDelegation = childDelegation; } - public String getGroups() - { + public String getGroups() { return groups; } - @SuppressWarnings( "UnusedDeclaration" ) - public void setGroups( String groups ) - { + @SuppressWarnings("UnusedDeclaration") + public void setGroups(String groups) { this.groups = groups; } - public String getExcludedGroups() - { + public String getExcludedGroups() { return excludedGroups; } - @SuppressWarnings( "UnusedDeclaration" ) - public void setExcludedGroups( String excludedGroups ) - { + @SuppressWarnings("UnusedDeclaration") + public void setExcludedGroups(String excludedGroups) { this.excludedGroups = excludedGroups; } - public String getJunitArtifactName() - { + public String getJunitArtifactName() { return junitArtifactName; } - @SuppressWarnings( "UnusedDeclaration" ) - public void setJunitArtifactName( String junitArtifactName ) - { + @SuppressWarnings("UnusedDeclaration") + public void setJunitArtifactName(String junitArtifactName) { this.junitArtifactName = junitArtifactName; } - public String getTestNGArtifactName() - { + public String getTestNGArtifactName() { return testNGArtifactName; } - @SuppressWarnings( "UnusedDeclaration" ) - public void setTestNGArtifactName( String testNGArtifactName ) - { + @SuppressWarnings("UnusedDeclaration") + public void setTestNGArtifactName(String testNGArtifactName) { this.testNGArtifactName = testNGArtifactName; } - public int getThreadCount() - { + public int getThreadCount() { return threadCount; } - @SuppressWarnings( "UnusedDeclaration" ) - public void setThreadCount( int threadCount ) - { + @SuppressWarnings("UnusedDeclaration") + public void setThreadCount(int threadCount) { this.threadCount = threadCount; } - public boolean getPerCoreThreadCount() - { + public boolean getPerCoreThreadCount() { return perCoreThreadCount; } - @SuppressWarnings( "UnusedDeclaration" ) - public void setPerCoreThreadCount( boolean perCoreThreadCount ) - { + @SuppressWarnings("UnusedDeclaration") + public void setPerCoreThreadCount(boolean perCoreThreadCount) { this.perCoreThreadCount = perCoreThreadCount; } - public boolean getUseUnlimitedThreads() - { + public boolean getUseUnlimitedThreads() { return useUnlimitedThreads; } - @SuppressWarnings( "UnusedDeclaration" ) - public void setUseUnlimitedThreads( boolean useUnlimitedThreads ) - { + @SuppressWarnings("UnusedDeclaration") + public void setUseUnlimitedThreads(boolean useUnlimitedThreads) { this.useUnlimitedThreads = useUnlimitedThreads; } - public String getParallel() - { + public String getParallel() { return parallel; } - @SuppressWarnings( "UnusedDeclaration" ) - public void setParallel( String parallel ) - { + @SuppressWarnings("UnusedDeclaration") + public void setParallel(String parallel) { this.parallel = parallel; } - public boolean isParallelOptimized() - { + public boolean isParallelOptimized() { return parallelOptimized; } - @SuppressWarnings( "UnusedDeclaration" ) - public void setParallelOptimized( boolean parallelOptimized ) - { + @SuppressWarnings("UnusedDeclaration") + public void setParallelOptimized(boolean parallelOptimized) { this.parallelOptimized = parallelOptimized; } - public int getThreadCountSuites() - { + public int getThreadCountSuites() { return threadCountSuites; } - public void setThreadCountSuites( int threadCountSuites ) - { + public void setThreadCountSuites(int threadCountSuites) { this.threadCountSuites = threadCountSuites; } - public int getThreadCountClasses() - { + public int getThreadCountClasses() { return threadCountClasses; } - public void setThreadCountClasses( int threadCountClasses ) - { + public void setThreadCountClasses(int threadCountClasses) { this.threadCountClasses = threadCountClasses; } - public int getThreadCountMethods() - { + public int getThreadCountMethods() { return threadCountMethods; } - public void setThreadCountMethods( int threadCountMethods ) - { + public void setThreadCountMethods(int threadCountMethods) { this.threadCountMethods = threadCountMethods; } - public boolean isTrimStackTrace() - { + public boolean isTrimStackTrace() { return trimStackTrace; } - @SuppressWarnings( "UnusedDeclaration" ) - public void setTrimStackTrace( boolean trimStackTrace ) - { + @SuppressWarnings("UnusedDeclaration") + public void setTrimStackTrace(boolean trimStackTrace) { this.trimStackTrace = trimStackTrace; } - public List getProjectRemoteRepositories() - { + public List getProjectRemoteRepositories() { return projectRemoteRepositories; } - @SuppressWarnings( "UnusedDeclaration" ) - public void setProjectRemoteRepositories( List projectRemoteRepositories ) - { + @SuppressWarnings("UnusedDeclaration") + public void setProjectRemoteRepositories(List projectRemoteRepositories) { this.projectRemoteRepositories = projectRemoteRepositories; } - public List getRemoteRepositories() - { + public List getRemoteRepositories() { return remoteRepositories; } - @SuppressWarnings( "UnusedDeclaration" ) - public void setRemoteRepositories( List remoteRepositories ) - { + @SuppressWarnings("UnusedDeclaration") + public void setRemoteRepositories(List remoteRepositories) { this.remoteRepositories = remoteRepositories; } - public boolean isDisableXmlReport() - { + public boolean isDisableXmlReport() { return disableXmlReport; } - @SuppressWarnings( "UnusedDeclaration" ) - public void setDisableXmlReport( boolean disableXmlReport ) - { + @SuppressWarnings("UnusedDeclaration") + public void setDisableXmlReport(boolean disableXmlReport) { this.disableXmlReport = disableXmlReport; } - - public boolean isEnableAssertions() - { + public boolean isEnableAssertions() { return enableAssertions; } - public boolean effectiveIsEnableAssertions() - { - if ( getArgLine() != null ) - { - List args = asList( getArgLine().split( " " ) ); - if ( args.contains( "-da" ) || args.contains( "-disableassertions" ) ) - { + public boolean effectiveIsEnableAssertions() { + if (getArgLine() != null) { + List args = asList(getArgLine().split(" ")); + if (args.contains("-da") || args.contains("-disableassertions")) { return false; } } return isEnableAssertions(); } - @SuppressWarnings( "UnusedDeclaration" ) - public void setEnableAssertions( boolean enableAssertions ) - { + @SuppressWarnings("UnusedDeclaration") + public void setEnableAssertions(boolean enableAssertions) { this.enableAssertions = enableAssertions; } - public MavenSession getSession() - { + public MavenSession getSession() { return session; } - @SuppressWarnings( "UnusedDeclaration" ) - public void setSession( MavenSession session ) - { + @SuppressWarnings("UnusedDeclaration") + public void setSession(MavenSession session) { this.session = session; } - public String getObjectFactory() - { + public String getObjectFactory() { return objectFactory; } - @SuppressWarnings( "UnusedDeclaration" ) - public void setObjectFactory( String objectFactory ) - { + @SuppressWarnings("UnusedDeclaration") + public void setObjectFactory(String objectFactory) { this.objectFactory = objectFactory; } - public ToolchainManager getToolchainManager() - { + public ToolchainManager getToolchainManager() { return toolchainManager; } - @SuppressWarnings( "UnusedDeclaration" ) - public void setToolchainManager( ToolchainManager toolchainManager ) - { + @SuppressWarnings("UnusedDeclaration") + public void setToolchainManager(ToolchainManager toolchainManager) { this.toolchainManager = toolchainManager; } - public boolean isMavenParallel() - { + public boolean isMavenParallel() { return parallelMavenExecution != null && parallelMavenExecution; } - public String[] getDependenciesToScan() - { + public String[] getDependenciesToScan() { return dependenciesToScan; } - public void setDependenciesToScan( String[] dependenciesToScan ) - { + public void setDependenciesToScan(String[] dependenciesToScan) { this.dependenciesToScan = dependenciesToScan; } - @SuppressWarnings( "UnusedDeclaration" ) - void setPluginDescriptor( PluginDescriptor pluginDescriptor ) - { + @SuppressWarnings("UnusedDeclaration") + void setPluginDescriptor(PluginDescriptor pluginDescriptor) { this.pluginDescriptor = pluginDescriptor; } - public PluginDescriptor getPluginDescriptor() - { + public PluginDescriptor getPluginDescriptor() { return pluginDescriptor; } - public MavenProject getProject() - { + public MavenProject getProject() { return project; } - @SuppressWarnings( "UnusedDeclaration" ) - public void setProject( MavenProject project ) - { + @SuppressWarnings("UnusedDeclaration") + public void setProject(MavenProject project) { this.project = project; } @Override - public File getTestSourceDirectory() - { + public File getTestSourceDirectory() { return testSourceDirectory; } @Override - public void setTestSourceDirectory( File testSourceDirectory ) - { + public void setTestSourceDirectory(File testSourceDirectory) { this.testSourceDirectory = testSourceDirectory; } - public String getForkCount() - { + public String getForkCount() { return forkCount; } - public boolean isReuseForks() - { + public boolean isReuseForks() { return reuseForks; } - public String[] getAdditionalClasspathElements() - { + public String[] getAdditionalClasspathElements() { return additionalClasspathElements; } - public void setAdditionalClasspathElements( String[] additionalClasspathElements ) - { + public void setAdditionalClasspathElements(String[] additionalClasspathElements) { this.additionalClasspathElements = additionalClasspathElements; } - public String[] getClasspathDependencyExcludes() - { + public String[] getClasspathDependencyExcludes() { return classpathDependencyExcludes; } - public void setClasspathDependencyExcludes( String[] classpathDependencyExcludes ) - { + public void setClasspathDependencyExcludes(String[] classpathDependencyExcludes) { this.classpathDependencyExcludes = classpathDependencyExcludes; } - public String getClasspathDependencyScopeExclude() - { + public String getClasspathDependencyScopeExclude() { return classpathDependencyScopeExclude; } - public void setClasspathDependencyScopeExclude( String classpathDependencyScopeExclude ) - { + public void setClasspathDependencyScopeExclude(String classpathDependencyScopeExclude) { this.classpathDependencyScopeExclude = classpathDependencyScopeExclude; } - public File getProjectBuildDirectory() - { + public File getProjectBuildDirectory() { return projectBuildDirectory; } - public void setProjectBuildDirectory( File projectBuildDirectory ) - { + public void setProjectBuildDirectory(File projectBuildDirectory) { this.projectBuildDirectory = projectBuildDirectory; } - protected void logDebugOrCliShowErrors( String s ) - { - SurefireHelper.logDebugOrCliShowErrors( s, getConsoleLogger(), cli ); + protected void logDebugOrCliShowErrors(String s) { + SurefireHelper.logDebugOrCliShowErrors(s, getConsoleLogger(), cli); } - public Map getJdkToolchain() - { + public Map getJdkToolchain() { return jdkToolchain; } - public void setJdkToolchain( Map jdkToolchain ) - { + public void setJdkToolchain(Map jdkToolchain) { this.jdkToolchain = jdkToolchain; } - public String getTempDir() - { + public String getTempDir() { return tempDir; } - public void setTempDir( String tempDir ) - { + public void setTempDir(String tempDir) { this.tempDir = tempDir; } - public void setResolutionErrorHandler( ResolutionErrorHandler resolutionErrorHandler ) - { + public void setResolutionErrorHandler(ResolutionErrorHandler resolutionErrorHandler) { this.resolutionErrorHandler = resolutionErrorHandler; } - private static final class ClasspathCache - { - private final Map classpaths = new HashMap<>( 4 ); + private static final class ClasspathCache { + private final Map classpaths = new HashMap<>(4); - private Classpath getCachedClassPath( @Nonnull String artifactId ) - { - return classpaths.get( artifactId ); + private Classpath getCachedClassPath(@Nonnull String artifactId) { + return classpaths.get(artifactId); } - private void setCachedClasspath( @Nonnull String key, @Nonnull Classpath classpath ) - { - classpaths.put( key, classpath ); + private void setCachedClasspath(@Nonnull String key, @Nonnull Classpath classpath) { + classpaths.put(key, classpath); } - private Classpath setCachedClasspath( @Nonnull String key, @Nonnull Set artifacts ) - { + private Classpath setCachedClasspath(@Nonnull String key, @Nonnull Set artifacts) { Collection files = new ArrayList<>(); - for ( Artifact artifact : artifacts ) - { - files.add( artifact.getFile().getAbsolutePath() ); + for (Artifact artifact : artifacts) { + files.add(artifact.getFile().getAbsolutePath()); } - Classpath classpath = new Classpath( files ); - setCachedClasspath( key, classpath ); + Classpath classpath = new Classpath(files); + setCachedClasspath(key, classpath); return classpath; } } @@ -4043,8 +3585,7 @@ private Classpath setCachedClasspath( @Nonnull String key, @Nonnull Set CLASSPATHS = - new ConcurrentHashMap<>( 4 ); +public class ClasspathCache { + private static final ConcurrentHashMap CLASSPATHS = new ConcurrentHashMap<>(4); - public static Classpath getCachedClassPath( @Nonnull String artifactId ) - { - return CLASSPATHS.get( artifactId ); + public static Classpath getCachedClassPath(@Nonnull String artifactId) { + return CLASSPATHS.get(artifactId); } - public static void setCachedClasspath( @Nonnull String key, @Nonnull Classpath classpath ) - { - CLASSPATHS.put( key, classpath ); + public static void setCachedClasspath(@Nonnull String key, @Nonnull Classpath classpath) { + CLASSPATHS.put(key, classpath); } - public static Classpath setCachedClasspath( @Nonnull String key, @Nonnull Set artifacts ) - { + public static Classpath setCachedClasspath(@Nonnull String key, @Nonnull Set artifacts) { Collection files = new ArrayList<>(); - for ( Artifact artifact : artifacts ) - { - files.add( artifact.getFile().getAbsolutePath() ); + for (Artifact artifact : artifacts) { + files.add(artifact.getFile().getAbsolutePath()); } - Classpath classpath = new Classpath( files ); - setCachedClasspath( key, classpath ); + Classpath classpath = new Classpath(files); + setCachedClasspath(key, classpath); return classpath; } } diff --git a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/CommonReflector.java b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/CommonReflector.java index 59497ad008..0d76ee8ce9 100644 --- a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/CommonReflector.java +++ b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/CommonReflector.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,12 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.surefire; + +import javax.annotation.Nonnull; + +import java.io.File; +import java.lang.reflect.Constructor; import org.apache.maven.plugin.surefire.extensions.SurefireConsoleOutputReporter; import org.apache.maven.plugin.surefire.extensions.SurefireStatelessReporter; @@ -27,10 +31,6 @@ import org.apache.maven.plugin.surefire.report.DefaultReporterFactory; import org.apache.maven.surefire.api.util.SurefireReflectionException; -import javax.annotation.Nonnull; -import java.io.File; -import java.lang.reflect.Constructor; - import static org.apache.maven.surefire.api.util.ReflectionUtils.getConstructor; import static org.apache.maven.surefire.api.util.ReflectionUtils.instantiateObject; import static org.apache.maven.surefire.api.util.ReflectionUtils.newInstance; @@ -38,8 +38,7 @@ /** * @author Kristian Rosenvold */ -public class CommonReflector -{ +public class CommonReflector { private final Class startupReportConfiguration; private final Class consoleLogger; private final Class statelessTestsetReporter; @@ -47,67 +46,76 @@ public class CommonReflector private final Class statelessTestsetInfoReporter; private final ClassLoader surefireClassLoader; - public CommonReflector( @Nonnull ClassLoader surefireClassLoader ) - { + public CommonReflector(@Nonnull ClassLoader surefireClassLoader) { this.surefireClassLoader = surefireClassLoader; - try - { - startupReportConfiguration = surefireClassLoader.loadClass( StartupReportConfiguration.class.getName() ); - consoleLogger = surefireClassLoader.loadClass( ConsoleLogger.class.getName() ); - statelessTestsetReporter = surefireClassLoader.loadClass( SurefireStatelessReporter.class.getName() ); - consoleOutputReporter = surefireClassLoader.loadClass( SurefireConsoleOutputReporter.class.getName() ); + try { + startupReportConfiguration = surefireClassLoader.loadClass(StartupReportConfiguration.class.getName()); + consoleLogger = surefireClassLoader.loadClass(ConsoleLogger.class.getName()); + statelessTestsetReporter = surefireClassLoader.loadClass(SurefireStatelessReporter.class.getName()); + consoleOutputReporter = surefireClassLoader.loadClass(SurefireConsoleOutputReporter.class.getName()); statelessTestsetInfoReporter = - surefireClassLoader.loadClass( SurefireStatelessTestsetInfoReporter.class.getName() ); - } - catch ( ClassNotFoundException e ) - { - throw new SurefireReflectionException( e ); + surefireClassLoader.loadClass(SurefireStatelessTestsetInfoReporter.class.getName()); + } catch (ClassNotFoundException e) { + throw new SurefireReflectionException(e); } } - public Object createReportingReporterFactory( @Nonnull StartupReportConfiguration startupReportConfiguration, - @Nonnull ConsoleLogger consoleLogger ) - { - Class[] args = { this.startupReportConfiguration, this.consoleLogger }; - Object src = createStartupReportConfiguration( startupReportConfiguration ); - Object logger = createConsoleLogger( consoleLogger, surefireClassLoader ); - Object[] params = { src, logger }; - return instantiateObject( DefaultReporterFactory.class.getName(), args, params, surefireClassLoader ); + public Object createReportingReporterFactory( + @Nonnull StartupReportConfiguration startupReportConfiguration, @Nonnull ConsoleLogger consoleLogger) { + Class[] args = {this.startupReportConfiguration, this.consoleLogger}; + Object src = createStartupReportConfiguration(startupReportConfiguration); + Object logger = createConsoleLogger(consoleLogger, surefireClassLoader); + Object[] params = {src, logger}; + return instantiateObject(DefaultReporterFactory.class.getName(), args, params, surefireClassLoader); } - private Object createStartupReportConfiguration( @Nonnull StartupReportConfiguration reporterConfiguration ) - { - Constructor constructor = getConstructor( startupReportConfiguration, boolean.class, boolean.class, - String.class, boolean.class, File.class, - boolean.class, String.class, File.class, boolean.class, - int.class, String.class, String.class, boolean.class, - statelessTestsetReporter, consoleOutputReporter, - statelessTestsetInfoReporter ); - Object[] params = { reporterConfiguration.isUseFile(), reporterConfiguration.isPrintSummary(), - reporterConfiguration.getReportFormat(), reporterConfiguration.isRedirectTestOutputToFile(), + private Object createStartupReportConfiguration(@Nonnull StartupReportConfiguration reporterConfiguration) { + Constructor constructor = getConstructor( + startupReportConfiguration, + boolean.class, + boolean.class, + String.class, + boolean.class, + File.class, + boolean.class, + String.class, + File.class, + boolean.class, + int.class, + String.class, + String.class, + boolean.class, + statelessTestsetReporter, + consoleOutputReporter, + statelessTestsetInfoReporter); + Object[] params = { + reporterConfiguration.isUseFile(), + reporterConfiguration.isPrintSummary(), + reporterConfiguration.getReportFormat(), + reporterConfiguration.isRedirectTestOutputToFile(), reporterConfiguration.getReportsDirectory(), - reporterConfiguration.isTrimStackTrace(), reporterConfiguration.getReportNameSuffix(), - reporterConfiguration.getStatisticsFile(), reporterConfiguration.isRequiresRunHistory(), - reporterConfiguration.getRerunFailingTestsCount(), reporterConfiguration.getXsdSchemaLocation(), - reporterConfiguration.getEncoding().name(), reporterConfiguration.isForking(), - reporterConfiguration.getXmlReporter().clone( surefireClassLoader ), - reporterConfiguration.getConsoleOutputReporter().clone( surefireClassLoader ), - reporterConfiguration.getTestsetReporter().clone( surefireClassLoader ) + reporterConfiguration.isTrimStackTrace(), + reporterConfiguration.getReportNameSuffix(), + reporterConfiguration.getStatisticsFile(), + reporterConfiguration.isRequiresRunHistory(), + reporterConfiguration.getRerunFailingTestsCount(), + reporterConfiguration.getXsdSchemaLocation(), + reporterConfiguration.getEncoding().name(), + reporterConfiguration.isForking(), + reporterConfiguration.getXmlReporter().clone(surefireClassLoader), + reporterConfiguration.getConsoleOutputReporter().clone(surefireClassLoader), + reporterConfiguration.getTestsetReporter().clone(surefireClassLoader) }; - return newInstance( constructor, params ); + return newInstance(constructor, params); } - static Object createConsoleLogger( ConsoleLogger consoleLogger, ClassLoader cl ) - { - try - { - Class decoratorClass = cl.loadClass( ConsoleLoggerDecorator.class.getName() ); - return getConstructor( decoratorClass, Object.class ).newInstance( consoleLogger ); - } - catch ( Exception e ) - { - throw new SurefireReflectionException( e ); + static Object createConsoleLogger(ConsoleLogger consoleLogger, ClassLoader cl) { + try { + Class decoratorClass = cl.loadClass(ConsoleLoggerDecorator.class.getName()); + return getConstructor(decoratorClass, Object.class).newInstance(consoleLogger); + } catch (Exception e) { + throw new SurefireReflectionException(e); } } } diff --git a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/InPluginVMSurefireStarter.java b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/InPluginVMSurefireStarter.java index 78bc9202c5..7d4d879bc3 100644 --- a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/InPluginVMSurefireStarter.java +++ b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/InPluginVMSurefireStarter.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,20 +16,22 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.surefire; + +import javax.annotation.Nonnull; + +import java.lang.reflect.InvocationTargetException; +import java.util.Map; import org.apache.maven.plugin.surefire.booterclient.Platform; import org.apache.maven.plugin.surefire.log.api.ConsoleLogger; +import org.apache.maven.surefire.api.suite.RunResult; +import org.apache.maven.surefire.api.testset.TestSetFailedException; +import org.apache.maven.surefire.api.util.DefaultScanResult; import org.apache.maven.surefire.booter.ClasspathConfiguration; import org.apache.maven.surefire.booter.ProviderConfiguration; import org.apache.maven.surefire.booter.StartupConfiguration; import org.apache.maven.surefire.booter.SurefireExecutionException; -import org.apache.maven.surefire.api.suite.RunResult; -import org.apache.maven.surefire.api.testset.TestSetFailedException; -import org.apache.maven.surefire.api.util.DefaultScanResult; - -import javax.annotation.Nonnull; -import java.lang.reflect.InvocationTargetException; -import java.util.Map; import static org.apache.maven.surefire.booter.ProviderFactory.invokeProvider; @@ -47,19 +47,19 @@ * @author Dan Fabulich * @author Kristian Rosenvold */ -public class InPluginVMSurefireStarter -{ +public class InPluginVMSurefireStarter { private final StartupConfiguration startupConfig; private final StartupReportConfiguration startupReportConfig; private final ProviderConfiguration providerConfig; private final ConsoleLogger consoleLogger; private final Platform platform; - public InPluginVMSurefireStarter( @Nonnull StartupConfiguration startupConfig, - @Nonnull ProviderConfiguration providerConfig, - @Nonnull StartupReportConfiguration startupReportConfig, - @Nonnull ConsoleLogger consoleLogger, @Nonnull Platform platform ) - { + public InPluginVMSurefireStarter( + @Nonnull StartupConfiguration startupConfig, + @Nonnull ProviderConfiguration providerConfig, + @Nonnull StartupReportConfiguration startupReportConfig, + @Nonnull ConsoleLogger consoleLogger, + @Nonnull Platform platform) { this.startupConfig = startupConfig; this.startupReportConfig = startupReportConfig; this.providerConfig = providerConfig; @@ -67,34 +67,30 @@ public InPluginVMSurefireStarter( @Nonnull StartupConfiguration startupConfig, this.platform = platform; } - public RunResult runSuitesInProcess( @Nonnull DefaultScanResult scanResult ) - throws SurefireExecutionException, TestSetFailedException - { + public RunResult runSuitesInProcess(@Nonnull DefaultScanResult scanResult) + throws SurefireExecutionException, TestSetFailedException { // The test classloader must be constructed first to avoid issues with commons-logging until we properly // separate the TestNG classloader Map providerProperties = providerConfig.getProviderProperties(); - scanResult.writeTo( providerProperties ); + scanResult.writeTo(providerProperties); startupConfig.writeSurefireTestClasspathProperty(); - ClassLoader testClassLoader = startupConfig.getClasspathConfiguration() - .toRealPath( ClasspathConfiguration.class ) + ClassLoader testClassLoader = startupConfig + .getClasspathConfiguration() + .toRealPath(ClasspathConfiguration.class) .createMergedClassLoader(); - CommonReflector surefireReflector = new CommonReflector( testClassLoader ); + CommonReflector surefireReflector = new CommonReflector(testClassLoader); - Object factory = surefireReflector.createReportingReporterFactory( startupReportConfig, consoleLogger ); + Object factory = surefireReflector.createReportingReporterFactory(startupReportConfig, consoleLogger); - try - { + try { return platform.isShutdown() - ? new RunResult( 0, 0, 0, 0 ) - : invokeProvider( null, testClassLoader, factory, providerConfig, false, startupConfig, true ); - } - catch ( InvocationTargetException e ) - { - throw new SurefireExecutionException( "Exception in provider", e.getTargetException() ); + ? new RunResult(0, 0, 0, 0) + : invokeProvider(null, testClassLoader, factory, providerConfig, false, startupConfig, true); + } catch (InvocationTargetException e) { + throw new SurefireExecutionException("Exception in provider", e.getTargetException()); } } - } diff --git a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/JdkAttributes.java b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/JdkAttributes.java index f8ab5f790c..69b1cfb099 100644 --- a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/JdkAttributes.java +++ b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/JdkAttributes.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.surefire; import java.io.File; @@ -28,36 +27,30 @@ * @author Tibor Digana (tibor17) * @since 2.20.1 */ -public final class JdkAttributes -{ +public final class JdkAttributes { private final File jvmExecutable; private final File jdkHome; private final boolean java9AtLeast; - public JdkAttributes( File jvmExecutable, File jdkHome, boolean java9AtLeast ) - { - this.jvmExecutable = requireNonNull( jvmExecutable, "null path to java executable" ); + public JdkAttributes(File jvmExecutable, File jdkHome, boolean java9AtLeast) { + this.jvmExecutable = requireNonNull(jvmExecutable, "null path to java executable"); this.jdkHome = jdkHome; this.java9AtLeast = java9AtLeast; } - public JdkAttributes( String jvmExecutable, boolean java9AtLeast ) - { - this( new File( jvmExecutable ), toJdkHomeFromJvmExec( jvmExecutable ), java9AtLeast ); + public JdkAttributes(String jvmExecutable, boolean java9AtLeast) { + this(new File(jvmExecutable), toJdkHomeFromJvmExec(jvmExecutable), java9AtLeast); } - public File getJvmExecutable() - { + public File getJvmExecutable() { return jvmExecutable; } - public File getJdkHome() - { + public File getJdkHome() { return jdkHome; } - public boolean isJava9AtLeast() - { + public boolean isJava9AtLeast() { return java9AtLeast; } } diff --git a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/ResolvePathResultWrapper.java b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/ResolvePathResultWrapper.java index 9197d89a33..b13bdc7bb7 100644 --- a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/ResolvePathResultWrapper.java +++ b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/ResolvePathResultWrapper.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,33 +16,30 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.surefire; import org.codehaus.plexus.languages.java.jpms.ResolvePathResult; /** * Wraps {@link ResolvePathResult} and place marker. */ -final class ResolvePathResultWrapper -{ +final class ResolvePathResultWrapper { private final ResolvePathResult resolvePathResult; private final boolean isMainModuleDescriptor; - ResolvePathResultWrapper( ResolvePathResult resolvePathResult, boolean isMainModuleDescriptor ) - { + ResolvePathResultWrapper(ResolvePathResult resolvePathResult, boolean isMainModuleDescriptor) { this.resolvePathResult = resolvePathResult; this.isMainModuleDescriptor = isMainModuleDescriptor; } - ResolvePathResult getResolvePathResult() - { + ResolvePathResult getResolvePathResult() { return resolvePathResult; } /** * @return {@code true} if module-info appears in src/main/java module */ - boolean isMainModuleDescriptor() - { + boolean isMainModuleDescriptor() { return isMainModuleDescriptor; } } diff --git a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/StartupReportConfiguration.java b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/StartupReportConfiguration.java index f6b4c27b83..d42e22cdac 100644 --- a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/StartupReportConfiguration.java +++ b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/StartupReportConfiguration.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,16 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.surefire; + +import javax.annotation.Nonnull; + +import java.io.File; +import java.io.PrintStream; +import java.nio.charset.Charset; +import java.util.Deque; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; import org.apache.maven.plugin.surefire.extensions.DefaultStatelessReportMojoConfiguration; import org.apache.maven.plugin.surefire.extensions.SurefireConsoleOutputReporter; @@ -32,19 +40,11 @@ import org.apache.maven.surefire.extensions.StatelessTestsetInfoConsoleReportEventListener; import org.apache.maven.surefire.extensions.StatelessTestsetInfoFileReportEventListener; -import javax.annotation.Nonnull; -import java.io.File; -import java.io.PrintStream; -import java.nio.charset.Charset; -import java.util.Deque; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - import static java.nio.charset.StandardCharsets.UTF_8; -import static org.apache.maven.surefire.shared.lang3.StringUtils.trimToNull; import static org.apache.maven.plugin.surefire.SurefireHelper.replaceForkThreadsInPath; import static org.apache.maven.plugin.surefire.report.ConsoleReporter.BRIEF; import static org.apache.maven.plugin.surefire.report.ConsoleReporter.PLAIN; +import static org.apache.maven.surefire.shared.lang3.StringUtils.trimToNull; /** * All the parameters used to construct reporters @@ -52,8 +52,7 @@ * * @author Kristian Rosenvold */ -public final class StartupReportConfiguration -{ +public final class StartupReportConfiguration { private final PrintStream originalSystemOut; private final PrintStream originalSystemErr; @@ -94,15 +93,24 @@ public final class StartupReportConfiguration private StatisticsReporter statisticsReporter; - @SuppressWarnings( "checkstyle:parameternumber" ) - public StartupReportConfiguration( boolean useFile, boolean printSummary, String reportFormat, - boolean redirectTestOutputToFile, - @Nonnull File reportsDirectory, boolean trimStackTrace, String reportNameSuffix, - File statisticsFile, boolean requiresRunHistory, int rerunFailingTestsCount, - String xsdSchemaLocation, String encoding, boolean isForking, - SurefireStatelessReporter xmlReporter, SurefireConsoleOutputReporter consoleOutputReporter, - SurefireStatelessTestsetInfoReporter testsetReporter ) - { + @SuppressWarnings("checkstyle:parameternumber") + public StartupReportConfiguration( + boolean useFile, + boolean printSummary, + String reportFormat, + boolean redirectTestOutputToFile, + @Nonnull File reportsDirectory, + boolean trimStackTrace, + String reportNameSuffix, + File statisticsFile, + boolean requiresRunHistory, + int rerunFailingTestsCount, + String xsdSchemaLocation, + String encoding, + boolean isForking, + SurefireStatelessReporter xmlReporter, + SurefireConsoleOutputReporter consoleOutputReporter, + SurefireStatelessTestsetInfoReporter testsetReporter) { this.useFile = useFile; this.printSummary = printSummary; this.reportFormat = reportFormat; @@ -116,160 +124,138 @@ public StartupReportConfiguration( boolean useFile, boolean printSummary, String this.originalSystemErr = System.err; this.rerunFailingTestsCount = rerunFailingTestsCount; this.xsdSchemaLocation = xsdSchemaLocation; - String charset = trimToNull( encoding ); - this.encoding = charset == null ? UTF_8 : Charset.forName( charset ); + String charset = trimToNull(encoding); + this.encoding = charset == null ? UTF_8 : Charset.forName(charset); this.isForking = isForking; this.xmlReporter = xmlReporter; this.consoleOutputReporter = consoleOutputReporter; this.testsetReporter = testsetReporter; } - public boolean isUseFile() - { + public boolean isUseFile() { return useFile; } - public boolean isPrintSummary() - { + public boolean isPrintSummary() { return printSummary; } - public String getReportFormat() - { + public String getReportFormat() { return reportFormat; } - public String getReportNameSuffix() - { + public String getReportNameSuffix() { return reportNameSuffix; } - public boolean isRedirectTestOutputToFile() - { + public boolean isRedirectTestOutputToFile() { return redirectTestOutputToFile; } - public File getReportsDirectory() - { + public File getReportsDirectory() { return reportsDirectory; } - public int getRerunFailingTestsCount() - { + public int getRerunFailingTestsCount() { return rerunFailingTestsCount; } public StatelessReportEventListener instantiateStatelessXmlReporter( - Integer forkNumber ) - { - assert ( forkNumber == null ) == !isForking; + Integer forkNumber) { + assert (forkNumber == null) == !isForking; // If forking TestNG the suites have same name 'TestSuite' and tend to override report statistics in stateful // reporter, see Surefire1535TestNGParallelSuitesIT. The testClassMethodRunHistory should be isolated. // In the in-plugin execution of parallel JUnit4.7 with rerun the map must be shared because reports and // listeners are in ThreadLocal, see Surefire1122ParallelAndFlakyTestsIT. - Map> testClassMethodRunHistory - = isForking - ? new ConcurrentHashMap>() - : this.testClassMethodRunHistory; - - DefaultStatelessReportMojoConfiguration xmlReporterConfig = - new DefaultStatelessReportMojoConfiguration( resolveReportsDirectory( forkNumber ), reportNameSuffix, - trimStackTrace, rerunFailingTestsCount, xsdSchemaLocation, testClassMethodRunHistory ); - - return xmlReporter.isDisable() ? null : xmlReporter.createListener( xmlReporterConfig ); + Map> testClassMethodRunHistory = + isForking ? new ConcurrentHashMap>() : this.testClassMethodRunHistory; + + DefaultStatelessReportMojoConfiguration xmlReporterConfig = new DefaultStatelessReportMojoConfiguration( + resolveReportsDirectory(forkNumber), + reportNameSuffix, + trimStackTrace, + rerunFailingTestsCount, + xsdSchemaLocation, + testClassMethodRunHistory); + + return xmlReporter.isDisable() ? null : xmlReporter.createListener(xmlReporterConfig); } public StatelessTestsetInfoFileReportEventListener instantiateFileReporter( - Integer forkNumber ) - { + Integer forkNumber) { return !testsetReporter.isDisable() && isUseFile() && isBriefOrPlainFormat() - ? testsetReporter.createListener( resolveReportsDirectory( forkNumber ), reportNameSuffix, encoding ) - : null; + ? testsetReporter.createListener(resolveReportsDirectory(forkNumber), reportNameSuffix, encoding) + : null; } public StatelessTestsetInfoConsoleReportEventListener instantiateConsoleReporter( - ConsoleLogger consoleLogger ) - { + ConsoleLogger consoleLogger) { return !testsetReporter.isDisable() && shouldReportToConsole() - ? testsetReporter.createListener( consoleLogger ) : null; + ? testsetReporter.createListener(consoleLogger) + : null; } - public boolean isBriefOrPlainFormat() - { + public boolean isBriefOrPlainFormat() { String fmt = getReportFormat(); - return BRIEF.equals( fmt ) || PLAIN.equals( fmt ); + return BRIEF.equals(fmt) || PLAIN.equals(fmt); } - public ConsoleOutputReportEventListener instantiateConsoleOutputFileReporter( Integer forkNum ) - { + public ConsoleOutputReportEventListener instantiateConsoleOutputFileReporter(Integer forkNum) { ConsoleOutputReportEventListener outputReport = isRedirectTestOutputToFile() - ? consoleOutputReporter.createListener( resolveReportsDirectory( forkNum ), reportNameSuffix, forkNum ) - : consoleOutputReporter.createListener( originalSystemOut, originalSystemErr ); + ? consoleOutputReporter.createListener(resolveReportsDirectory(forkNum), reportNameSuffix, forkNum) + : consoleOutputReporter.createListener(originalSystemOut, originalSystemErr); return consoleOutputReporter.isDisable() ? null : outputReport; } - public synchronized StatisticsReporter getStatisticsReporter() - { - if ( statisticsReporter == null ) - { - statisticsReporter = requiresRunHistory ? new StatisticsReporter( statisticsFile ) : null; + public synchronized StatisticsReporter getStatisticsReporter() { + if (statisticsReporter == null) { + statisticsReporter = requiresRunHistory ? new StatisticsReporter(statisticsFile) : null; } return statisticsReporter; } - public File getStatisticsFile() - { + public File getStatisticsFile() { return statisticsFile; } - public boolean isTrimStackTrace() - { + public boolean isTrimStackTrace() { return trimStackTrace; } - public boolean isRequiresRunHistory() - { + public boolean isRequiresRunHistory() { return requiresRunHistory; } - public String getXsdSchemaLocation() - { + public String getXsdSchemaLocation() { return xsdSchemaLocation; } - public Charset getEncoding() - { + public Charset getEncoding() { return encoding; } - public boolean isForking() - { + public boolean isForking() { return isForking; } - private File resolveReportsDirectory( Integer forkNumber ) - { - return forkNumber == null ? reportsDirectory : replaceForkThreadsInPath( reportsDirectory, forkNumber ); + private File resolveReportsDirectory(Integer forkNumber) { + return forkNumber == null ? reportsDirectory : replaceForkThreadsInPath(reportsDirectory, forkNumber); } - public SurefireStatelessReporter getXmlReporter() - { + public SurefireStatelessReporter getXmlReporter() { return xmlReporter; } - public SurefireConsoleOutputReporter getConsoleOutputReporter() - { + public SurefireConsoleOutputReporter getConsoleOutputReporter() { return consoleOutputReporter; } - public SurefireStatelessTestsetInfoReporter getTestsetReporter() - { + public SurefireStatelessTestsetInfoReporter getTestsetReporter() { return testsetReporter; } - private boolean shouldReportToConsole() - { + private boolean shouldReportToConsole() { return isUseFile() ? isPrintSummary() : isRedirectTestOutputToFile() || isBriefOrPlainFormat(); } } diff --git a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/SurefireDependencyResolver.java b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/SurefireDependencyResolver.java index 45de14dd75..9af9db2780 100644 --- a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/SurefireDependencyResolver.java +++ b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/SurefireDependencyResolver.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.surefire; import javax.annotation.Nonnull; import javax.annotation.Nullable; @@ -60,8 +59,7 @@ * @author Stephen Connolly * @author Kristian Rosenvold */ -final class SurefireDependencyResolver -{ +final class SurefireDependencyResolver { static final String PROVIDER_GROUP_ID = "org.apache.maven.surefire"; private static final String[] PROVIDER_CLASSPATH_ORDER = { @@ -96,13 +94,15 @@ final class SurefireDependencyResolver private final boolean offline; - SurefireDependencyResolver( RepositorySystem repositorySystem, ConsoleLogger log, - ArtifactRepository localRepository, - List pluginRemoteRepositories, - List projectRemoteRepositories, - ResolutionErrorHandler resolutionErrorHandler, - String pluginName, boolean offline ) - { + SurefireDependencyResolver( + RepositorySystem repositorySystem, + ConsoleLogger log, + ArtifactRepository localRepository, + List pluginRemoteRepositories, + List projectRemoteRepositories, + ResolutionErrorHandler resolutionErrorHandler, + String pluginName, + boolean offline) { this.repositorySystem = repositorySystem; this.log = log; this.localRepository = localRepository; @@ -113,185 +113,154 @@ final class SurefireDependencyResolver this.offline = offline; } - static boolean isWithinVersionSpec( @Nullable Artifact artifact, @Nonnull String versionSpec ) - { - if ( artifact == null ) - { + static boolean isWithinVersionSpec(@Nullable Artifact artifact, @Nonnull String versionSpec) { + if (artifact == null) { return false; } - try - { - VersionRange range = createFromVersionSpec( versionSpec ); - try - { - return range.containsVersion( artifact.getSelectedVersion() ); + try { + VersionRange range = createFromVersionSpec(versionSpec); + try { + return range.containsVersion(artifact.getSelectedVersion()); + } catch (NullPointerException e) { + return range.containsVersion(new DefaultArtifactVersion(artifact.getBaseVersion())); } - catch ( NullPointerException e ) - { - return range.containsVersion( new DefaultArtifactVersion( artifact.getBaseVersion() ) ); - } - } - catch ( InvalidVersionSpecificationException | OverConstrainedVersionException e ) - { - throw new RuntimeException( "Bug in plugin. Please report with stacktrace" ); + } catch (InvalidVersionSpecificationException | OverConstrainedVersionException e) { + throw new RuntimeException("Bug in plugin. Please report with stacktrace"); } } - Map resolvePluginDependencies( Plugin plugin, Map pluginResolvedDependencies ) - throws MojoExecutionException - { + Map resolvePluginDependencies(Plugin plugin, Map pluginResolvedDependencies) + throws MojoExecutionException { Map resolved = new LinkedHashMap<>(); Collection pluginDependencies = plugin.getDependencies(); - for ( Dependency dependency : pluginDependencies ) - { - Artifact dependencyArtifact = repositorySystem.createDependencyArtifact( dependency ); - ArtifactResolutionResult artifactResolutionResult = resolvePluginArtifact( dependencyArtifact ); - for ( Artifact artifact : artifactResolutionResult.getArtifacts() ) - { + for (Dependency dependency : pluginDependencies) { + Artifact dependencyArtifact = repositorySystem.createDependencyArtifact(dependency); + ArtifactResolutionResult artifactResolutionResult = resolvePluginArtifact(dependencyArtifact); + for (Artifact artifact : artifactResolutionResult.getArtifacts()) { String key = artifact.getGroupId() + ":" + artifact.getArtifactId(); - Artifact resolvedPluginDependency = pluginResolvedDependencies.get( key ); - if ( resolvedPluginDependency != null ) - { - resolved.put( key, artifact ); + Artifact resolvedPluginDependency = pluginResolvedDependencies.get(key); + if (resolvedPluginDependency != null) { + resolved.put(key, artifact); } } } return resolved; } - ArtifactResolutionResult resolvePluginArtifact( Artifact artifact ) throws MojoExecutionException - { - return resolvePluginArtifact( artifact, new RuntimeArtifactFilter() ); + ArtifactResolutionResult resolvePluginArtifact(Artifact artifact) throws MojoExecutionException { + return resolvePluginArtifact(artifact, new RuntimeArtifactFilter()); } - ArtifactResolutionResult resolveProjectArtifact( Artifact artifact ) throws MojoExecutionException - { - return resolveProjectArtifact( artifact, new RuntimeArtifactFilter() ); + ArtifactResolutionResult resolveProjectArtifact(Artifact artifact) throws MojoExecutionException { + return resolveProjectArtifact(artifact, new RuntimeArtifactFilter()); } - private ArtifactResolutionResult resolvePluginArtifact( Artifact artifact, ArtifactFilter filter ) - throws MojoExecutionException - { - return resolveArtifact( artifact, pluginRemoteRepositories, filter ); + private ArtifactResolutionResult resolvePluginArtifact(Artifact artifact, ArtifactFilter filter) + throws MojoExecutionException { + return resolveArtifact(artifact, pluginRemoteRepositories, filter); } - private ArtifactResolutionResult resolveProjectArtifact( Artifact artifact, ArtifactFilter filter ) - throws MojoExecutionException - { - return resolveArtifact( artifact, projectRemoteRepositories, filter ); + private ArtifactResolutionResult resolveProjectArtifact(Artifact artifact, ArtifactFilter filter) + throws MojoExecutionException { + return resolveArtifact(artifact, projectRemoteRepositories, filter); } - private ArtifactResolutionResult resolveArtifact( Artifact artifact, List repositories, - ArtifactFilter filter ) throws MojoExecutionException - { + private ArtifactResolutionResult resolveArtifact( + Artifact artifact, List repositories, ArtifactFilter filter) + throws MojoExecutionException { ArtifactResolutionRequest request = new ArtifactResolutionRequest() - .setOffline( offline ) - .setArtifact( artifact ) - .setLocalRepository( localRepository ) - .setResolveTransitively( true ) - .setCollectionFilter( filter ) - .setRemoteRepositories( repositories ); - - ArtifactResolutionResult result = repositorySystem.resolve( request ); - try - { - resolutionErrorHandler.throwErrors( request, result ); - } - catch ( ArtifactResolutionException e ) - { - throw new MojoExecutionException( e.getMessage(), e ); + .setOffline(offline) + .setArtifact(artifact) + .setLocalRepository(localRepository) + .setResolveTransitively(true) + .setCollectionFilter(filter) + .setRemoteRepositories(repositories); + + ArtifactResolutionResult result = repositorySystem.resolve(request); + try { + resolutionErrorHandler.throwErrors(request, result); + } catch (ArtifactResolutionException e) { + throw new MojoExecutionException(e.getMessage(), e); } return result; } @Nonnull - Set getProviderClasspath( String providerArtifactId, String providerVersion ) - throws MojoExecutionException - { - Dependency provider = toProviderDependency( providerArtifactId, providerVersion ); + Set getProviderClasspath(String providerArtifactId, String providerVersion) + throws MojoExecutionException { + Dependency provider = toProviderDependency(providerArtifactId, providerVersion); - Artifact providerArtifact = repositorySystem.createDependencyArtifact( provider ); + Artifact providerArtifact = repositorySystem.createDependencyArtifact(provider); - ArtifactResolutionResult result = resolvePluginArtifact( providerArtifact ); + ArtifactResolutionResult result = resolvePluginArtifact(providerArtifact); - if ( log.isDebugEnabled() ) - { - for ( Artifact artifact : result.getArtifacts() ) - { + if (log.isDebugEnabled()) { + for (Artifact artifact : result.getArtifacts()) { String artifactPath = artifact.getFile().getAbsolutePath(); String scope = artifact.getScope(); - log.debug( "Adding to " + pluginName + " test classpath: " + artifactPath + " Scope: " + scope ); + log.debug("Adding to " + pluginName + " test classpath: " + artifactPath + " Scope: " + scope); } } - return orderProviderArtifacts( result.getArtifacts() ); + return orderProviderArtifacts(result.getArtifacts()); } @Nonnull - Map getProviderClasspathAsMap( String providerArtifactId, String providerVersion ) - throws MojoExecutionException - { - return artifactMapByVersionlessId( getProviderClasspath( providerArtifactId, providerVersion ) ); + Map getProviderClasspathAsMap(String providerArtifactId, String providerVersion) + throws MojoExecutionException { + return artifactMapByVersionlessId(getProviderClasspath(providerArtifactId, providerVersion)); } // FIXME // method argument should be unchanged // what if providerArtifacts will be unmodifiable - private static Set orderProviderArtifacts( Set providerArtifacts ) - { + private static Set orderProviderArtifacts(Set providerArtifacts) { Set orderedProviderArtifacts = new LinkedHashSet<>(); - for ( String order : PROVIDER_CLASSPATH_ORDER ) - { + for (String order : PROVIDER_CLASSPATH_ORDER) { Iterator providerArtifactsIt = providerArtifacts.iterator(); - while ( providerArtifactsIt.hasNext() ) - { + while (providerArtifactsIt.hasNext()) { Artifact providerArtifact = providerArtifactsIt.next(); - if ( providerArtifact.getArtifactId().equals( order ) ) - { - orderedProviderArtifacts.add( providerArtifact ); + if (providerArtifact.getArtifactId().equals(order)) { + orderedProviderArtifacts.add(providerArtifact); providerArtifactsIt.remove(); } } } - orderedProviderArtifacts.addAll( providerArtifacts ); + orderedProviderArtifacts.addAll(providerArtifacts); return orderedProviderArtifacts; } - private static Dependency toProviderDependency( String providerArtifactId, String providerVersion ) - { + private static Dependency toProviderDependency(String providerArtifactId, String providerVersion) { Dependency dependency = new Dependency(); - dependency.setGroupId( PROVIDER_GROUP_ID ); - dependency.setArtifactId( providerArtifactId ); - dependency.setVersion( providerVersion ); - dependency.setType( "jar" ); + dependency.setGroupId(PROVIDER_GROUP_ID); + dependency.setArtifactId(providerArtifactId); + dependency.setVersion(providerVersion); + dependency.setType("jar"); return dependency; } - static class RuntimeArtifactFilter implements ArtifactFilter - { + static class RuntimeArtifactFilter implements ArtifactFilter { private static final Collection SCOPES = - asList( SCOPE_COMPILE, SCOPE_COMPILE_PLUS_RUNTIME, SCOPE_RUNTIME ); + asList(SCOPE_COMPILE, SCOPE_COMPILE_PLUS_RUNTIME, SCOPE_RUNTIME); private final Artifact filter; - RuntimeArtifactFilter() - { - this( null ); + RuntimeArtifactFilter() { + this(null); } - RuntimeArtifactFilter( Artifact filter ) - { + RuntimeArtifactFilter(Artifact filter) { this.filter = filter; } @Override - public boolean include( Artifact artifact ) - { + public boolean include(Artifact artifact) { String scope = artifact.getScope(); - return ( filter == null || artifact.equals( filter ) ) - && !artifact.isOptional() && ( scope == null || SCOPES.contains( scope ) ); + return (filter == null || artifact.equals(filter)) + && !artifact.isOptional() + && (scope == null || SCOPES.contains(scope)); } } } diff --git a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/SurefireExecutionParameters.java b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/SurefireExecutionParameters.java index 2275b32f06..2d4b838959 100644 --- a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/SurefireExecutionParameters.java +++ b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/SurefireExecutionParameters.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.surefire; import java.io.File; import java.util.List; @@ -29,103 +28,102 @@ * * @author Stephen Connolly */ -public interface SurefireExecutionParameters -{ +public interface SurefireExecutionParameters { boolean isSkipTests(); - void setSkipTests( boolean skipTests ); + void setSkipTests(boolean skipTests); boolean isSkipExec(); - void setSkipExec( boolean skipExec ); + void setSkipExec(boolean skipExec); boolean isSkip(); - void setSkip( boolean skip ); + void setSkip(boolean skip); File getBasedir(); - void setBasedir( File basedir ); + void setBasedir(File basedir); File getTestClassesDirectory(); - void setTestClassesDirectory( File testClassesDirectory ); + void setTestClassesDirectory(File testClassesDirectory); File getMainBuildPath(); - void setMainBuildPath( File mainBuildPath ); + void setMainBuildPath(File mainBuildPath); File getReportsDirectory(); - void setReportsDirectory( File reportsDirectory ); + void setReportsDirectory(File reportsDirectory); File getTestSourceDirectory(); - void setTestSourceDirectory( File testSourceDirectory ); + void setTestSourceDirectory(File testSourceDirectory); String getTest(); - void setTest( String test ); + void setTest(String test); List getIncludes(); - void setIncludes( List includes ); + void setIncludes(List includes); List getExcludes(); - void setExcludes( List excludes ); + void setExcludes(List excludes); ArtifactRepository getLocalRepository(); - void setLocalRepository( ArtifactRepository localRepository ); + void setLocalRepository(ArtifactRepository localRepository); boolean isPrintSummary(); - void setPrintSummary( boolean printSummary ); + void setPrintSummary(boolean printSummary); String getReportFormat(); - void setReportFormat( String reportFormat ); + void setReportFormat(String reportFormat); boolean isUseFile(); - void setUseFile( boolean useFile ); + void setUseFile(boolean useFile); String getDebugForkedProcess(); - void setDebugForkedProcess( String debugForkedProcess ); + void setDebugForkedProcess(String debugForkedProcess); int getForkedProcessTimeoutInSeconds(); - void setForkedProcessTimeoutInSeconds( int forkedProcessTimeoutInSeconds ); + void setForkedProcessTimeoutInSeconds(int forkedProcessTimeoutInSeconds); int getForkedProcessExitTimeoutInSeconds(); - void setForkedProcessExitTimeoutInSeconds( int forkedProcessTerminationTimeoutInSeconds ); + void setForkedProcessExitTimeoutInSeconds(int forkedProcessTerminationTimeoutInSeconds); double getParallelTestsTimeoutInSeconds(); - void setParallelTestsTimeoutInSeconds( double parallelTestsTimeoutInSeconds ); + void setParallelTestsTimeoutInSeconds(double parallelTestsTimeoutInSeconds); double getParallelTestsTimeoutForcedInSeconds(); - void setParallelTestsTimeoutForcedInSeconds( double parallelTestsTimeoutForcedInSeconds ); + void setParallelTestsTimeoutForcedInSeconds(double parallelTestsTimeoutForcedInSeconds); boolean isUseSystemClassLoader(); - void setUseSystemClassLoader( boolean useSystemClassLoader ); + void setUseSystemClassLoader(boolean useSystemClassLoader); boolean isUseManifestOnlyJar(); - void setUseManifestOnlyJar( boolean useManifestOnlyJar ); + void setUseManifestOnlyJar(boolean useManifestOnlyJar); String getEncoding(); - void setEncoding( String encoding ); + void setEncoding(String encoding); boolean getFailIfNoSpecifiedTests(); - void setFailIfNoSpecifiedTests( boolean failIfNoSpecifiedTests ); + void setFailIfNoSpecifiedTests(boolean failIfNoSpecifiedTests); int getSkipAfterFailureCount(); @@ -133,9 +131,9 @@ public interface SurefireExecutionParameters String[] getIncludeJUnit5Engines(); - void setIncludeJUnit5Engines( String[] includeJUnit5Engines ); + void setIncludeJUnit5Engines(String[] includeJUnit5Engines); String[] getExcludeJUnit5Engines(); - void setExcludeJUnit5Engines( String[] excludeJUnit5Engines ); + void setExcludeJUnit5Engines(String[] excludeJUnit5Engines); } diff --git a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/SurefireHelper.java b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/SurefireHelper.java index 5822451046..03158be67a 100644 --- a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/SurefireHelper.java +++ b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/SurefireHelper.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,16 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.surefire; + +import javax.annotation.Nonnull; + +import java.io.File; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Deque; +import java.util.LinkedList; +import java.util.List; import org.apache.maven.execution.MavenExecutionRequest; import org.apache.maven.execution.MavenSession; @@ -29,17 +37,7 @@ import org.apache.maven.surefire.api.testset.TestSetFailedException; import org.apache.maven.surefire.booter.SurefireBooterForkException; -import javax.annotation.Nonnull; -import java.io.File; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Deque; -import java.util.LinkedList; -import java.util.List; - import static java.util.Collections.unmodifiableList; -import static org.apache.maven.surefire.api.util.internal.DumpFileUtils.newFormattedDateFileName; -import static org.apache.maven.surefire.shared.lang3.SystemUtils.IS_OS_WINDOWS; import static org.apache.maven.surefire.api.booter.DumpErrorSingleton.DUMPSTREAM_FILE_EXT; import static org.apache.maven.surefire.api.booter.DumpErrorSingleton.DUMP_FILE_EXT; import static org.apache.maven.surefire.api.cli.CommandLineOption.LOGGING_LEVEL_DEBUG; @@ -47,12 +45,13 @@ import static org.apache.maven.surefire.api.cli.CommandLineOption.LOGGING_LEVEL_INFO; import static org.apache.maven.surefire.api.cli.CommandLineOption.LOGGING_LEVEL_WARN; import static org.apache.maven.surefire.api.cli.CommandLineOption.SHOW_ERRORS; +import static org.apache.maven.surefire.api.util.internal.DumpFileUtils.newFormattedDateFileName; +import static org.apache.maven.surefire.shared.lang3.SystemUtils.IS_OS_WINDOWS; /** * Helper class for surefire plugins */ -public final class SurefireHelper -{ +public final class SurefireHelper { private static final String DUMP_FILE_DATE = newFormattedDateFileName(); public static final String DUMP_FILE_PREFIX = DUMP_FILE_DATE + "-jvmRun"; @@ -80,13 +79,12 @@ public final class SurefireHelper */ private static final int MAX_PATH_LENGTH_WINDOWS = 247; - private static final String[] DUMP_FILES_PRINT = - { - "[date]" + DUMP_FILE_EXT, - "[date]-jvmRun[N]" + DUMP_FILE_EXT, - "[date]" + DUMPSTREAM_FILE_EXT, - "[date]-jvmRun[N]" + DUMPSTREAM_FILE_EXT - }; + private static final String[] DUMP_FILES_PRINT = { + "[date]" + DUMP_FILE_EXT, + "[date]-jvmRun[N]" + DUMP_FILE_EXT, + "[date]" + DUMPSTREAM_FILE_EXT, + "[date]-jvmRun[N]" + DUMPSTREAM_FILE_EXT + }; /** * The placeholder that is replaced by the executing thread's running number. The thread number @@ -104,135 +102,108 @@ public final class SurefireHelper /** * Do not instantiate. */ - private SurefireHelper() - { - throw new IllegalAccessError( "Utility class" ); + private SurefireHelper() { + throw new IllegalAccessError("Utility class"); } @Nonnull - public static String replaceThreadNumberPlaceholders( @Nonnull String argLine, int threadNumber ) - { - String threadNumberAsString = String.valueOf( threadNumber ); - return argLine.replace( THREAD_NUMBER_PLACEHOLDER, threadNumberAsString ) - .replace( FORK_NUMBER_PLACEHOLDER, threadNumberAsString ); + public static String replaceThreadNumberPlaceholders(@Nonnull String argLine, int threadNumber) { + String threadNumberAsString = String.valueOf(threadNumber); + return argLine.replace(THREAD_NUMBER_PLACEHOLDER, threadNumberAsString) + .replace(FORK_NUMBER_PLACEHOLDER, threadNumberAsString); } - public static File replaceForkThreadsInPath( File path, int replacement ) - { + public static File replaceForkThreadsInPath(File path, int replacement) { Deque dirs = new LinkedList<>(); File root = path; - while ( !root.exists() ) - { - dirs.addFirst( replaceThreadNumberPlaceholders( root.getName(), replacement ) ); + while (!root.exists()) { + dirs.addFirst(replaceThreadNumberPlaceholders(root.getName(), replacement)); root = root.getParentFile(); } File replacedPath = root; - for ( String dir : dirs ) - { - replacedPath = new File( replacedPath, dir ); + for (String dir : dirs) { + replacedPath = new File(replacedPath, dir); } return replacedPath; } - public static String[] getDumpFilesToPrint() - { + public static String[] getDumpFilesToPrint() { return DUMP_FILES_PRINT.clone(); } - public static void reportExecution( SurefireReportParameters reportParameters, RunResult result, - PluginConsoleLogger log, Exception firstForkException ) - throws MojoFailureException, MojoExecutionException - { + public static void reportExecution( + SurefireReportParameters reportParameters, + RunResult result, + PluginConsoleLogger log, + Exception firstForkException) + throws MojoFailureException, MojoExecutionException { boolean isError = firstForkException != null || result.isTimeout() || !result.isErrorFree(); - boolean isTooFlaky = isTooFlaky( result, reportParameters ); - if ( !isError && !isTooFlaky ) - { - if ( result.getCompletedCount() == 0 && failIfNoTests( reportParameters ) ) - { - throw new MojoFailureException( "No tests were executed! " - + "(Set -DfailIfNoTests=false to ignore this error.)" ); + boolean isTooFlaky = isTooFlaky(result, reportParameters); + if (!isError && !isTooFlaky) { + if (result.getCompletedCount() == 0 && failIfNoTests(reportParameters)) { + throw new MojoFailureException( + "No tests were executed! " + "(Set -DfailIfNoTests=false to ignore this error.)"); } return; } - if ( reportParameters.isTestFailureIgnore() ) - { - String errorMessage = createErrorMessage( reportParameters, result, firstForkException ); + if (reportParameters.isTestFailureIgnore()) { + String errorMessage = createErrorMessage(reportParameters, result, firstForkException); - if ( firstForkException instanceof SurefireBooterForkException ) - { - throw new MojoExecutionException( errorMessage, firstForkException ); + if (firstForkException instanceof SurefireBooterForkException) { + throw new MojoExecutionException(errorMessage, firstForkException); } - log.error( errorMessage ); - } - else - { - throwException( reportParameters, result, firstForkException ); + log.error(errorMessage); + } else { + throwException(reportParameters, result, firstForkException); } } - public static List commandLineOptions( MavenSession session, PluginConsoleLogger log ) - { + public static List commandLineOptions(MavenSession session, PluginConsoleLogger log) { List cli = new ArrayList<>(); - if ( log.isErrorEnabled() ) - { - cli.add( LOGGING_LEVEL_ERROR ); + if (log.isErrorEnabled()) { + cli.add(LOGGING_LEVEL_ERROR); } - if ( log.isWarnEnabled() ) - { - cli.add( LOGGING_LEVEL_WARN ); + if (log.isWarnEnabled()) { + cli.add(LOGGING_LEVEL_WARN); } - if ( log.isInfoEnabled() ) - { - cli.add( LOGGING_LEVEL_INFO ); + if (log.isInfoEnabled()) { + cli.add(LOGGING_LEVEL_INFO); } - if ( log.isDebugEnabled() ) - { - cli.add( LOGGING_LEVEL_DEBUG ); + if (log.isDebugEnabled()) { + cli.add(LOGGING_LEVEL_DEBUG); } MavenExecutionRequest request = session.getRequest(); - if ( request.isShowErrors() ) - { - cli.add( SHOW_ERRORS ); + if (request.isShowErrors()) { + cli.add(SHOW_ERRORS); } String failureBehavior = request.getReactorFailureBehavior(); - if ( failureBehavior != null ) - { - try - { - cli.add( CommandLineOption.valueOf( failureBehavior ) ); - } - catch ( IllegalArgumentException e ) - { + if (failureBehavior != null) { + try { + cli.add(CommandLineOption.valueOf(failureBehavior)); + } catch (IllegalArgumentException e) { // CommandLineOption does not have specified enum as string. See getRequest() method in Maven Session. } } - return unmodifiableList( cli ); + return unmodifiableList(cli); } - public static void logDebugOrCliShowErrors( String s, PluginConsoleLogger log, Collection cli ) - { - if ( cli.contains( LOGGING_LEVEL_DEBUG ) ) - { - log.debug( s ); - } - else if ( cli.contains( SHOW_ERRORS ) ) - { - if ( log.isDebugEnabled() ) - { - log.debug( s ); - } - else - { - log.info( s ); + public static void logDebugOrCliShowErrors(String s, PluginConsoleLogger log, Collection cli) { + if (cli.contains(LOGGING_LEVEL_DEBUG)) { + log.debug(s); + } else if (cli.contains(SHOW_ERRORS)) { + if (log.isDebugEnabled()) { + log.debug(s); + } else { + log.info(s); } } } @@ -250,102 +221,81 @@ else if ( cli.contains( SHOW_ERRORS ) ) * @param path source path * @return escaped to platform path */ - public static String escapeToPlatformPath( String path ) - { - if ( IS_OS_WINDOWS && path.length() > MAX_PATH_LENGTH_WINDOWS ) - { - path = path.startsWith( "\\\\" ) ? "\\\\?\\UNC\\" + path.substring( 2 ) : "\\\\?\\" + path; + public static String escapeToPlatformPath(String path) { + if (IS_OS_WINDOWS && path.length() > MAX_PATH_LENGTH_WINDOWS) { + path = path.startsWith("\\\\") ? "\\\\?\\UNC\\" + path.substring(2) : "\\\\?\\" + path; } return path; } - private static boolean failIfNoTests( SurefireReportParameters reportParameters ) - { + private static boolean failIfNoTests(SurefireReportParameters reportParameters) { return reportParameters.getFailIfNoTests(); } - private static boolean isFatal( Exception firstForkException ) - { - return firstForkException != null && !( firstForkException instanceof TestSetFailedException ); + private static boolean isFatal(Exception firstForkException) { + return firstForkException != null && !(firstForkException instanceof TestSetFailedException); } - private static void throwException( SurefireReportParameters reportParameters, RunResult result, - Exception firstForkException ) - throws MojoFailureException, MojoExecutionException - { - if ( isFatal( firstForkException ) || result.isInternalError() ) - { - throw new MojoExecutionException( createErrorMessage( reportParameters, result, firstForkException ), - firstForkException ); - } - else - { - throw new MojoFailureException( createErrorMessage( reportParameters, result, firstForkException ), - firstForkException ); + private static void throwException( + SurefireReportParameters reportParameters, RunResult result, Exception firstForkException) + throws MojoFailureException, MojoExecutionException { + if (isFatal(firstForkException) || result.isInternalError()) { + throw new MojoExecutionException( + createErrorMessage(reportParameters, result, firstForkException), firstForkException); + } else { + throw new MojoFailureException( + createErrorMessage(reportParameters, result, firstForkException), firstForkException); } } - private static String createErrorMessage( SurefireReportParameters reportParameters, RunResult result, - Exception firstForkException ) - { - StringBuilder msg = new StringBuilder( 512 ); + private static String createErrorMessage( + SurefireReportParameters reportParameters, RunResult result, Exception firstForkException) { + StringBuilder msg = new StringBuilder(512); - if ( result.isTimeout() ) - { - msg.append( "There was a timeout in the fork" ); - } - else - { - if ( result.getFailures() > 0 ) - { - msg.append( "There are test failures." ); + if (result.isTimeout()) { + msg.append("There was a timeout in the fork"); + } else { + if (result.getFailures() > 0) { + msg.append("There are test failures."); } - if ( isTooFlaky( result, reportParameters ) ) - { - if ( result.getFailures() > 0 ) - { - msg.append( "\n" ); + if (isTooFlaky(result, reportParameters)) { + if (result.getFailures() > 0) { + msg.append("\n"); } - msg.append( "There" ) - .append( result.getFlakes() == 1 ? " is " : " are " ) - .append( result.getFlakes() ) - .append( result.getFlakes() == 1 ? " flake " : " flakes " ) - .append( "and failOnFlakeCount is set to " ) - .append( reportParameters.getFailOnFlakeCount() ) - .append( "." ); + msg.append("There") + .append(result.getFlakes() == 1 ? " is " : " are ") + .append(result.getFlakes()) + .append(result.getFlakes() == 1 ? " flake " : " flakes ") + .append("and failOnFlakeCount is set to ") + .append(reportParameters.getFailOnFlakeCount()) + .append("."); } - msg.append( "\n\nPlease refer to " ) - .append( reportParameters.getReportsDirectory() ) - .append( " for the individual test results." ) - .append( '\n' ) - .append( "Please refer to dump files (if any exist) " ) - .append( DUMP_FILES_PRINT[0] ) - .append( ", " ) - .append( DUMP_FILES_PRINT[1] ) - .append( " and " ) - .append( DUMP_FILES_PRINT[2] ) - .append( "." ); + msg.append("\n\nPlease refer to ") + .append(reportParameters.getReportsDirectory()) + .append(" for the individual test results.") + .append('\n') + .append("Please refer to dump files (if any exist) ") + .append(DUMP_FILES_PRINT[0]) + .append(", ") + .append(DUMP_FILES_PRINT[1]) + .append(" and ") + .append(DUMP_FILES_PRINT[2]) + .append("."); } - if ( firstForkException != null && firstForkException.getLocalizedMessage() != null ) - { - msg.append( '\n' ) - .append( firstForkException.getLocalizedMessage() ); + if (firstForkException != null && firstForkException.getLocalizedMessage() != null) { + msg.append('\n').append(firstForkException.getLocalizedMessage()); } - if ( result.isFailure() ) - { - msg.append( '\n' ) - .append( result.getFailure() ); + if (result.isFailure()) { + msg.append('\n').append(result.getFailure()); } return msg.toString(); } - private static boolean isTooFlaky( RunResult result, SurefireReportParameters reportParameters ) - { + private static boolean isTooFlaky(RunResult result, SurefireReportParameters reportParameters) { int failOnFlakeCount = reportParameters.getFailOnFlakeCount(); return failOnFlakeCount > 0 && result.getFlakes() >= failOnFlakeCount; } - } diff --git a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/SurefireProperties.java b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/SurefireProperties.java index 2f5e919457..96e3cdaefb 100644 --- a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/SurefireProperties.java +++ b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/SurefireProperties.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.surefire; import java.io.File; import java.io.FileInputStream; @@ -43,230 +42,183 @@ /** * A properties implementation that preserves insertion order. */ -public class SurefireProperties - extends Properties - implements KeyValueSource -{ +public class SurefireProperties extends Properties implements KeyValueSource { private static final Collection KEYS_THAT_CANNOT_BE_USED_AS_SYSTEM_PROPERTIES = - asList( "java.library.path", "file.encoding", "jdk.map.althashing.threshold", "line.separator" ); + asList("java.library.path", "file.encoding", "jdk.map.althashing.threshold", "line.separator"); private final LinkedHashSet items = new LinkedHashSet<>(); - public SurefireProperties() - { - } + public SurefireProperties() {} - public SurefireProperties( Properties source ) - { - if ( source != null ) - { - putAll( source ); + public SurefireProperties(Properties source) { + if (source != null) { + putAll(source); } } - public SurefireProperties( KeyValueSource source ) - { - if ( source != null ) - { - source.copyTo( this ); + public SurefireProperties(KeyValueSource source) { + if (source != null) { + source.copyTo(this); } } @Override - public synchronized void putAll( Map t ) - { - for ( Entry entry : t.entrySet() ) - { - put( entry.getKey(), entry.getValue() ); + public synchronized void putAll(Map t) { + for (Entry entry : t.entrySet()) { + put(entry.getKey(), entry.getValue()); } } @Override - public synchronized Object put( Object key, Object value ) - { - items.add( key ); - return super.put( key, value ); + public synchronized Object put(Object key, Object value) { + items.add(key); + return super.put(key, value); } @Override - public synchronized Object remove( Object key ) - { - items.remove( key ); - return super.remove( key ); + public synchronized Object remove(Object key) { + items.remove(key); + return super.remove(key); } @Override - public synchronized void clear() - { + public synchronized void clear() { items.clear(); super.clear(); } @Override - public synchronized Enumeration keys() - { - return Collections.enumeration( items ); + public synchronized Enumeration keys() { + return Collections.enumeration(items); } - public void copyPropertiesFrom( Properties source ) - { - if ( source != null ) - { - putAll( source ); + public void copyPropertiesFrom(Properties source) { + if (source != null) { + putAll(source); } } - public Iterable getStringKeySet() - { + public Iterable getStringKeySet() { return keySet(); } - public Set propertiesThatCannotBeSetASystemProperties() - { + public Set propertiesThatCannotBeSetASystemProperties() { Set result = new HashSet<>(); - for ( Object key : getStringKeySet() ) - { + for (Object key : getStringKeySet()) { //noinspection SuspiciousMethodCalls - if ( KEYS_THAT_CANNOT_BE_USED_AS_SYSTEM_PROPERTIES.contains( key ) ) - { - result.add( key ); + if (KEYS_THAT_CANNOT_BE_USED_AS_SYSTEM_PROPERTIES.contains(key)) { + result.add(key); } } return result; } - public void copyToSystemProperties() - { - for ( Object o : items ) - { + public void copyToSystemProperties() { + for (Object o : items) { String key = (String) o; - String value = getProperty( key ); - System.setProperty( key, value ); + String value = getProperty(key); + System.setProperty(key, value); } } - static SurefireProperties calculateEffectiveProperties( Properties systemProperties, - Map systemPropertyVariables, - Properties userProperties, SurefireProperties props ) - { + static SurefireProperties calculateEffectiveProperties( + Properties systemProperties, + Map systemPropertyVariables, + Properties userProperties, + SurefireProperties props) { SurefireProperties result = new SurefireProperties(); - result.copyPropertiesFrom( systemProperties ); + result.copyPropertiesFrom(systemProperties); - result.copyPropertiesFrom( props ); + result.copyPropertiesFrom(props); - copyProperties( result, systemPropertyVariables ); + copyProperties(result, systemPropertyVariables); // We used to take all of our system properties and dump them in with the // user specified properties for SUREFIRE-121, causing SUREFIRE-491. // Not gonna do THAT any more... instead, we only propagate those system properties // that have been explicitly specified by the user via -Dkey=value on the CLI - result.copyPropertiesFrom( userProperties ); + result.copyPropertiesFrom(userProperties); return result; } - private static void copyProperties( Properties target, Map source ) - { - if ( source != null ) - { - for ( String key : source.keySet() ) - { - String value = source.get( key ); - target.setProperty( key, value == null ? "" : value ); + private static void copyProperties(Properties target, Map source) { + if (source != null) { + for (String key : source.keySet()) { + String value = source.get(key); + target.setProperty(key, value == null ? "" : value); } } } @Override - public void copyTo( Map target ) - { - target.putAll( this ); + public void copyTo(Map target) { + target.putAll(this); } - public void setProperty( String key, File file ) - { - if ( file != null ) - { - setProperty( key, file.toString() ); + public void setProperty(String key, File file) { + if (file != null) { + setProperty(key, file.toString()); } } - public void setProperty( String key, Boolean aBoolean ) - { - if ( aBoolean != null ) - { - setProperty( key, aBoolean.toString() ); + public void setProperty(String key, Boolean aBoolean) { + if (aBoolean != null) { + setProperty(key, aBoolean.toString()); } } - public void setProperty( String key, int value ) - { - setProperty( key, String.valueOf( value ) ); + public void setProperty(String key, int value) { + setProperty(key, String.valueOf(value)); } - public void setProperty( String key, Long value ) - { - if ( value != null ) - { - setProperty( key, value.toString() ); + public void setProperty(String key, Long value) { + if (value != null) { + setProperty(key, value.toString()); } } - public void addList( List items, String propertyPrefix ) - { - if ( items != null && !items.isEmpty() ) - { + public void addList(List items, String propertyPrefix) { + if (items != null && !items.isEmpty()) { int i = 0; - for ( Object item : items ) - { - if ( item == null ) - { - throw new NullPointerException( propertyPrefix + i + " has null value" ); + for (Object item : items) { + if (item == null) { + throw new NullPointerException(propertyPrefix + i + " has null value"); } - String[] stringArray = StringUtils.split( item.toString(), "," ); + String[] stringArray = StringUtils.split(item.toString(), ","); - for ( String aStringArray : stringArray ) - { - setProperty( propertyPrefix + i, aStringArray ); + for (String aStringArray : stringArray) { + setProperty(propertyPrefix + i, aStringArray); i++; } } } } - public void setClasspath( String prefix, Classpath classpath ) - { + public void setClasspath(String prefix, Classpath classpath) { List classpathElements = classpath.getClassPath(); - for ( int i = 0; i < classpathElements.size(); ++i ) - { - String element = classpathElements.get( i ); - setProperty( prefix + i, element ); + for (int i = 0; i < classpathElements.size(); ++i) { + String element = classpathElements.get(i); + setProperty(prefix + i, element); } } - private static SurefireProperties loadProperties( InputStream inStream ) - throws IOException - { - try ( final InputStream surefirePropertiesStream = inStream ) - { + private static SurefireProperties loadProperties(InputStream inStream) throws IOException { + try (InputStream surefirePropertiesStream = inStream) { Properties p = new Properties(); - p.load( surefirePropertiesStream ); - return new SurefireProperties( p ); + p.load(surefirePropertiesStream); + return new SurefireProperties(p); } } - public static SurefireProperties loadProperties( File file ) - throws IOException - { - return file == null ? new SurefireProperties() : loadProperties( new FileInputStream( file ) ); + public static SurefireProperties loadProperties(File file) throws IOException { + return file == null ? new SurefireProperties() : loadProperties(new FileInputStream(file)); } - public void setNullableProperty( String key, String value ) - { - if ( value != null ) - { - super.setProperty( key, value ); + public void setNullableProperty(String key, String value) { + if (value != null) { + super.setProperty(key, value); } } } diff --git a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/SurefireReportParameters.java b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/SurefireReportParameters.java index da808ed4c3..2c27f7257d 100644 --- a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/SurefireReportParameters.java +++ b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/SurefireReportParameters.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.surefire; import java.io.File; @@ -26,41 +25,40 @@ * * @author Stephen Connolly */ -public interface SurefireReportParameters -{ +public interface SurefireReportParameters { boolean isSkipTests(); - void setSkipTests( boolean skipTests ); + void setSkipTests(boolean skipTests); boolean isSkipExec(); - void setSkipExec( boolean skipExec ); + void setSkipExec(boolean skipExec); boolean isSkip(); - void setSkip( boolean skip ); + void setSkip(boolean skip); boolean isTestFailureIgnore(); - void setTestFailureIgnore( boolean testFailureIgnore ); + void setTestFailureIgnore(boolean testFailureIgnore); File getBasedir(); - void setBasedir( File basedir ); + void setBasedir(File basedir); File getTestClassesDirectory(); - void setTestClassesDirectory( File testClassesDirectory ); + void setTestClassesDirectory(File testClassesDirectory); File getReportsDirectory(); - void setReportsDirectory( File reportsDirectory ); + void setReportsDirectory(File reportsDirectory); boolean getFailIfNoTests(); - void setFailIfNoTests( boolean failIfNoTests ); + void setFailIfNoTests(boolean failIfNoTests); int getFailOnFlakeCount(); - void setFailOnFlakeCount( int failOnFlakeCount ); + void setFailOnFlakeCount(int failOnFlakeCount); } diff --git a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/TestClassPath.java b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/TestClassPath.java index ba73361774..f3379564f8 100644 --- a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/TestClassPath.java +++ b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/TestClassPath.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,9 +16,7 @@ * specific language governing permissions and limitations * under the License. */ - -import org.apache.maven.artifact.Artifact; -import org.apache.maven.surefire.booter.Classpath; +package org.apache.maven.plugin.surefire; import java.io.File; import java.util.ArrayList; @@ -28,64 +24,57 @@ import java.util.List; import java.util.Map; +import org.apache.maven.artifact.Artifact; +import org.apache.maven.surefire.booter.Classpath; + import static java.util.Collections.addAll; import static org.apache.maven.surefire.shared.utils.StringUtils.split; -final class TestClassPath -{ +final class TestClassPath { private final Iterable artifacts; private final File classesDirectory; private final File testClassesDirectory; private final String[] additionalClasspathElements; - TestClassPath( Iterable artifacts, - File classesDirectory, - File testClassesDirectory, - String[] additionalClasspathElements ) - { + TestClassPath( + Iterable artifacts, + File classesDirectory, + File testClassesDirectory, + String[] additionalClasspathElements) { this.artifacts = artifacts; this.classesDirectory = classesDirectory; this.testClassesDirectory = testClassesDirectory; this.additionalClasspathElements = additionalClasspathElements; } - Map getTestDependencies() - { + Map getTestDependencies() { Map artifactMapping = new LinkedHashMap<>(); - for ( Artifact artifact : artifacts ) - { - artifactMapping.put( artifact.getGroupId() + ":" + artifact.getArtifactId(), artifact ); + for (Artifact artifact : artifacts) { + artifactMapping.put(artifact.getGroupId() + ":" + artifact.getArtifactId(), artifact); } return artifactMapping; } - Classpath toClasspath() - { + Classpath toClasspath() { List classpath = new ArrayList<>(); - classpath.add( testClassesDirectory.getAbsolutePath() ); - classpath.add( classesDirectory.getAbsolutePath() ); - for ( Artifact artifact : artifacts ) - { - if ( artifact.getArtifactHandler().isAddedToClasspath() ) - { + classpath.add(testClassesDirectory.getAbsolutePath()); + classpath.add(classesDirectory.getAbsolutePath()); + for (Artifact artifact : artifacts) { + if (artifact.getArtifactHandler().isAddedToClasspath()) { File file = artifact.getFile(); - if ( file != null ) - { - classpath.add( file.getAbsolutePath() ); + if (file != null) { + classpath.add(file.getAbsolutePath()); } } } - if ( additionalClasspathElements != null ) - { - for ( String additionalClasspathElement : additionalClasspathElements ) - { - if ( additionalClasspathElement != null ) - { - addAll( classpath, split( additionalClasspathElement, "," ) ); + if (additionalClasspathElements != null) { + for (String additionalClasspathElement : additionalClasspathElements) { + if (additionalClasspathElement != null) { + addAll(classpath, split(additionalClasspathElement, ",")); } } } - return new Classpath( classpath ); + return new Classpath(classpath); } } diff --git a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/AbstractClasspathForkConfiguration.java b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/AbstractClasspathForkConfiguration.java index f8e08eab8d..22685201f0 100644 --- a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/AbstractClasspathForkConfiguration.java +++ b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/AbstractClasspathForkConfiguration.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire.booterclient; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,50 +16,61 @@ * specific language governing permissions and limitations * under the License. */ - -import org.apache.maven.plugin.surefire.log.api.ConsoleLogger; -import org.apache.maven.surefire.booter.Classpath; -import org.apache.maven.surefire.extensions.ForkNodeFactory; +package org.apache.maven.plugin.surefire.booterclient; import javax.annotation.Nonnull; import javax.annotation.Nullable; + import java.io.File; import java.util.Map; import java.util.Properties; +import org.apache.maven.plugin.surefire.log.api.ConsoleLogger; +import org.apache.maven.surefire.booter.Classpath; +import org.apache.maven.surefire.extensions.ForkNodeFactory; + /** * @author Tibor Digana (tibor17) * @since 2.21.0.Jigsaw */ -abstract class AbstractClasspathForkConfiguration - extends DefaultForkConfiguration -{ +abstract class AbstractClasspathForkConfiguration extends DefaultForkConfiguration { - @SuppressWarnings( "checkstyle:parameternumber" ) - AbstractClasspathForkConfiguration( @Nonnull Classpath bootClasspath, - @Nonnull File tempDirectory, - @Nullable String debugLine, - @Nonnull File workingDirectory, - @Nonnull Properties modelProperties, - @Nullable String argLine, - @Nonnull Map environmentVariables, - @Nonnull String[] excludedEnvironmentVariables, - boolean debug, - int forkCount, - boolean reuseForks, - @Nonnull Platform pluginPlatform, - @Nonnull ConsoleLogger log, - @Nonnull ForkNodeFactory forkNodeFactory ) - { - super( bootClasspath, tempDirectory, debugLine, workingDirectory, modelProperties, argLine, - environmentVariables, excludedEnvironmentVariables, debug, forkCount, reuseForks, pluginPlatform, log, - forkNodeFactory ); + @SuppressWarnings("checkstyle:parameternumber") + AbstractClasspathForkConfiguration( + @Nonnull Classpath bootClasspath, + @Nonnull File tempDirectory, + @Nullable String debugLine, + @Nonnull File workingDirectory, + @Nonnull Properties modelProperties, + @Nullable String argLine, + @Nonnull Map environmentVariables, + @Nonnull String[] excludedEnvironmentVariables, + boolean debug, + int forkCount, + boolean reuseForks, + @Nonnull Platform pluginPlatform, + @Nonnull ConsoleLogger log, + @Nonnull ForkNodeFactory forkNodeFactory) { + super( + bootClasspath, + tempDirectory, + debugLine, + workingDirectory, + modelProperties, + argLine, + environmentVariables, + excludedEnvironmentVariables, + debug, + forkCount, + reuseForks, + pluginPlatform, + log, + forkNodeFactory); } @Override @Nonnull - protected String extendJvmArgLine( @Nonnull String jvmArgLine ) - { + protected String extendJvmArgLine(@Nonnull String jvmArgLine) { return jvmArgLine; } } diff --git a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/BooterSerializer.java b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/BooterSerializer.java index 1385bd44d6..2dbc27b300 100644 --- a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/BooterSerializer.java +++ b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/BooterSerializer.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire.booterclient; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,14 +16,14 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.surefire.booterclient; + +import java.io.File; +import java.io.IOException; +import java.util.Collections; +import java.util.List; import org.apache.maven.plugin.surefire.SurefireProperties; -import org.apache.maven.surefire.booter.AbstractPathConfiguration; -import org.apache.maven.surefire.booter.ClassLoaderConfiguration; -import org.apache.maven.surefire.booter.KeyValueSource; -import org.apache.maven.surefire.booter.ProcessCheckerType; -import org.apache.maven.surefire.booter.ProviderConfiguration; -import org.apache.maven.surefire.booter.StartupConfiguration; import org.apache.maven.surefire.api.cli.CommandLineOption; import org.apache.maven.surefire.api.report.ReporterConfiguration; import org.apache.maven.surefire.api.testset.DirectoryScannerParameters; @@ -34,11 +32,12 @@ import org.apache.maven.surefire.api.testset.TestListResolver; import org.apache.maven.surefire.api.testset.TestRequest; import org.apache.maven.surefire.api.util.RunOrder; - -import java.io.File; -import java.io.IOException; -import java.util.Collections; -import java.util.List; +import org.apache.maven.surefire.booter.AbstractPathConfiguration; +import org.apache.maven.surefire.booter.ClassLoaderConfiguration; +import org.apache.maven.surefire.booter.KeyValueSource; +import org.apache.maven.surefire.booter.ProcessCheckerType; +import org.apache.maven.surefire.booter.ProviderConfiguration; +import org.apache.maven.surefire.booter.StartupConfiguration; import static org.apache.maven.plugin.surefire.SurefireHelper.replaceForkThreadsInPath; import static org.apache.maven.surefire.booter.AbstractPathConfiguration.CHILD_DELEGATION; @@ -49,6 +48,7 @@ import static org.apache.maven.surefire.booter.BooterConstants.FAIL_FAST_COUNT; import static org.apache.maven.surefire.booter.BooterConstants.FORKTESTSET; import static org.apache.maven.surefire.booter.BooterConstants.FORKTESTSET_PREFER_TESTS_FROM_IN_STREAM; +import static org.apache.maven.surefire.booter.BooterConstants.FORK_NODE_CONNECTION_STRING; import static org.apache.maven.surefire.booter.BooterConstants.FORK_NUMBER; import static org.apache.maven.surefire.booter.BooterConstants.INCLUDES_PROPERTY_PREFIX; import static org.apache.maven.surefire.booter.BooterConstants.ISTRIMSTACKTRACE; @@ -56,23 +56,22 @@ import static org.apache.maven.surefire.booter.BooterConstants.PLUGIN_PID; import static org.apache.maven.surefire.booter.BooterConstants.PROCESS_CHECKER; import static org.apache.maven.surefire.booter.BooterConstants.PROVIDER_CONFIGURATION; -import static org.apache.maven.surefire.booter.BooterConstants.RUN_ORDER_RANDOM_SEED; import static org.apache.maven.surefire.booter.BooterConstants.REPORTSDIRECTORY; import static org.apache.maven.surefire.booter.BooterConstants.REQUESTEDTEST; import static org.apache.maven.surefire.booter.BooterConstants.RERUN_FAILING_TESTS_COUNT; import static org.apache.maven.surefire.booter.BooterConstants.RUN_ORDER; +import static org.apache.maven.surefire.booter.BooterConstants.RUN_ORDER_RANDOM_SEED; import static org.apache.maven.surefire.booter.BooterConstants.RUN_STATISTICS_FILE; import static org.apache.maven.surefire.booter.BooterConstants.SHUTDOWN; import static org.apache.maven.surefire.booter.BooterConstants.SOURCE_DIRECTORY; import static org.apache.maven.surefire.booter.BooterConstants.SPECIFIC_TEST_PROPERTY_PREFIX; import static org.apache.maven.surefire.booter.BooterConstants.SYSTEM_EXIT_TIMEOUT; -import static org.apache.maven.surefire.booter.BooterConstants.TEST_CLASSES_DIRECTORY; -import static org.apache.maven.surefire.booter.BooterConstants.TEST_SUITE_XML_FILES; import static org.apache.maven.surefire.booter.BooterConstants.TESTARTIFACT_CLASSIFIER; import static org.apache.maven.surefire.booter.BooterConstants.TESTARTIFACT_VERSION; +import static org.apache.maven.surefire.booter.BooterConstants.TEST_CLASSES_DIRECTORY; +import static org.apache.maven.surefire.booter.BooterConstants.TEST_SUITE_XML_FILES; import static org.apache.maven.surefire.booter.BooterConstants.USEMANIFESTONLYJAR; import static org.apache.maven.surefire.booter.BooterConstants.USESYSTEMCLASSLOADER; -import static org.apache.maven.surefire.booter.BooterConstants.FORK_NODE_CONNECTION_STRING; import static org.apache.maven.surefire.booter.SystemPropertyManager.writePropertiesFile; /** @@ -90,116 +89,108 @@ * @author Dan Fabulich * @author Kristian Rosenvold */ -class BooterSerializer -{ +class BooterSerializer { private final ForkConfiguration forkConfiguration; - BooterSerializer( ForkConfiguration forkConfiguration ) - { + BooterSerializer(ForkConfiguration forkConfiguration) { this.forkConfiguration = forkConfiguration; } /** * Does not modify sourceProperties */ - File serialize( KeyValueSource sourceProperties, ProviderConfiguration providerConfiguration, - StartupConfiguration startupConfiguration, Object testSet, boolean readTestsFromInStream, - Long pid, int forkNumber, String forkNodeConnectionString ) - throws IOException - { - SurefireProperties properties = new SurefireProperties( sourceProperties ); - properties.setNullableProperty( FORK_NODE_CONNECTION_STRING, forkNodeConnectionString ); - properties.setProperty( PLUGIN_PID, pid ); + File serialize( + KeyValueSource sourceProperties, + ProviderConfiguration providerConfiguration, + StartupConfiguration startupConfiguration, + Object testSet, + boolean readTestsFromInStream, + Long pid, + int forkNumber, + String forkNodeConnectionString) + throws IOException { + SurefireProperties properties = new SurefireProperties(sourceProperties); + properties.setNullableProperty(FORK_NODE_CONNECTION_STRING, forkNodeConnectionString); + properties.setProperty(PLUGIN_PID, pid); AbstractPathConfiguration cp = startupConfiguration.getClasspathConfiguration(); - properties.setClasspath( CLASSPATH, cp.getTestClasspath() ); - properties.setClasspath( SUREFIRE_CLASSPATH, cp.getProviderClasspath() ); - properties.setProperty( ENABLE_ASSERTIONS, toString( cp.isEnableAssertions() ) ); - properties.setProperty( CHILD_DELEGATION, toString( cp.isChildDelegation() ) ); + properties.setClasspath(CLASSPATH, cp.getTestClasspath()); + properties.setClasspath(SUREFIRE_CLASSPATH, cp.getProviderClasspath()); + properties.setProperty(ENABLE_ASSERTIONS, toString(cp.isEnableAssertions())); + properties.setProperty(CHILD_DELEGATION, toString(cp.isChildDelegation())); ProcessCheckerType processChecker = startupConfiguration.getProcessChecker(); - properties.setNullableProperty( PROCESS_CHECKER, processChecker == null ? null : processChecker.getType() ); + properties.setNullableProperty(PROCESS_CHECKER, processChecker == null ? null : processChecker.getType()); TestArtifactInfo testNg = providerConfiguration.getTestArtifact(); - if ( testNg != null ) - { - properties.setProperty( TESTARTIFACT_VERSION, testNg.getVersion() ); - properties.setNullableProperty( TESTARTIFACT_CLASSIFIER, testNg.getClassifier() ); + if (testNg != null) { + properties.setProperty(TESTARTIFACT_VERSION, testNg.getVersion()); + properties.setNullableProperty(TESTARTIFACT_CLASSIFIER, testNg.getClassifier()); } - properties.setProperty( FORKTESTSET_PREFER_TESTS_FROM_IN_STREAM, readTestsFromInStream ); - properties.setNullableProperty( FORKTESTSET, getTypeEncoded( testSet ) ); + properties.setProperty(FORKTESTSET_PREFER_TESTS_FROM_IN_STREAM, readTestsFromInStream); + properties.setNullableProperty(FORKTESTSET, getTypeEncoded(testSet)); TestRequest testSuiteDefinition = providerConfiguration.getTestSuiteDefinition(); - if ( testSuiteDefinition != null ) - { - properties.setProperty( SOURCE_DIRECTORY, testSuiteDefinition.getTestSourceDirectory() ); - if ( testSet instanceof File ) - { - properties.addList( Collections.singletonList( (File) testSet ), TEST_SUITE_XML_FILES ); - } - else - { - properties.addList( testSuiteDefinition.getSuiteXmlFiles(), TEST_SUITE_XML_FILES ); + if (testSuiteDefinition != null) { + properties.setProperty(SOURCE_DIRECTORY, testSuiteDefinition.getTestSourceDirectory()); + if (testSet instanceof File) { + properties.addList(Collections.singletonList((File) testSet), TEST_SUITE_XML_FILES); + } else { + properties.addList(testSuiteDefinition.getSuiteXmlFiles(), TEST_SUITE_XML_FILES); } TestListResolver testFilter = testSuiteDefinition.getTestListResolver(); - properties.setProperty( REQUESTEDTEST, testFilter == null ? "" : testFilter.getPluginParameterTest() ); + properties.setProperty(REQUESTEDTEST, testFilter == null ? "" : testFilter.getPluginParameterTest()); int rerunFailingTestsCount = testSuiteDefinition.getRerunFailingTestsCount(); - properties.setNullableProperty( RERUN_FAILING_TESTS_COUNT, toString( rerunFailingTestsCount ) ); + properties.setNullableProperty(RERUN_FAILING_TESTS_COUNT, toString(rerunFailingTestsCount)); } DirectoryScannerParameters directoryScannerParameters = providerConfiguration.getDirScannerParams(); - if ( directoryScannerParameters != null ) - { - properties.addList( directoryScannerParameters.getIncludes(), INCLUDES_PROPERTY_PREFIX ); - properties.addList( directoryScannerParameters.getExcludes(), EXCLUDES_PROPERTY_PREFIX ); - properties.addList( directoryScannerParameters.getSpecificTests(), SPECIFIC_TEST_PROPERTY_PREFIX ); - properties.setProperty( TEST_CLASSES_DIRECTORY, directoryScannerParameters.getTestClassesDirectory() ); + if (directoryScannerParameters != null) { + properties.addList(directoryScannerParameters.getIncludes(), INCLUDES_PROPERTY_PREFIX); + properties.addList(directoryScannerParameters.getExcludes(), EXCLUDES_PROPERTY_PREFIX); + properties.addList(directoryScannerParameters.getSpecificTests(), SPECIFIC_TEST_PROPERTY_PREFIX); + properties.setProperty(TEST_CLASSES_DIRECTORY, directoryScannerParameters.getTestClassesDirectory()); } final RunOrderParameters runOrderParameters = providerConfiguration.getRunOrderParameters(); - if ( runOrderParameters != null ) - { - properties.setProperty( RUN_ORDER, RunOrder.asString( runOrderParameters.getRunOrder() ) ); - properties.setProperty( RUN_STATISTICS_FILE, runOrderParameters.getRunStatisticsFile() ); - properties.setProperty( RUN_ORDER_RANDOM_SEED, runOrderParameters.getRunOrderRandomSeed() ); + if (runOrderParameters != null) { + properties.setProperty(RUN_ORDER, RunOrder.asString(runOrderParameters.getRunOrder())); + properties.setProperty(RUN_STATISTICS_FILE, runOrderParameters.getRunStatisticsFile()); + properties.setProperty(RUN_ORDER_RANDOM_SEED, runOrderParameters.getRunOrderRandomSeed()); } ReporterConfiguration reporterConfiguration = providerConfiguration.getReporterConfiguration(); boolean rep = reporterConfiguration.isTrimStackTrace(); - File reportsDirectory = replaceForkThreadsInPath( reporterConfiguration.getReportsDirectory(), forkNumber ); - properties.setProperty( FORK_NUMBER, forkNumber ); - properties.setProperty( ISTRIMSTACKTRACE, rep ); - properties.setProperty( REPORTSDIRECTORY, reportsDirectory ); + File reportsDirectory = replaceForkThreadsInPath(reporterConfiguration.getReportsDirectory(), forkNumber); + properties.setProperty(FORK_NUMBER, forkNumber); + properties.setProperty(ISTRIMSTACKTRACE, rep); + properties.setProperty(REPORTSDIRECTORY, reportsDirectory); ClassLoaderConfiguration classLoaderConfig = startupConfiguration.getClassLoaderConfiguration(); - properties.setProperty( USESYSTEMCLASSLOADER, toString( classLoaderConfig.isUseSystemClassLoader() ) ); - properties.setProperty( USEMANIFESTONLYJAR, toString( classLoaderConfig.isUseManifestOnlyJar() ) ); - properties.setProperty( PROVIDER_CONFIGURATION, startupConfiguration.getProviderClassName() ); - properties.setProperty( FAIL_FAST_COUNT, toString( providerConfiguration.getSkipAfterFailureCount() ) ); - properties.setProperty( SHUTDOWN, providerConfiguration.getShutdown().name() ); + properties.setProperty(USESYSTEMCLASSLOADER, toString(classLoaderConfig.isUseSystemClassLoader())); + properties.setProperty(USEMANIFESTONLYJAR, toString(classLoaderConfig.isUseManifestOnlyJar())); + properties.setProperty(PROVIDER_CONFIGURATION, startupConfiguration.getProviderClassName()); + properties.setProperty(FAIL_FAST_COUNT, toString(providerConfiguration.getSkipAfterFailureCount())); + properties.setProperty(SHUTDOWN, providerConfiguration.getShutdown().name()); List mainCliOptions = providerConfiguration.getMainCliOptions(); - if ( mainCliOptions != null ) - { - properties.addList( mainCliOptions, MAIN_CLI_OPTIONS ); + if (mainCliOptions != null) { + properties.addList(mainCliOptions, MAIN_CLI_OPTIONS); } - properties.setNullableProperty( SYSTEM_EXIT_TIMEOUT, toString( providerConfiguration.getSystemExitTimeout() ) ); + properties.setNullableProperty(SYSTEM_EXIT_TIMEOUT, toString(providerConfiguration.getSystemExitTimeout())); File surefireTmpDir = forkConfiguration.getTempDirectory(); boolean debug = forkConfiguration.isDebug(); - return writePropertiesFile( properties, surefireTmpDir, "surefire", debug ); + return writePropertiesFile(properties, surefireTmpDir, "surefire", debug); } - private static String getTypeEncoded( Object value ) - { - if ( value == null ) - { + private static String getTypeEncoded(Object value) { + if (value == null) { return null; } - String valueToUse = value instanceof Class ? ( (Class) value ).getName() : value.toString(); + String valueToUse = value instanceof Class ? ((Class) value).getName() : value.toString(); return value.getClass().getName() + "|" + valueToUse; } - private static String toString( Object o ) - { - return String.valueOf( o ); + private static String toString(Object o) { + return String.valueOf(o); } } diff --git a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/ChecksumCalculator.java b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/ChecksumCalculator.java index 2e87a4d8ab..498d6c95db 100644 --- a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/ChecksumCalculator.java +++ b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/ChecksumCalculator.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire.booterclient; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,9 +16,7 @@ * specific language governing permissions and limitations * under the License. */ - -import org.apache.maven.artifact.Artifact; -import org.apache.maven.artifact.repository.ArtifactRepository; +package org.apache.maven.plugin.surefire.booterclient; import java.io.File; import java.security.MessageDigest; @@ -29,141 +25,111 @@ import java.util.List; import java.util.Map; +import org.apache.maven.artifact.Artifact; +import org.apache.maven.artifact.repository.ArtifactRepository; + import static java.nio.charset.StandardCharsets.UTF_8; /** * @author Kristian Rosenvold */ -public class ChecksumCalculator -{ +public class ChecksumCalculator { private static final String HEX = "0123456789ABCDEF"; private final List checksumItems = new ArrayList<>(); - private void appendObject( Object item ) - { - checksumItems.add( item ); + private void appendObject(Object item) { + checksumItems.add(item); } - public void add( boolean value ) - { - checksumItems.add( value ); + public void add(boolean value) { + checksumItems.add(value); } - public void add( int value ) - { - checksumItems.add( value ); + public void add(int value) { + checksumItems.add(value); } - public void add( double value ) - { - checksumItems.add( value ); + public void add(double value) { + checksumItems.add(value); } - public void add( Map map ) - { - if ( map != null ) - { - appendObject( map.toString() ); + public void add(Map map) { + if (map != null) { + appendObject(map.toString()); } } - public void add( String string ) - { - appendObject( string ); + public void add(String string) { + appendObject(string); } - public void add( File workingDirectory ) - { - appendObject( workingDirectory ); + public void add(File workingDirectory) { + appendObject(workingDirectory); } - public void add( ArtifactRepository localRepository ) - { - appendObject( localRepository ); + public void add(ArtifactRepository localRepository) { + appendObject(localRepository); } - public void add( List items ) - { - if ( items != null ) - { - for ( Object item : items ) - { - appendObject( item ); + public void add(List items) { + if (items != null) { + for (Object item : items) { + appendObject(item); } + } else { + appendObject(null); } - else - { - appendObject( null ); - } - } - public void add( Object[] items ) - { - if ( items != null ) - { - for ( Object item : items ) - { - appendObject( item ); + public void add(Object[] items) { + if (items != null) { + for (Object item : items) { + appendObject(item); } - } - else - { - appendObject( null ); + } else { + appendObject(null); } } - public void add( Artifact artifact ) - { - appendObject( artifact != null ? artifact.getId() : null ); + public void add(Artifact artifact) { + appendObject(artifact != null ? artifact.getId() : null); } - public void add( Boolean aBoolean ) - { - appendObject( aBoolean ); + public void add(Boolean aBoolean) { + appendObject(aBoolean); } - @SuppressWarnings( "checkstyle:magicnumber" ) - private static String asHexString( byte[] bytes ) - { - if ( bytes == null ) - { + @SuppressWarnings("checkstyle:magicnumber") + private static String asHexString(byte[] bytes) { + if (bytes == null) { return null; } - final StringBuilder result = new StringBuilder( 2 * bytes.length ); - for ( byte b : bytes ) - { - result.append( HEX.charAt( ( b & 0xF0 ) >> 4 ) ).append( HEX.charAt( ( b & 0x0F ) ) ); + final StringBuilder result = new StringBuilder(2 * bytes.length); + for (byte b : bytes) { + result.append(HEX.charAt((b & 0xF0) >> 4)).append(HEX.charAt((b & 0x0F))); } return result.toString(); } - private String getConfig() - { + private String getConfig() { StringBuilder result = new StringBuilder(); - for ( Object checksumItem : checksumItems ) - { - result.append( checksumItem != null ? checksumItem.toString() : "null" ); + for (Object checksumItem : checksumItems) { + result.append(checksumItem != null ? checksumItem.toString() : "null"); } return result.toString(); } - public String getSha1() - { - try - { - MessageDigest md = MessageDigest.getInstance( "SHA-1" ); + public String getSha1() { + try { + MessageDigest md = MessageDigest.getInstance("SHA-1"); String configValue = getConfig(); - byte[] configBytes = configValue.getBytes( UTF_8 ); - md.update( configBytes ); + byte[] configBytes = configValue.getBytes(UTF_8); + md.update(configBytes); byte[] sha1hash = md.digest(); - return asHexString( sha1hash ); - } - catch ( NoSuchAlgorithmException e ) - { - throw new RuntimeException( e ); + return asHexString(sha1hash); + } catch (NoSuchAlgorithmException e) { + throw new RuntimeException(e); } } - } diff --git a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/ClasspathForkConfiguration.java b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/ClasspathForkConfiguration.java index 1ce9d617ef..16b4800dae 100644 --- a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/ClasspathForkConfiguration.java +++ b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/ClasspathForkConfiguration.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire.booterclient; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,14 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.surefire.booterclient; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; + +import java.io.File; +import java.util.Map; +import java.util.Properties; import org.apache.maven.plugin.surefire.booterclient.lazytestprovider.Commandline; import org.apache.maven.plugin.surefire.log.api.ConsoleLogger; @@ -26,45 +32,54 @@ import org.apache.maven.surefire.booter.SurefireBooterForkException; import org.apache.maven.surefire.extensions.ForkNodeFactory; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; -import java.io.File; -import java.util.Map; -import java.util.Properties; - import static org.apache.maven.surefire.shared.utils.StringUtils.join; /** * @author Tibor Digana (tibor17) * @since 2.21.0.Jigsaw */ -public final class ClasspathForkConfiguration - extends AbstractClasspathForkConfiguration -{ - @SuppressWarnings( "checkstyle:parameternumber" ) - public ClasspathForkConfiguration( @Nonnull Classpath bootClasspath, @Nonnull File tempDirectory, - @Nullable String debugLine, @Nonnull File workingDirectory, - @Nonnull Properties modelProperties, @Nullable String argLine, - @Nonnull Map environmentVariables, - @Nonnull String[] excludedEnvironmentVariables, - boolean debug, int forkCount, - boolean reuseForks, @Nonnull Platform pluginPlatform, - @Nonnull ConsoleLogger log, - @Nonnull ForkNodeFactory forkNodeFactory ) - { - super( bootClasspath, tempDirectory, debugLine, workingDirectory, modelProperties, argLine, - environmentVariables, excludedEnvironmentVariables, debug, forkCount, reuseForks, pluginPlatform, log, - forkNodeFactory ); +public final class ClasspathForkConfiguration extends AbstractClasspathForkConfiguration { + @SuppressWarnings("checkstyle:parameternumber") + public ClasspathForkConfiguration( + @Nonnull Classpath bootClasspath, + @Nonnull File tempDirectory, + @Nullable String debugLine, + @Nonnull File workingDirectory, + @Nonnull Properties modelProperties, + @Nullable String argLine, + @Nonnull Map environmentVariables, + @Nonnull String[] excludedEnvironmentVariables, + boolean debug, + int forkCount, + boolean reuseForks, + @Nonnull Platform pluginPlatform, + @Nonnull ConsoleLogger log, + @Nonnull ForkNodeFactory forkNodeFactory) { + super( + bootClasspath, + tempDirectory, + debugLine, + workingDirectory, + modelProperties, + argLine, + environmentVariables, + excludedEnvironmentVariables, + debug, + forkCount, + reuseForks, + pluginPlatform, + log, + forkNodeFactory); } @Override - protected void resolveClasspath( @Nonnull Commandline cli, - @Nonnull String booterThatHasMainMethod, - @Nonnull StartupConfiguration config, - @Nonnull File dumpLogDirectory ) - throws SurefireBooterForkException - { - cli.addEnvironment( "CLASSPATH", join( toCompleteClasspath( config ).iterator(), File.pathSeparator ) ); - cli.createArg().setValue( booterThatHasMainMethod ); + protected void resolveClasspath( + @Nonnull Commandline cli, + @Nonnull String booterThatHasMainMethod, + @Nonnull StartupConfiguration config, + @Nonnull File dumpLogDirectory) + throws SurefireBooterForkException { + cli.addEnvironment("CLASSPATH", join(toCompleteClasspath(config).iterator(), File.pathSeparator)); + cli.createArg().setValue(booterThatHasMainMethod); } } diff --git a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/DefaultForkConfiguration.java b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/DefaultForkConfiguration.java index b70abd75f1..d469c15d09 100644 --- a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/DefaultForkConfiguration.java +++ b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/DefaultForkConfiguration.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire.booterclient; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,30 +16,32 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.surefire.booterclient; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; + +import java.io.File; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Properties; import org.apache.maven.plugin.surefire.JdkAttributes; import org.apache.maven.plugin.surefire.booterclient.lazytestprovider.Commandline; import org.apache.maven.plugin.surefire.log.api.ConsoleLogger; +import org.apache.maven.surefire.api.util.internal.ImmutableMap; import org.apache.maven.surefire.booter.AbstractPathConfiguration; import org.apache.maven.surefire.booter.Classpath; import org.apache.maven.surefire.booter.StartupConfiguration; import org.apache.maven.surefire.booter.SurefireBooterForkException; import org.apache.maven.surefire.extensions.ForkNodeFactory; -import org.apache.maven.surefire.api.util.internal.ImmutableMap; import org.apache.maven.surefire.shared.utils.cli.CommandLineException; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; -import java.io.File; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Properties; - import static org.apache.maven.plugin.surefire.SurefireHelper.replaceForkThreadsInPath; -import static org.apache.maven.plugin.surefire.util.Relocator.relocate; import static org.apache.maven.plugin.surefire.SurefireHelper.replaceThreadNumberPlaceholders; +import static org.apache.maven.plugin.surefire.util.Relocator.relocate; import static org.apache.maven.surefire.booter.Classpath.join; /** @@ -50,48 +50,67 @@ * @author Tibor Digana (tibor17) * @since 2.21.0.Jigsaw */ -public abstract class DefaultForkConfiguration - extends ForkConfiguration -{ - @Nonnull private final Classpath booterClasspath; - @Nonnull private final File tempDirectory; +public abstract class DefaultForkConfiguration extends ForkConfiguration { + @Nonnull + private final Classpath booterClasspath; + + @Nonnull + private final File tempDirectory; + @Nullable private final String debugLine; - @Nonnull private final File workingDirectory; - @Nonnull private final Properties modelProperties; - @Nullable private final String argLine; - @Nonnull private final Map environmentVariables; - @Nonnull private final String[] excludedEnvironmentVariables; + + @Nonnull + private final File workingDirectory; + + @Nonnull + private final Properties modelProperties; + + @Nullable + private final String argLine; + + @Nonnull + private final Map environmentVariables; + + @Nonnull + private final String[] excludedEnvironmentVariables; + private final boolean debug; private final int forkCount; private final boolean reuseForks; - @Nonnull private final Platform pluginPlatform; - @Nonnull private final ConsoleLogger log; - @Nonnull private final ForkNodeFactory forkNodeFactory; - - @SuppressWarnings( "checkstyle:parameternumber" ) - protected DefaultForkConfiguration( @Nonnull Classpath booterClasspath, - @Nonnull File tempDirectory, - @Nullable String debugLine, - @Nonnull File workingDirectory, - @Nonnull Properties modelProperties, - @Nullable String argLine, - @Nonnull Map environmentVariables, - @Nonnull String[] excludedEnvironmentVariables, - boolean debug, - int forkCount, - boolean reuseForks, - @Nonnull Platform pluginPlatform, - @Nonnull ConsoleLogger log, - @Nonnull ForkNodeFactory forkNodeFactory ) - { + + @Nonnull + private final Platform pluginPlatform; + + @Nonnull + private final ConsoleLogger log; + + @Nonnull + private final ForkNodeFactory forkNodeFactory; + + @SuppressWarnings("checkstyle:parameternumber") + protected DefaultForkConfiguration( + @Nonnull Classpath booterClasspath, + @Nonnull File tempDirectory, + @Nullable String debugLine, + @Nonnull File workingDirectory, + @Nonnull Properties modelProperties, + @Nullable String argLine, + @Nonnull Map environmentVariables, + @Nonnull String[] excludedEnvironmentVariables, + boolean debug, + int forkCount, + boolean reuseForks, + @Nonnull Platform pluginPlatform, + @Nonnull ConsoleLogger log, + @Nonnull ForkNodeFactory forkNodeFactory) { this.booterClasspath = booterClasspath; this.tempDirectory = tempDirectory; this.debugLine = debugLine; this.workingDirectory = workingDirectory; this.modelProperties = modelProperties; this.argLine = argLine; - this.environmentVariables = toImmutable( environmentVariables ); + this.environmentVariables = toImmutable(environmentVariables); this.excludedEnvironmentVariables = excludedEnvironmentVariables; this.debug = debug; this.forkCount = forkCount; @@ -101,22 +120,21 @@ protected DefaultForkConfiguration( @Nonnull Classpath booterClasspath, this.forkNodeFactory = forkNodeFactory; } - protected abstract void resolveClasspath( @Nonnull Commandline cli, - @Nonnull String booterThatHasMainMethod, - @Nonnull StartupConfiguration config, - @Nonnull File dumpLogDirectory ) + protected abstract void resolveClasspath( + @Nonnull Commandline cli, + @Nonnull String booterThatHasMainMethod, + @Nonnull StartupConfiguration config, + @Nonnull File dumpLogDirectory) throws SurefireBooterForkException; @Nonnull - protected String extendJvmArgLine( @Nonnull String jvmArgLine ) - { + protected String extendJvmArgLine(@Nonnull String jvmArgLine) { return jvmArgLine; } @Nonnull @Override - public final ForkNodeFactory getForkNodeFactory() - { + public final ForkNodeFactory getForkNodeFactory() { return forkNodeFactory; } @@ -129,89 +147,71 @@ public final ForkNodeFactory getForkNodeFactory() */ @Nonnull @Override - public Commandline createCommandLine( @Nonnull StartupConfiguration config, - int forkNumber, - @Nonnull File dumpLogDirectory ) - throws SurefireBooterForkException - { - try - { - Commandline cli = - new Commandline( getExcludedEnvironmentVariables() ); - - cli.setWorkingDirectory( getWorkingDirectory( forkNumber ).getAbsolutePath() ); - - for ( Entry entry : getEnvironmentVariables().entrySet() ) - { + public Commandline createCommandLine( + @Nonnull StartupConfiguration config, int forkNumber, @Nonnull File dumpLogDirectory) + throws SurefireBooterForkException { + try { + Commandline cli = new Commandline(getExcludedEnvironmentVariables()); + + cli.setWorkingDirectory(getWorkingDirectory(forkNumber).getAbsolutePath()); + + for (Entry entry : getEnvironmentVariables().entrySet()) { String value = entry.getValue(); - cli.addEnvironment( entry.getKey(), value == null ? "" : value ); + cli.addEnvironment(entry.getKey(), value == null ? "" : value); } - cli.setExecutable( getJdkForTests().getJvmExecutable().getAbsolutePath() ); + cli.setExecutable(getJdkForTests().getJvmExecutable().getAbsolutePath()); - String jvmArgLine = newJvmArgLine( forkNumber ); - if ( !jvmArgLine.isEmpty() ) - { - cli.createArg() - .setLine( jvmArgLine ); + String jvmArgLine = newJvmArgLine(forkNumber); + if (!jvmArgLine.isEmpty()) { + cli.createArg().setLine(jvmArgLine); } - if ( getDebugLine() != null && !getDebugLine().isEmpty() ) - { - cli.createArg() - .setLine( getDebugLine() ); + if (getDebugLine() != null && !getDebugLine().isEmpty()) { + cli.createArg().setLine(getDebugLine()); } - resolveClasspath( cli, findStartClass( config ), config, dumpLogDirectory ); + resolveClasspath(cli, findStartClass(config), config, dumpLogDirectory); return cli; - } - catch ( CommandLineException e ) - { - throw new SurefireBooterForkException( e.getLocalizedMessage(), e ); + } catch (CommandLineException e) { + throw new SurefireBooterForkException(e.getLocalizedMessage(), e); } } - protected ConsoleLogger getLogger() - { + protected ConsoleLogger getLogger() { return log; } @Nonnull - protected List toCompleteClasspath( @Nonnull StartupConfiguration conf ) throws SurefireBooterForkException - { + protected List toCompleteClasspath(@Nonnull StartupConfiguration conf) throws SurefireBooterForkException { AbstractPathConfiguration pathConfig = conf.getClasspathConfiguration(); - if ( pathConfig.isClassPathConfig() == pathConfig.isModularPathConfig() ) - { - throw new SurefireBooterForkException( "Could not find class-path config nor modular class-path either." ); + if (pathConfig.isClassPathConfig() == pathConfig.isModularPathConfig()) { + throw new SurefireBooterForkException("Could not find class-path config nor modular class-path either."); } Classpath bootClasspath = getBooterClasspath(); Classpath testClasspath = pathConfig.getTestClasspath(); Classpath providerClasspath = pathConfig.getProviderClasspath(); - Classpath completeClasspath = join( join( bootClasspath, testClasspath ), providerClasspath ); + Classpath completeClasspath = join(join(bootClasspath, testClasspath), providerClasspath); - getLogger().debug( completeClasspath.getLogMessage( "boot classpath:" ) ); - getLogger().debug( completeClasspath.getCompactLogMessage( "boot(compact) classpath:" ) ); + getLogger().debug(completeClasspath.getLogMessage("boot classpath:")); + getLogger().debug(completeClasspath.getCompactLogMessage("boot(compact) classpath:")); return completeClasspath.getClassPath(); } @Nonnull - private File getWorkingDirectory( int forkNumber ) - throws SurefireBooterForkException - { - File cwd = replaceForkThreadsInPath( getWorkingDirectory(), forkNumber ); - - if ( !cwd.exists() && !cwd.mkdirs() ) - { - throw new SurefireBooterForkException( "Cannot create workingDirectory " + cwd.getAbsolutePath() ); + private File getWorkingDirectory(int forkNumber) throws SurefireBooterForkException { + File cwd = replaceForkThreadsInPath(getWorkingDirectory(), forkNumber); + + if (!cwd.exists() && !cwd.mkdirs()) { + throw new SurefireBooterForkException("Cannot create workingDirectory " + cwd.getAbsolutePath()); } - if ( !cwd.isDirectory() ) - { + if (!cwd.isDirectory()) { throw new SurefireBooterForkException( - "WorkingDirectory " + cwd.getAbsolutePath() + " exists and is not a directory" ); + "WorkingDirectory " + cwd.getAbsolutePath() + " exists and is not a directory"); } return cwd; } @@ -224,26 +224,22 @@ private File getWorkingDirectory( int forkNumber ) * This allows other plugins to modify or set properties with the changes getting picked up by surefire. */ @Nonnull - private String interpolateArgLineWithPropertyExpressions() - { - if ( getArgLine() == null ) - { + private String interpolateArgLineWithPropertyExpressions() { + if (getArgLine() == null) { return ""; } String resolvedArgLine = getArgLine().trim(); - if ( resolvedArgLine.isEmpty() ) - { + if (resolvedArgLine.isEmpty()) { return ""; } - for ( final String key : getModelProperties().stringPropertyNames() ) - { + for (final String key : getModelProperties().stringPropertyNames()) { String field = "@{" + key + "}"; - if ( getArgLine().contains( field ) ) - { - resolvedArgLine = resolvedArgLine.replace( field, getModelProperties().getProperty( key, "" ) ); + if (getArgLine().contains(field)) { + resolvedArgLine = + resolvedArgLine.replace(field, getModelProperties().getProperty(key, "")); } } @@ -251,9 +247,8 @@ private String interpolateArgLineWithPropertyExpressions() } @Nonnull - private static String stripWhitespace( @Nonnull String argLine ) - { - return argLine.replaceAll( "\\s", " " ); + private static String stripWhitespace(@Nonnull String argLine) { + return argLine.replaceAll("\\s", " "); } /** @@ -265,110 +260,94 @@ private static String stripWhitespace( @Nonnull String argLine ) * @return never returns null */ @Nonnull - private static Map toImmutable( @Nullable Map map ) - { - return map == null ? Collections.emptyMap() : new ImmutableMap<>( map ); + private static Map toImmutable(@Nullable Map map) { + return map == null ? Collections.emptyMap() : new ImmutableMap<>(map); } @Override @Nonnull - public File getTempDirectory() - { + public File getTempDirectory() { return tempDirectory; } @Override @Nullable - protected String getDebugLine() - { + protected String getDebugLine() { return debugLine; } @Override @Nonnull - protected File getWorkingDirectory() - { + protected File getWorkingDirectory() { return workingDirectory; } @Override @Nonnull - protected Properties getModelProperties() - { + protected Properties getModelProperties() { return modelProperties; } @Override @Nullable - protected String getArgLine() - { + protected String getArgLine() { return argLine; } @Override @Nonnull - protected Map getEnvironmentVariables() - { + protected Map getEnvironmentVariables() { return environmentVariables; } @Nonnull @Override - protected String[] getExcludedEnvironmentVariables() - { + protected String[] getExcludedEnvironmentVariables() { return excludedEnvironmentVariables; } @Override - protected boolean isDebug() - { + protected boolean isDebug() { return debug; } @Override - protected int getForkCount() - { + protected int getForkCount() { return forkCount; } @Override - protected boolean isReuseForks() - { + protected boolean isReuseForks() { return reuseForks; } @Override @Nonnull - protected Platform getPluginPlatform() - { + protected Platform getPluginPlatform() { return pluginPlatform; } @Override @Nonnull - protected JdkAttributes getJdkForTests() - { + protected JdkAttributes getJdkForTests() { return getPluginPlatform().getJdkExecAttributesForTests(); } @Override @Nonnull - protected Classpath getBooterClasspath() - { + protected Classpath getBooterClasspath() { return booterClasspath; } @Nonnull - private String newJvmArgLine( int forks ) - { - String interpolatedArgs = stripWhitespace( interpolateArgLineWithPropertyExpressions() ); - String argsWithReplacedForkNumbers = replaceThreadNumberPlaceholders( interpolatedArgs, forks ); - return extendJvmArgLine( argsWithReplacedForkNumbers ); + private String newJvmArgLine(int forks) { + String interpolatedArgs = stripWhitespace(interpolateArgLineWithPropertyExpressions()); + String argsWithReplacedForkNumbers = replaceThreadNumberPlaceholders(interpolatedArgs, forks); + return extendJvmArgLine(argsWithReplacedForkNumbers); } @Nonnull - private static String findStartClass( StartupConfiguration config ) - { - return config.isShadefire() ? relocate( DEFAULT_PROVIDER_CLASS ) : DEFAULT_PROVIDER_CLASS; + private static String findStartClass(StartupConfiguration config) { + return config.isShadefire() ? relocate(DEFAULT_PROVIDER_CLASS) : DEFAULT_PROVIDER_CLASS; } } diff --git a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/ForkConfiguration.java b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/ForkConfiguration.java index 83781344b1..f5b37ede3d 100644 --- a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/ForkConfiguration.java +++ b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/ForkConfiguration.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire.booterclient; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,14 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.surefire.booterclient; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; + +import java.io.File; +import java.util.Map; +import java.util.Properties; import org.apache.maven.plugin.surefire.JdkAttributes; import org.apache.maven.plugin.surefire.booterclient.lazytestprovider.Commandline; @@ -27,33 +33,50 @@ import org.apache.maven.surefire.booter.SurefireBooterForkException; import org.apache.maven.surefire.extensions.ForkNodeFactory; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; -import java.io.File; -import java.util.Map; -import java.util.Properties; - /** * Configuration for forking tests. */ -public abstract class ForkConfiguration -{ +public abstract class ForkConfiguration { static final String DEFAULT_PROVIDER_CLASS = ForkedBooter.class.getName(); - @Nonnull public abstract ForkNodeFactory getForkNodeFactory(); - @Nonnull public abstract File getTempDirectory(); - @Nullable protected abstract String getDebugLine(); - @Nonnull protected abstract File getWorkingDirectory(); - @Nonnull protected abstract Properties getModelProperties(); - @Nullable protected abstract String getArgLine(); - @Nonnull protected abstract Map getEnvironmentVariables(); - @Nonnull protected abstract String[] getExcludedEnvironmentVariables(); + @Nonnull + public abstract ForkNodeFactory getForkNodeFactory(); + + @Nonnull + public abstract File getTempDirectory(); + + @Nullable + protected abstract String getDebugLine(); + + @Nonnull + protected abstract File getWorkingDirectory(); + + @Nonnull + protected abstract Properties getModelProperties(); + + @Nullable + protected abstract String getArgLine(); + + @Nonnull + protected abstract Map getEnvironmentVariables(); + + @Nonnull + protected abstract String[] getExcludedEnvironmentVariables(); + protected abstract boolean isDebug(); + protected abstract int getForkCount(); + protected abstract boolean isReuseForks(); - @Nonnull protected abstract Platform getPluginPlatform(); - @Nonnull protected abstract JdkAttributes getJdkForTests(); - @Nonnull protected abstract Classpath getBooterClasspath(); + + @Nonnull + protected abstract Platform getPluginPlatform(); + + @Nonnull + protected abstract JdkAttributes getJdkForTests(); + + @Nonnull + protected abstract Classpath getBooterClasspath(); /** * @param config The startup configuration @@ -64,8 +87,7 @@ public abstract class ForkConfiguration * when unable to perform the fork */ @Nonnull - public abstract Commandline createCommandLine( @Nonnull StartupConfiguration config, - int forkNumber, - @Nonnull File dumpLogDirectory ) + public abstract Commandline createCommandLine( + @Nonnull StartupConfiguration config, int forkNumber, @Nonnull File dumpLogDirectory) throws SurefireBooterForkException; } diff --git a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/ForkNumberBucket.java b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/ForkNumberBucket.java index d5d52e6075..dde528456c 100644 --- a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/ForkNumberBucket.java +++ b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/ForkNumberBucket.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire.booterclient; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.surefire.booterclient; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; @@ -29,43 +28,37 @@ * * @author Andreas Gudian */ -public final class ForkNumberBucket -{ +public final class ForkNumberBucket { private static final ForkNumberBucket INSTANCE = new ForkNumberBucket(); private final Queue qFree = new ConcurrentLinkedQueue<>(); - private final AtomicInteger highWaterMark = new AtomicInteger( 1 ); + private final AtomicInteger highWaterMark = new AtomicInteger(1); /** * Non-public constructor */ - private ForkNumberBucket() - { - } + private ForkNumberBucket() {} /** * @return a fork number that is not currently in use. The value must be returned to the bucket using * {@link #returnNumber(int)}. */ - public static int drawNumber() - { + public static int drawNumber() { return getInstance().drawNumberInternal(); } /** * @param number the number to return to the bucket so that it can be reused. */ - public static void returnNumber( int number ) - { - getInstance().returnNumberInternal( number ); + public static void returnNumber(int number) { + getInstance().returnNumberInternal(number); } /** * @return a singleton instance */ - private static ForkNumberBucket getInstance() - { + private static ForkNumberBucket getInstance() { return INSTANCE; } @@ -73,8 +66,7 @@ private static ForkNumberBucket getInstance() * @return a fork number that is not currently in use. The value must be returned to the bucket using * {@link #returnNumber(int)}. */ - private int drawNumberInternal() - { + private int drawNumberInternal() { Integer nextFree = qFree.poll(); return nextFree == null ? highWaterMark.getAndIncrement() : nextFree; } @@ -82,16 +74,14 @@ private int drawNumberInternal() /** * @return the highest number that has been drawn */ - private int getHighestDrawnNumber() - { + private int getHighestDrawnNumber() { return highWaterMark.get() - 1; } /** * @param number the number to return to the bucket so that it can be reused. */ - private void returnNumberInternal( int number ) - { - qFree.add( number ); + private void returnNumberInternal(int number) { + qFree.add(number); } } diff --git a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/ForkStarter.java b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/ForkStarter.java index 17b0e5412c..c612861eb8 100644 --- a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/ForkStarter.java +++ b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/ForkStarter.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire.booterclient; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,13 +16,37 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.surefire.booterclient; + +import javax.annotation.Nonnull; + +import java.io.Closeable; +import java.io.File; +import java.io.IOException; +import java.util.Collection; +import java.util.Map; +import java.util.Queue; +import java.util.Set; +import java.util.concurrent.ArrayBlockingQueue; +import java.util.concurrent.Callable; +import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.concurrent.ConcurrentSkipListSet; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Future; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.ThreadFactory; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.atomic.AtomicInteger; import org.apache.maven.plugin.surefire.CommonReflector; import org.apache.maven.plugin.surefire.StartupReportConfiguration; import org.apache.maven.plugin.surefire.SurefireProperties; import org.apache.maven.plugin.surefire.booterclient.lazytestprovider.AbstractCommandReader; -import org.apache.maven.plugin.surefire.booterclient.lazytestprovider.NotifiableTestStream; import org.apache.maven.plugin.surefire.booterclient.lazytestprovider.Commandline; +import org.apache.maven.plugin.surefire.booterclient.lazytestprovider.NotifiableTestStream; import org.apache.maven.plugin.surefire.booterclient.lazytestprovider.TestLessInputStream; import org.apache.maven.plugin.surefire.booterclient.lazytestprovider.TestProvidingInputStream; import org.apache.maven.plugin.surefire.booterclient.output.ForkClient; @@ -34,50 +56,28 @@ import org.apache.maven.plugin.surefire.log.api.ConsoleLogger; import org.apache.maven.plugin.surefire.report.DefaultReporterFactory; import org.apache.maven.plugin.surefire.report.ReportsMerger; +import org.apache.maven.surefire.api.booter.Shutdown; +import org.apache.maven.surefire.api.fork.ForkNodeArguments; +import org.apache.maven.surefire.api.provider.SurefireProvider; +import org.apache.maven.surefire.api.report.StackTraceWriter; +import org.apache.maven.surefire.api.suite.RunResult; +import org.apache.maven.surefire.api.testset.TestRequest; +import org.apache.maven.surefire.api.util.DefaultScanResult; import org.apache.maven.surefire.booter.AbstractPathConfiguration; import org.apache.maven.surefire.booter.PropertiesWrapper; import org.apache.maven.surefire.booter.ProviderConfiguration; import org.apache.maven.surefire.booter.ProviderFactory; -import org.apache.maven.surefire.api.booter.Shutdown; import org.apache.maven.surefire.booter.StartupConfiguration; import org.apache.maven.surefire.booter.SurefireBooterForkException; import org.apache.maven.surefire.booter.SurefireExecutionException; import org.apache.maven.surefire.extensions.EventHandler; import org.apache.maven.surefire.extensions.ForkChannel; import org.apache.maven.surefire.extensions.ForkNodeFactory; -import org.apache.maven.surefire.api.fork.ForkNodeArguments; import org.apache.maven.surefire.extensions.Stoppable; import org.apache.maven.surefire.extensions.util.CommandlineExecutor; import org.apache.maven.surefire.extensions.util.CommandlineStreams; import org.apache.maven.surefire.extensions.util.CountdownCloseable; import org.apache.maven.surefire.extensions.util.LineConsumerThread; -import org.apache.maven.surefire.api.provider.SurefireProvider; -import org.apache.maven.surefire.api.report.StackTraceWriter; -import org.apache.maven.surefire.api.suite.RunResult; -import org.apache.maven.surefire.api.testset.TestRequest; -import org.apache.maven.surefire.api.util.DefaultScanResult; - -import javax.annotation.Nonnull; -import java.io.Closeable; -import java.io.File; -import java.io.IOException; -import java.util.Collection; -import java.util.Map; -import java.util.Queue; -import java.util.Set; -import java.util.concurrent.ArrayBlockingQueue; -import java.util.concurrent.Callable; -import java.util.concurrent.ConcurrentLinkedQueue; -import java.util.concurrent.ConcurrentSkipListSet; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Future; -import java.util.concurrent.LinkedBlockingQueue; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.ScheduledFuture; -import java.util.concurrent.ThreadFactory; -import java.util.concurrent.ThreadPoolExecutor; -import java.util.concurrent.atomic.AtomicInteger; import static java.lang.StrictMath.min; import static java.lang.System.currentTimeMillis; @@ -95,10 +95,7 @@ import static org.apache.maven.plugin.surefire.booterclient.ForkNumberBucket.drawNumber; import static org.apache.maven.plugin.surefire.booterclient.ForkNumberBucket.returnNumber; import static org.apache.maven.plugin.surefire.booterclient.lazytestprovider.TestLessInputStream.TestLessInputStreamBuilder; -import static org.apache.maven.surefire.booter.SystemPropertyManager.writePropertiesFile; import static org.apache.maven.surefire.api.cli.CommandLineOption.SHOW_ERRORS; -import static org.apache.maven.surefire.shared.utils.cli.ShutdownHookUtils.addShutDownHook; -import static org.apache.maven.surefire.shared.utils.cli.ShutdownHookUtils.removeShutdownHook; import static org.apache.maven.surefire.api.suite.RunResult.SUCCESS; import static org.apache.maven.surefire.api.suite.RunResult.failure; import static org.apache.maven.surefire.api.suite.RunResult.timeout; @@ -106,6 +103,9 @@ import static org.apache.maven.surefire.api.util.internal.DaemonThreadFactory.newDaemonThread; import static org.apache.maven.surefire.api.util.internal.DaemonThreadFactory.newDaemonThreadFactory; import static org.apache.maven.surefire.api.util.internal.StringUtils.NL; +import static org.apache.maven.surefire.booter.SystemPropertyManager.writePropertiesFile; +import static org.apache.maven.surefire.shared.utils.cli.ShutdownHookUtils.addShutDownHook; +import static org.apache.maven.surefire.shared.utils.cli.ShutdownHookUtils.removeShutdownHook; /** * Starts the fork or runs in-process. @@ -121,19 +121,18 @@ * @author Carlos Sanchez * @author Kristian Rosenvold */ -public class ForkStarter -{ +public class ForkStarter { private static final String EXECUTION_EXCEPTION = "ExecutionException"; private static final long PING_IN_SECONDS = 10; private static final int TIMEOUT_CHECK_PERIOD_MILLIS = 100; - private static final ThreadFactory FORKED_JVM_DAEMON_THREAD_FACTORY - = newDaemonThreadFactory( "surefire-fork-starter" ); + private static final ThreadFactory FORKED_JVM_DAEMON_THREAD_FACTORY = + newDaemonThreadFactory("surefire-fork-starter"); - private static final ThreadFactory SHUTDOWN_HOOK_THREAD_FACTORY - = newDaemonThreadFactory( "surefire-jvm-killer-shutdownhook" ); + private static final ThreadFactory SHUTDOWN_HOOK_THREAD_FACTORY = + newDaemonThreadFactory("surefire-jvm-killer-shutdownhook"); private static final AtomicInteger SYSTEM_PROPERTIES_FILE_COUNTER = new AtomicInteger(); @@ -164,43 +163,32 @@ public class ForkStarter /** * Closes stuff, with a shutdown hook to make sure things really get closed. */ - private final class CloseableCloser - implements Runnable, Closeable - { + private final class CloseableCloser implements Runnable, Closeable { private final int jvmRun; private final Queue testProvidingInputStream; private final Thread inputStreamCloserHook; - CloseableCloser( int jvmRun, Closeable... testProvidingInputStream ) - { + CloseableCloser(int jvmRun, Closeable... testProvidingInputStream) { this.jvmRun = jvmRun; this.testProvidingInputStream = new ConcurrentLinkedQueue<>(); - addAll( this.testProvidingInputStream, testProvidingInputStream ); - if ( this.testProvidingInputStream.isEmpty() ) - { + addAll(this.testProvidingInputStream, testProvidingInputStream); + if (this.testProvidingInputStream.isEmpty()) { inputStreamCloserHook = null; - } - else - { - inputStreamCloserHook = newDaemonThread( this, "closer-shutdown-hook" ); - addShutDownHook( inputStreamCloserHook ); + } else { + inputStreamCloserHook = newDaemonThread(this, "closer-shutdown-hook"); + addShutDownHook(inputStreamCloserHook); } } @Override - @SuppressWarnings( "checkstyle:innerassignment" ) - public void run() - { - for ( Closeable closeable; ( closeable = testProvidingInputStream.poll() ) != null; ) - { - try - { + @SuppressWarnings("checkstyle:innerassignment") + public void run() { + for (Closeable closeable; (closeable = testProvidingInputStream.poll()) != null; ) { + try { closeable.close(); - } - catch ( IOException | RuntimeException e ) - { + } catch (IOException | RuntimeException e) { // This error does not fail a test and does not necessarily mean that the forked JVM std/out stream // was not closed, see ThreadedStreamConsumer. This error means that JVM wrote messages to a native // stream which could not be parsed or report failed. The tests may still correctly run nevertheless @@ -209,47 +197,44 @@ public void run() // inform the users. String msg = "ForkStarter IOException: " + e.getLocalizedMessage() + "."; File reportsDir = reportMerger.getReportsDirectory(); - File dump = InPluginProcessDumpSingleton.getSingleton() - .dumpStreamException( e, msg, reportsDir, jvmRun ); - log.warning( msg + " See the dump file " + dump.getAbsolutePath() ); + File dump = + InPluginProcessDumpSingleton.getSingleton().dumpStreamException(e, msg, reportsDir, jvmRun); + log.warning(msg + " See the dump file " + dump.getAbsolutePath()); } } } @Override - public void close() - { - try - { + public void close() { + try { run(); - } - finally - { + } finally { testProvidingInputStream.clear(); - if ( inputStreamCloserHook != null ) - { - removeShutdownHook( inputStreamCloserHook ); + if (inputStreamCloserHook != null) { + removeShutdownHook(inputStreamCloserHook); } } } - void addCloseable( Closeable closeable ) - { - testProvidingInputStream.add( closeable ); + void addCloseable(Closeable closeable) { + testProvidingInputStream.add(closeable); } } - public ForkStarter( ProviderConfiguration providerConfiguration, StartupConfiguration startupConfiguration, - ForkConfiguration forkConfiguration, int forkedProcessTimeoutInSeconds, - StartupReportConfiguration startupReportConfiguration, ConsoleLogger log ) - { + public ForkStarter( + ProviderConfiguration providerConfiguration, + StartupConfiguration startupConfiguration, + ForkConfiguration forkConfiguration, + int forkedProcessTimeoutInSeconds, + StartupReportConfiguration startupReportConfiguration, + ConsoleLogger log) { this.forkConfiguration = forkConfiguration; this.providerConfiguration = providerConfiguration; this.forkedProcessTimeoutInSeconds = forkedProcessTimeoutInSeconds; this.startupConfiguration = startupConfiguration; this.startupReportConfiguration = startupReportConfiguration; this.log = log; - reportMerger = new DefaultReporterFactory( startupReportConfiguration, log ); + reportMerger = new DefaultReporterFactory(startupReportConfiguration, log); reportMerger.runStarting(); defaultReporterFactories = new ConcurrentLinkedQueue<>(); currentForkClients = new ConcurrentLinkedQueue<>(); @@ -257,466 +242,410 @@ public ForkStarter( ProviderConfiguration providerConfiguration, StartupConfigur triggerTimeoutCheck(); } - public RunResult run( @Nonnull SurefireProperties effectiveSystemProperties, @Nonnull DefaultScanResult scanResult ) - throws SurefireBooterForkException - { - try - { + public RunResult run(@Nonnull SurefireProperties effectiveSystemProperties, @Nonnull DefaultScanResult scanResult) + throws SurefireBooterForkException { + try { Map providerProperties = providerConfiguration.getProviderProperties(); - scanResult.writeTo( providerProperties ); - return isForkOnce() - ? run( effectiveSystemProperties, providerProperties ) - : run( effectiveSystemProperties ); - } - finally - { - reportMerger.mergeFromOtherFactories( defaultReporterFactories ); + scanResult.writeTo(providerProperties); + return isForkOnce() ? run(effectiveSystemProperties, providerProperties) : run(effectiveSystemProperties); + } finally { + reportMerger.mergeFromOtherFactories(defaultReporterFactories); reportMerger.close(); pingThreadScheduler.shutdownNow(); timeoutCheckScheduler.shutdownNow(); - for ( String line : logsAtEnd ) - { - log.warning( line ); + for (String line : logsAtEnd) { + log.warning(line); } } } - public void killOrphanForks() - { - for ( ForkClient fork : currentForkClients ) - { + public void killOrphanForks() { + for (ForkClient fork : currentForkClients) { fork.kill(); } } - private RunResult run( SurefireProperties effectiveSystemProps, Map providerProperties ) - throws SurefireBooterForkException - { + private RunResult run(SurefireProperties effectiveSystemProps, Map providerProperties) + throws SurefireBooterForkException { TestLessInputStreamBuilder builder = new TestLessInputStreamBuilder(); TestLessInputStream stream = builder.build(); - Thread shutdown = createImmediateShutdownHookThread( builder, providerConfiguration.getShutdown() ); - ScheduledFuture ping = triggerPingTimerForShutdown( builder ); + Thread shutdown = createImmediateShutdownHookThread(builder, providerConfiguration.getShutdown()); + ScheduledFuture ping = triggerPingTimerForShutdown(builder); int forkNumber = drawNumber(); - PropertiesWrapper props = new PropertiesWrapper( providerProperties ); - try - { - addShutDownHook( shutdown ); + PropertiesWrapper props = new PropertiesWrapper(providerProperties); + try { + addShutDownHook(shutdown); DefaultReporterFactory forkedReporterFactory = - new DefaultReporterFactory( startupReportConfiguration, log, forkNumber ); - defaultReporterFactories.add( forkedReporterFactory ); - ForkClient forkClient = new ForkClient( forkedReporterFactory, stream, forkNumber ); + new DefaultReporterFactory(startupReportConfiguration, log, forkNumber); + defaultReporterFactories.add(forkedReporterFactory); + ForkClient forkClient = new ForkClient(forkedReporterFactory, stream, forkNumber); ForkNodeFactory node = forkConfiguration.getForkNodeFactory(); return forkConfiguration.getPluginPlatform().isShutdown() - ? new RunResult( 0, 0, 0, 0 ) - : fork( null, props, forkClient, effectiveSystemProps, forkNumber, stream, node, false ); - } - finally - { - returnNumber( forkNumber ); - removeShutdownHook( shutdown ); - ping.cancel( true ); - builder.removeStream( stream ); + ? new RunResult(0, 0, 0, 0) + : fork(null, props, forkClient, effectiveSystemProps, forkNumber, stream, node, false); + } finally { + returnNumber(forkNumber); + removeShutdownHook(shutdown); + ping.cancel(true); + builder.removeStream(stream); } } - private RunResult run( SurefireProperties effectiveSystemProperties ) - throws SurefireBooterForkException - { + private RunResult run(SurefireProperties effectiveSystemProperties) throws SurefireBooterForkException { return forkConfiguration.isReuseForks() - ? runSuitesForkOnceMultiple( effectiveSystemProperties, forkConfiguration.getForkCount() ) - : runSuitesForkPerTestSet( effectiveSystemProperties, forkConfiguration.getForkCount() ); + ? runSuitesForkOnceMultiple(effectiveSystemProperties, forkConfiguration.getForkCount()) + : runSuitesForkPerTestSet(effectiveSystemProperties, forkConfiguration.getForkCount()); } - private boolean isForkOnce() - { - return forkConfiguration.isReuseForks() && ( forkConfiguration.getForkCount() == 1 || hasSuiteXmlFiles() ); + private boolean isForkOnce() { + return forkConfiguration.isReuseForks() && (forkConfiguration.getForkCount() == 1 || hasSuiteXmlFiles()); } - private boolean hasSuiteXmlFiles() - { + private boolean hasSuiteXmlFiles() { TestRequest testSuiteDefinition = providerConfiguration.getTestSuiteDefinition(); - return testSuiteDefinition != null && !testSuiteDefinition.getSuiteXmlFiles().isEmpty(); + return testSuiteDefinition != null + && !testSuiteDefinition.getSuiteXmlFiles().isEmpty(); } - @SuppressWarnings( "checkstyle:magicnumber" ) - private RunResult runSuitesForkOnceMultiple( SurefireProperties effectiveSystemProps, int forkCount ) - throws SurefireBooterForkException - { - ThreadPoolExecutor executor - = new ThreadPoolExecutor( forkCount, forkCount, 60L, SECONDS, new ArrayBlockingQueue<>( forkCount ) ); - executor.setThreadFactory( FORKED_JVM_DAEMON_THREAD_FACTORY ); + @SuppressWarnings("checkstyle:magicnumber") + private RunResult runSuitesForkOnceMultiple(SurefireProperties effectiveSystemProps, int forkCount) + throws SurefireBooterForkException { + ThreadPoolExecutor executor = + new ThreadPoolExecutor(forkCount, forkCount, 60L, SECONDS, new ArrayBlockingQueue<>(forkCount)); + executor.setThreadFactory(FORKED_JVM_DAEMON_THREAD_FACTORY); Queue tests = new ConcurrentLinkedQueue<>(); - for ( Class clazz : getSuitesIterator() ) - { - tests.add( clazz.getName() ); + for (Class clazz : getSuitesIterator()) { + tests.add(clazz.getName()); } Queue forks = new ConcurrentLinkedQueue<>(); - for ( int forkNum = 0, total = min( forkCount, tests.size() ); forkNum < total; forkNum++ ) - { - forks.add( new TestProvidingInputStream( tests ) ); + for (int forkNum = 0, total = min(forkCount, tests.size()); forkNum < total; forkNum++) { + forks.add(new TestProvidingInputStream(tests)); } - Thread shutdown = createShutdownHookThread( forks, providerConfiguration.getShutdown() ); - addShutDownHook( shutdown ); - ScheduledFuture ping = triggerPingTimerForShutdown( forks ); + Thread shutdown = createShutdownHookThread(forks, providerConfiguration.getShutdown()); + addShutDownHook(shutdown); + ScheduledFuture ping = triggerPingTimerForShutdown(forks); - try - { + try { int failFastCount = providerConfiguration.getSkipAfterFailureCount(); - AtomicInteger notifyForksToSkipTestsNow = new AtomicInteger( failFastCount ); - Collection> results = - forks.stream() - .filter( fork -> !forkConfiguration.getPluginPlatform().isShutdown() ) - .map( fork -> (Callable) () -> - { - int forkNumber = drawNumber(); - DefaultReporterFactory reporter = - new DefaultReporterFactory( startupReportConfiguration, log, forkNumber ); - defaultReporterFactories.add( reporter ); - ForkClient client = new ForkClient( reporter, fork, forkNumber ); - client.setStopOnNextTestListener( () -> - runIfZeroCountDown( () -> notifyStreamsToSkipTests( forks ), notifyForksToSkipTestsNow ) ); - Map providerProperties = providerConfiguration.getProviderProperties(); - PropertiesWrapper keyValues = new PropertiesWrapper( providerProperties ); - ForkNodeFactory node = forkConfiguration.getForkNodeFactory(); - try - { - return fork( null, keyValues, client, effectiveSystemProps, forkNumber, fork, node, true ); - } - finally - { - returnNumber( forkNumber ); - } - } ).map( executor::submit ) - .collect( toList() ); + AtomicInteger notifyForksToSkipTestsNow = new AtomicInteger(failFastCount); + Collection> results = forks.stream() + .filter(fork -> !forkConfiguration.getPluginPlatform().isShutdown()) + .map(fork -> (Callable) () -> { + int forkNumber = drawNumber(); + DefaultReporterFactory reporter = + new DefaultReporterFactory(startupReportConfiguration, log, forkNumber); + defaultReporterFactories.add(reporter); + ForkClient client = new ForkClient(reporter, fork, forkNumber); + client.setStopOnNextTestListener(() -> + runIfZeroCountDown(() -> notifyStreamsToSkipTests(forks), notifyForksToSkipTestsNow)); + Map providerProperties = providerConfiguration.getProviderProperties(); + PropertiesWrapper keyValues = new PropertiesWrapper(providerProperties); + ForkNodeFactory node = forkConfiguration.getForkNodeFactory(); + try { + return fork(null, keyValues, client, effectiveSystemProps, forkNumber, fork, node, true); + } finally { + returnNumber(forkNumber); + } + }) + .map(executor::submit) + .collect(toList()); - return awaitResultsDone( results, executor ); - } - finally - { - removeShutdownHook( shutdown ); - ping.cancel( true ); - closeExecutor( executor ); + return awaitResultsDone(results, executor); + } finally { + removeShutdownHook(shutdown); + ping.cancel(true); + closeExecutor(executor); } } - private static void notifyStreamsToSkipTests( Collection notifiableTestStreams ) - { - for ( NotifiableTestStream notifiableTestStream : notifiableTestStreams ) - { + private static void notifyStreamsToSkipTests(Collection notifiableTestStreams) { + for (NotifiableTestStream notifiableTestStream : notifiableTestStreams) { notifiableTestStream.skipSinceNextTest(); } } - @SuppressWarnings( "checkstyle:magicnumber" ) - private RunResult runSuitesForkPerTestSet( SurefireProperties effectiveSystemProps, int forkCount ) - throws SurefireBooterForkException - { + @SuppressWarnings("checkstyle:magicnumber") + private RunResult runSuitesForkPerTestSet(SurefireProperties effectiveSystemProps, int forkCount) + throws SurefireBooterForkException { TestLessInputStreamBuilder builder = new TestLessInputStreamBuilder(); - Thread shutdown = createCachableShutdownHookThread( builder, providerConfiguration.getShutdown() ); + Thread shutdown = createCachableShutdownHookThread(builder, providerConfiguration.getShutdown()); ThreadPoolExecutor executor = - new ThreadPoolExecutor( forkCount, forkCount, 60, SECONDS, new LinkedBlockingQueue<>() ); - executor.setThreadFactory( FORKED_JVM_DAEMON_THREAD_FACTORY ); - ScheduledFuture ping = triggerPingTimerForShutdown( builder ); - try - { - addShutDownHook( shutdown ); + new ThreadPoolExecutor(forkCount, forkCount, 60, SECONDS, new LinkedBlockingQueue<>()); + executor.setThreadFactory(FORKED_JVM_DAEMON_THREAD_FACTORY); + ScheduledFuture ping = triggerPingTimerForShutdown(builder); + try { + addShutDownHook(shutdown); int failFastCount = providerConfiguration.getSkipAfterFailureCount(); - AtomicInteger notifyForksToSkipTestsNow = new AtomicInteger( failFastCount ); - Collection> results = - stream( ( (Iterable) getSuitesIterator() ).spliterator(), false ) - .filter( fork -> !forkConfiguration.getPluginPlatform().isShutdown() ) - .map( testSet -> (Callable) () -> - { - int forkNumber = drawNumber(); - DefaultReporterFactory forkedReporterFactory = - new DefaultReporterFactory( startupReportConfiguration, log, forkNumber ); - defaultReporterFactories.add( forkedReporterFactory ); - TestLessInputStream stream = builder.build(); - ForkClient forkClient = new ForkClient( forkedReporterFactory, stream, forkNumber ); - NotifiableTestStream notifiable = builder.getCachableCommands(); - forkClient.setStopOnNextTestListener( () -> - runIfZeroCountDown( notifiable::skipSinceNextTest, notifyForksToSkipTestsNow ) ); - Map providerProperties = providerConfiguration.getProviderProperties(); - PropertiesWrapper keyValues = new PropertiesWrapper( providerProperties ); - ForkNodeFactory node = forkConfiguration.getForkNodeFactory(); - try - { - return fork( testSet, keyValues, forkClient, effectiveSystemProps, forkNumber, stream, node, - false ); - } - finally - { - returnNumber( forkNumber ); - builder.removeStream( stream ); - } - } ).map( executor::submit ) - .collect( toList() ); + AtomicInteger notifyForksToSkipTestsNow = new AtomicInteger(failFastCount); + Collection> results = stream(((Iterable) getSuitesIterator()).spliterator(), false) + .filter(fork -> !forkConfiguration.getPluginPlatform().isShutdown()) + .map(testSet -> (Callable) () -> { + int forkNumber = drawNumber(); + DefaultReporterFactory forkedReporterFactory = + new DefaultReporterFactory(startupReportConfiguration, log, forkNumber); + defaultReporterFactories.add(forkedReporterFactory); + TestLessInputStream stream = builder.build(); + ForkClient forkClient = new ForkClient(forkedReporterFactory, stream, forkNumber); + NotifiableTestStream notifiable = builder.getCachableCommands(); + forkClient.setStopOnNextTestListener( + () -> runIfZeroCountDown(notifiable::skipSinceNextTest, notifyForksToSkipTestsNow)); + Map providerProperties = providerConfiguration.getProviderProperties(); + PropertiesWrapper keyValues = new PropertiesWrapper(providerProperties); + ForkNodeFactory node = forkConfiguration.getForkNodeFactory(); + try { + return fork( + testSet, + keyValues, + forkClient, + effectiveSystemProps, + forkNumber, + stream, + node, + false); + } finally { + returnNumber(forkNumber); + builder.removeStream(stream); + } + }) + .map(executor::submit) + .collect(toList()); - return awaitResultsDone( results, executor ); - } - finally - { - removeShutdownHook( shutdown ); - ping.cancel( true ); - closeExecutor( executor ); + return awaitResultsDone(results, executor); + } finally { + removeShutdownHook(shutdown); + ping.cancel(true); + closeExecutor(executor); } } - private static RunResult awaitResultsDone( Collection> results, ExecutorService executorService ) - throws SurefireBooterForkException - { - RunResult globalResult = new RunResult( 0, 0, 0, 0 ); + private static RunResult awaitResultsDone(Collection> results, ExecutorService executorService) + throws SurefireBooterForkException { + RunResult globalResult = new RunResult(0, 0, 0, 0); SurefireBooterForkException exception = null; - for ( Future result : results ) - { - try - { + for (Future result : results) { + try { RunResult cur = result.get(); - if ( cur != null ) - { - globalResult = globalResult.aggregate( cur ); - } - else - { - throw new SurefireBooterForkException( "No results for " + result.toString() ); + if (cur != null) { + globalResult = globalResult.aggregate(cur); + } else { + throw new SurefireBooterForkException("No results for " + result.toString()); } - } - catch ( InterruptedException e ) - { + } catch (InterruptedException e) { executorService.shutdownNow(); currentThread().interrupt(); - throw new SurefireBooterForkException( "Interrupted", e ); - } - catch ( ExecutionException e ) - { + throw new SurefireBooterForkException("Interrupted", e); + } catch (ExecutionException e) { Throwable realException = e.getCause(); - if ( realException == null ) - { - if ( exception == null ) - { - exception = new SurefireBooterForkException( EXECUTION_EXCEPTION ); + if (realException == null) { + if (exception == null) { + exception = new SurefireBooterForkException(EXECUTION_EXCEPTION); } - } - else - { + } else { String previousError = ""; - if ( exception != null && !EXECUTION_EXCEPTION.equals( exception.getLocalizedMessage().trim() ) ) - { + if (exception != null + && !EXECUTION_EXCEPTION.equals( + exception.getLocalizedMessage().trim())) { previousError = exception.getLocalizedMessage() + "\n"; } String error = previousError + EXECUTION_EXCEPTION + " " + realException.getLocalizedMessage(); - exception = new SurefireBooterForkException( error, realException ); + exception = new SurefireBooterForkException(error, realException); } } } - if ( exception != null ) - { + if (exception != null) { throw exception; } return globalResult; } - @SuppressWarnings( "checkstyle:magicnumber" ) - private void closeExecutor( ExecutorService executorService ) - throws SurefireBooterForkException - { + @SuppressWarnings("checkstyle:magicnumber") + private void closeExecutor(ExecutorService executorService) throws SurefireBooterForkException { executorService.shutdown(); - try - { + try { // Should stop immediately, as we got all the results if we are here - executorService.awaitTermination( 60 * 60, SECONDS ); - } - catch ( InterruptedException e ) - { + executorService.awaitTermination(60 * 60, SECONDS); + } catch (InterruptedException e) { currentThread().interrupt(); - throw new SurefireBooterForkException( "Interrupted", e ); + throw new SurefireBooterForkException("Interrupted", e); } } - private RunResult fork( Object testSet, PropertiesWrapper providerProperties, ForkClient forkClient, - SurefireProperties effectiveSystemProperties, int forkNumber, - AbstractCommandReader commandReader, ForkNodeFactory forkNodeFactory, - boolean readTestsFromInStream ) - throws SurefireBooterForkException - { - CloseableCloser closer = new CloseableCloser( forkNumber, commandReader ); + private RunResult fork( + Object testSet, + PropertiesWrapper providerProperties, + ForkClient forkClient, + SurefireProperties effectiveSystemProperties, + int forkNumber, + AbstractCommandReader commandReader, + ForkNodeFactory forkNodeFactory, + boolean readTestsFromInStream) + throws SurefireBooterForkException { + CloseableCloser closer = new CloseableCloser(forkNumber, commandReader); final String tempDir; final File surefireProperties; final File systPropsFile; final ForkChannel forkChannel; - File dumpLogDir = replaceForkThreadsInPath( startupReportConfiguration.getReportsDirectory(), forkNumber ); - try - { - ForkNodeArguments forkNodeArguments = new ForkedNodeArg( forkConfiguration.isDebug(), forkNumber, - dumpLogDir, randomUUID().toString() ); - forkChannel = forkNodeFactory.createForkChannel( forkNodeArguments ); - closer.addCloseable( forkChannel ); + File dumpLogDir = replaceForkThreadsInPath(startupReportConfiguration.getReportsDirectory(), forkNumber); + try { + ForkNodeArguments forkNodeArguments = new ForkedNodeArg( + forkConfiguration.isDebug(), + forkNumber, + dumpLogDir, + randomUUID().toString()); + forkChannel = forkNodeFactory.createForkChannel(forkNodeArguments); + closer.addCloseable(forkChannel); tempDir = forkConfiguration.getTempDirectory().getCanonicalPath(); - BooterSerializer booterSerializer = new BooterSerializer( forkConfiguration ); + BooterSerializer booterSerializer = new BooterSerializer(forkConfiguration); Long pluginPid = forkConfiguration.getPluginPlatform().getPluginPid(); - log.debug( "Determined Maven Process ID " + pluginPid ); + log.debug("Determined Maven Process ID " + pluginPid); String connectionString = forkChannel.getForkNodeConnectionString(); - log.debug( "Fork Channel [" + forkNumber + "] connection string '" + connectionString - + "' for the implementation " + forkChannel.getClass() ); - surefireProperties = booterSerializer.serialize( providerProperties, providerConfiguration, - startupConfiguration, testSet, readTestsFromInStream, pluginPid, forkNumber, connectionString ); - - if ( effectiveSystemProperties != null ) - { + log.debug("Fork Channel [" + forkNumber + "] connection string '" + connectionString + + "' for the implementation " + forkChannel.getClass()); + surefireProperties = booterSerializer.serialize( + providerProperties, + providerConfiguration, + startupConfiguration, + testSet, + readTestsFromInStream, + pluginPid, + forkNumber, + connectionString); + + if (effectiveSystemProperties != null) { SurefireProperties filteredProperties = - createCopyAndReplaceForkNumPlaceholder( effectiveSystemProperties, forkNumber ); - - systPropsFile = writePropertiesFile( filteredProperties, forkConfiguration.getTempDirectory(), - "surefire_" + SYSTEM_PROPERTIES_FILE_COUNTER.getAndIncrement(), - forkConfiguration.isDebug() ); - } - else - { + createCopyAndReplaceForkNumPlaceholder(effectiveSystemProperties, forkNumber); + + systPropsFile = writePropertiesFile( + filteredProperties, + forkConfiguration.getTempDirectory(), + "surefire_" + SYSTEM_PROPERTIES_FILE_COUNTER.getAndIncrement(), + forkConfiguration.isDebug()); + } else { systPropsFile = null; } - } - catch ( IOException e ) - { - throw new SurefireBooterForkException( "Error creating properties files for forking", e ); + } catch (IOException e) { + throw new SurefireBooterForkException("Error creating properties files for forking", e); } - Commandline cli = forkConfiguration.createCommandLine( startupConfiguration, forkNumber, dumpLogDir ); + Commandline cli = forkConfiguration.createCommandLine(startupConfiguration, forkNumber, dumpLogDir); - cli.createArg().setValue( tempDir ); - cli.createArg().setValue( DUMP_FILE_PREFIX + forkNumber ); - cli.createArg().setValue( surefireProperties.getName() ); - if ( systPropsFile != null ) - { - cli.createArg().setValue( systPropsFile.getName() ); + cli.createArg().setValue(tempDir); + cli.createArg().setValue(DUMP_FILE_PREFIX + forkNumber); + cli.createArg().setValue(surefireProperties.getName()); + if (systPropsFile != null) { + cli.createArg().setValue(systPropsFile.getName()); } - ThreadedStreamConsumer eventConsumer = new ThreadedStreamConsumer( forkClient ); - closer.addCloseable( eventConsumer ); + ThreadedStreamConsumer eventConsumer = new ThreadedStreamConsumer(forkClient); + closer.addCloseable(eventConsumer); - log.debug( "Forking command line: " + cli ); + log.debug("Forking command line: " + cli); Integer result = null; RunResult runResult = null; SurefireBooterForkException booterForkException = null; Stoppable err = null; DefaultReporterFactory reporter = forkClient.getDefaultReporterFactory(); - currentForkClients.add( forkClient ); + currentForkClients.add(forkClient); CountdownCloseable countdownCloseable = - new CountdownCloseable( eventConsumer, forkChannel.getCountdownCloseablePermits() ); - try ( CommandlineExecutor exec = new CommandlineExecutor( cli, countdownCloseable ) ) - { + new CountdownCloseable(eventConsumer, forkChannel.getCountdownCloseablePermits()); + try (CommandlineExecutor exec = new CommandlineExecutor(cli, countdownCloseable)) { forkChannel.tryConnectToClient(); CommandlineStreams streams = exec.execute(); - closer.addCloseable( streams ); + closer.addCloseable(streams); - err = bindErrorStream( forkNumber, countdownCloseable, streams, forkClient.getConsoleOutputReceiver() ); + err = bindErrorStream(forkNumber, countdownCloseable, streams, forkClient.getConsoleOutputReceiver()); - forkChannel.bindCommandReader( commandReader, streams.getStdInChannel() ); + forkChannel.bindCommandReader(commandReader, streams.getStdInChannel()); - forkChannel.bindEventHandler( eventConsumer, countdownCloseable, streams.getStdOutChannel() ); + forkChannel.bindEventHandler(eventConsumer, countdownCloseable, streams.getStdOutChannel()); - log.debug( "Fork Channel [" + forkNumber + "] connected to the client." ); + log.debug("Fork Channel [" + forkNumber + "] connected to the client."); result = exec.awaitExit(); - if ( forkClient.hadTimeout() ) - { - runResult = timeout( reporter.getGlobalRunStatistics().getRunResult() ); - } - else if ( result != SUCCESS ) - { + if (forkClient.hadTimeout()) { + runResult = timeout(reporter.getGlobalRunStatistics().getRunResult()); + } else if (result != SUCCESS) { booterForkException = - new SurefireBooterForkException( "Error occurred in starting fork, check output in log" ); + new SurefireBooterForkException("Error occurred in starting fork, check output in log"); } - } - catch ( InterruptedException e ) - { - log.error( "Closing the streams after (InterruptedException) '" + e.getLocalizedMessage() + "'" ); + } catch (InterruptedException e) { + log.error("Closing the streams after (InterruptedException) '" + e.getLocalizedMessage() + "'"); // maybe implement it in the Future.cancel() of the extension or similar forkChannel.disable(); - if ( err != null ) - { + if (err != null) { err.disable(); } - } - catch ( Exception e ) - { + } catch (Exception e) { // CommandLineException from pipes and IOException from sockets - runResult = failure( reporter.getGlobalRunStatistics().getRunResult(), e ); + runResult = failure(reporter.getGlobalRunStatistics().getRunResult(), e); String cliErr = e.getLocalizedMessage(); Throwable cause = e.getCause(); booterForkException = - new SurefireBooterForkException( "Error while executing forked tests.", cliErr, cause, runResult ); - } - finally - { - log.debug( "Closing the fork " + forkNumber + " after " - + ( forkClient.isSaidGoodBye() ? "saying GoodBye." : "not saying Good Bye." ) ); - currentForkClients.remove( forkClient ); + new SurefireBooterForkException("Error while executing forked tests.", cliErr, cause, runResult); + } finally { + log.debug("Closing the fork " + forkNumber + " after " + + (forkClient.isSaidGoodBye() ? "saying GoodBye." : "not saying Good Bye.")); + currentForkClients.remove(forkClient); closer.close(); - if ( runResult == null ) - { + if (runResult == null) { runResult = reporter.getGlobalRunStatistics().getRunResult(); } - forkClient.close( runResult.isTimeout() ); + forkClient.close(runResult.isTimeout()); - if ( !runResult.isTimeout() ) - { + if (!runResult.isTimeout()) { Throwable cause = booterForkException == null ? null : booterForkException.getCause(); String detail = booterForkException == null ? "" : "\n" + booterForkException.getMessage(); - if ( forkClient.isErrorInFork() ) - { + if (forkClient.isErrorInFork()) { StackTraceWriter errorInFork = forkClient.getErrorInFork(); - String errorInForkMessage = - errorInFork == null ? null : errorInFork.getThrowable().getLocalizedMessage(); - boolean showStackTrace = providerConfiguration.getMainCliOptions().contains( SHOW_ERRORS ); + String errorInForkMessage = errorInFork == null + ? null + : errorInFork.getThrowable().getLocalizedMessage(); + boolean showStackTrace = + providerConfiguration.getMainCliOptions().contains(SHOW_ERRORS); String stackTrace = errorInForkMessage; - if ( showStackTrace ) - { - if ( errorInFork != null ) - { - if ( stackTrace == null ) - { + if (showStackTrace) { + if (errorInFork != null) { + if (stackTrace == null) { stackTrace = ""; - } - else - { + } else { stackTrace += NL; } stackTrace += errorInFork.writeTrimmedTraceToString(); } } //noinspection ThrowFromFinallyBlock - throw new SurefireBooterForkException( "There was an error in the forked process" - + detail - + ( stackTrace == null ? "" : "\n" + stackTrace ), cause ); + throw new SurefireBooterForkException( + "There was an error in the forked process" + + detail + + (stackTrace == null ? "" : "\n" + stackTrace), + cause); } - if ( !forkClient.isSaidGoodBye() ) - { + if (!forkClient.isSaidGoodBye()) { String errorCode = result == null ? "" : "\nProcess Exit Code: " + result; String testsInProgress = forkClient.hasTestsInProgress() ? "\nCrashed tests:" : ""; - for ( String test : forkClient.testsInProgress() ) - { + for (String test : forkClient.testsInProgress()) { testsInProgress += "\n" + test; } // noinspection ThrowFromFinallyBlock throw new SurefireBooterForkException( - "The forked VM terminated without properly saying goodbye. VM crash or System.exit called?" - + "\nCommand was " + cli.toString() + detail + errorCode + testsInProgress, cause ); + "The forked VM terminated without properly saying goodbye. VM crash or System.exit called?" + + "\nCommand was " + cli.toString() + detail + errorCode + testsInProgress, + cause); } } - if ( booterForkException != null ) - { + if (booterForkException != null) { throw booterForkException; } } @@ -724,144 +653,125 @@ else if ( result != SUCCESS ) return runResult; } - private static Stoppable bindErrorStream( int forkNumber, CountdownCloseable countdownCloseable, - CommandlineStreams streams, Object errorStreamLock ) - { - EventHandler errConsumer = new NativeStdErrStreamConsumer( errorStreamLock ); - LineConsumerThread stdErr = new LineConsumerThread( "fork-" + forkNumber + "-err-thread", - streams.getStdErrChannel(), errConsumer, countdownCloseable ); + private static Stoppable bindErrorStream( + int forkNumber, CountdownCloseable countdownCloseable, CommandlineStreams streams, Object errorStreamLock) { + EventHandler errConsumer = new NativeStdErrStreamConsumer(errorStreamLock); + LineConsumerThread stdErr = new LineConsumerThread( + "fork-" + forkNumber + "-err-thread", streams.getStdErrChannel(), errConsumer, countdownCloseable); stdErr.start(); return stdErr; } - private Iterable> getSuitesIterator() - throws SurefireBooterForkException - { - try - { + private Iterable> getSuitesIterator() throws SurefireBooterForkException { + try { AbstractPathConfiguration classpathConfiguration = startupConfiguration.getClasspathConfiguration(); ClassLoader unifiedClassLoader = classpathConfiguration.createMergedClassLoader(); - CommonReflector commonReflector = new CommonReflector( unifiedClassLoader ); - Object reporterFactory = commonReflector.createReportingReporterFactory( startupReportConfiguration, log ); + CommonReflector commonReflector = new CommonReflector(unifiedClassLoader); + Object reporterFactory = commonReflector.createReportingReporterFactory(startupReportConfiguration, log); - ProviderFactory providerFactory = - new ProviderFactory( startupConfiguration, providerConfiguration, unifiedClassLoader, reporterFactory ); - SurefireProvider surefireProvider = providerFactory.createProvider( false ); + ProviderFactory providerFactory = new ProviderFactory( + startupConfiguration, providerConfiguration, unifiedClassLoader, reporterFactory); + SurefireProvider surefireProvider = providerFactory.createProvider(false); return surefireProvider.getSuites(); - } - catch ( SurefireExecutionException e ) - { - throw new SurefireBooterForkException( "Unable to create classloader to find test suites", e ); + } catch (SurefireExecutionException e) { + throw new SurefireBooterForkException("Unable to create classloader to find test suites", e); } } - private static Thread createImmediateShutdownHookThread( final TestLessInputStreamBuilder builder, - final Shutdown shutdownType ) - { - return SHUTDOWN_HOOK_THREAD_FACTORY.newThread( new Runnable() - { + private static Thread createImmediateShutdownHookThread( + final TestLessInputStreamBuilder builder, final Shutdown shutdownType) { + return SHUTDOWN_HOOK_THREAD_FACTORY.newThread(new Runnable() { @Override - public void run() - { - builder.getImmediateCommands().shutdown( shutdownType ); + public void run() { + builder.getImmediateCommands().shutdown(shutdownType); } - } ); + }); } - private static Thread createCachableShutdownHookThread( final TestLessInputStreamBuilder builder, - final Shutdown shutdownType ) - { - return SHUTDOWN_HOOK_THREAD_FACTORY.newThread( new Runnable() - { + private static Thread createCachableShutdownHookThread( + final TestLessInputStreamBuilder builder, final Shutdown shutdownType) { + return SHUTDOWN_HOOK_THREAD_FACTORY.newThread(new Runnable() { @Override - public void run() - { - builder.getCachableCommands().shutdown( shutdownType ); + public void run() { + builder.getCachableCommands().shutdown(shutdownType); } - } ); + }); } - private static Thread createShutdownHookThread( final Iterable streams, - final Shutdown shutdownType ) - { - return SHUTDOWN_HOOK_THREAD_FACTORY.newThread( new Runnable() - { + private static Thread createShutdownHookThread( + final Iterable streams, final Shutdown shutdownType) { + return SHUTDOWN_HOOK_THREAD_FACTORY.newThread(new Runnable() { @Override - public void run() - { - for ( TestProvidingInputStream stream : streams ) - { - stream.shutdown( shutdownType ); + public void run() { + for (TestProvidingInputStream stream : streams) { + stream.shutdown(shutdownType); } } - } ); + }); } - private static ScheduledExecutorService createPingScheduler() - { - ThreadFactory threadFactory = newDaemonThreadFactory( "ping-timer-" + PING_IN_SECONDS + "s" ); - return newScheduledThreadPool( 1, threadFactory ); + private static ScheduledExecutorService createPingScheduler() { + ThreadFactory threadFactory = newDaemonThreadFactory("ping-timer-" + PING_IN_SECONDS + "s"); + return newScheduledThreadPool(1, threadFactory); } - private static ScheduledExecutorService createTimeoutCheckScheduler() - { - ThreadFactory threadFactory = newDaemonThreadFactory( "timeout-check-timer" ); - return newScheduledThreadPool( 1, threadFactory ); + private static ScheduledExecutorService createTimeoutCheckScheduler() { + ThreadFactory threadFactory = newDaemonThreadFactory("timeout-check-timer"); + return newScheduledThreadPool(1, threadFactory); } - private ScheduledFuture triggerPingTimerForShutdown( final TestLessInputStreamBuilder builder ) - { - return pingThreadScheduler.scheduleWithFixedDelay( new Runnable() - { - @Override - public void run() - { - builder.getImmediateCommands().noop(); - } - }, 0, PING_IN_SECONDS, SECONDS ); + private ScheduledFuture triggerPingTimerForShutdown(final TestLessInputStreamBuilder builder) { + return pingThreadScheduler.scheduleWithFixedDelay( + new Runnable() { + @Override + public void run() { + builder.getImmediateCommands().noop(); + } + }, + 0, + PING_IN_SECONDS, + SECONDS); } - private ScheduledFuture triggerPingTimerForShutdown( final Iterable streams ) - { - return pingThreadScheduler.scheduleWithFixedDelay( new Runnable() - { - @Override - public void run() - { - for ( TestProvidingInputStream stream : streams ) - { - stream.noop(); - } - } - }, 0, PING_IN_SECONDS, SECONDS ); + private ScheduledFuture triggerPingTimerForShutdown(final Iterable streams) { + return pingThreadScheduler.scheduleWithFixedDelay( + new Runnable() { + @Override + public void run() { + for (TestProvidingInputStream stream : streams) { + stream.noop(); + } + } + }, + 0, + PING_IN_SECONDS, + SECONDS); } - private ScheduledFuture triggerTimeoutCheck() - { - return timeoutCheckScheduler.scheduleWithFixedDelay( new Runnable() - { - @Override - public void run() - { - long systemTime = currentTimeMillis(); - for ( ForkClient forkClient : currentForkClients ) - { - forkClient.tryToTimeout( systemTime, forkedProcessTimeoutInSeconds ); - } - } - }, 0, TIMEOUT_CHECK_PERIOD_MILLIS, MILLISECONDS ); + private ScheduledFuture triggerTimeoutCheck() { + return timeoutCheckScheduler.scheduleWithFixedDelay( + new Runnable() { + @Override + public void run() { + long systemTime = currentTimeMillis(); + for (ForkClient forkClient : currentForkClients) { + forkClient.tryToTimeout(systemTime, forkedProcessTimeoutInSeconds); + } + } + }, + 0, + TIMEOUT_CHECK_PERIOD_MILLIS, + MILLISECONDS); } - private final class ForkedNodeArg implements ForkNodeArguments - { + private final class ForkedNodeArg implements ForkNodeArguments { private final int forkChannelId; private final File dumpLogDir; private final String sessionId; private final boolean debug; - ForkedNodeArg( boolean debug, int forkChannelId, File dumpLogDir, String sessionId ) - { + ForkedNodeArg(boolean debug, int forkChannelId, File dumpLogDir, String sessionId) { this.debug = debug; this.forkChannelId = forkChannelId; this.dumpLogDir = dumpLogDir; @@ -870,62 +780,54 @@ private final class ForkedNodeArg implements ForkNodeArguments @Nonnull @Override - public String getSessionId() - { + public String getSessionId() { return sessionId; } @Override - public int getForkChannelId() - { + public int getForkChannelId() { return forkChannelId; } @Override @Nonnull - public File dumpStreamText( @Nonnull String text ) - { - return InPluginProcessDumpSingleton.getSingleton().dumpStreamText( text, dumpLogDir, forkChannelId ); + public File dumpStreamText(@Nonnull String text) { + return InPluginProcessDumpSingleton.getSingleton().dumpStreamText(text, dumpLogDir, forkChannelId); } @Nonnull @Override - public File dumpStreamException( @Nonnull Throwable t ) - { + public File dumpStreamException(@Nonnull Throwable t) { return InPluginProcessDumpSingleton.getSingleton() - .dumpStreamException( t, t.getLocalizedMessage(), dumpLogDir, forkChannelId ); + .dumpStreamException(t, t.getLocalizedMessage(), dumpLogDir, forkChannelId); } @Override - public void logWarningAtEnd( @Nonnull String text ) - { - logsAtEnd.add( text ); + public void logWarningAtEnd(@Nonnull String text) { + logsAtEnd.add(text); } @Nonnull @Override - public ConsoleLogger getConsoleLogger() - { + public ConsoleLogger getConsoleLogger() { return log; } @Nonnull @Override - public Object getConsoleLock() - { + public Object getConsoleLock() { return log; } @Override - public File getEventStreamBinaryFile() - { - return debug ? InPluginProcessDumpSingleton.getSingleton() - .getEventStreamBinaryFile( dumpLogDir, forkChannelId ) : null; + public File getEventStreamBinaryFile() { + return debug + ? InPluginProcessDumpSingleton.getSingleton().getEventStreamBinaryFile(dumpLogDir, forkChannelId) + : null; } @Override - public File getCommandStreamBinaryFile() - { + public File getCommandStreamBinaryFile() { return null; } } diff --git a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/JarManifestForkConfiguration.java b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/JarManifestForkConfiguration.java index 7f82091eae..5e29d1ed31 100644 --- a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/JarManifestForkConfiguration.java +++ b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/JarManifestForkConfiguration.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire.booterclient; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,21 +16,11 @@ * specific language governing permissions and limitations * under the License. */ - -import org.apache.maven.surefire.shared.compress.archivers.zip.Zip64Mode; -import org.apache.maven.surefire.shared.compress.archivers.zip.ZipArchiveEntry; -import org.apache.maven.surefire.shared.compress.archivers.zip.ZipArchiveOutputStream; -import org.apache.maven.plugin.surefire.booterclient.lazytestprovider.Commandline; -import org.apache.maven.plugin.surefire.booterclient.output.InPluginProcessDumpSingleton; -import org.apache.maven.plugin.surefire.log.api.ConsoleLogger; -import org.apache.maven.surefire.api.util.TempFileManager; -import org.apache.maven.surefire.booter.Classpath; -import org.apache.maven.surefire.booter.StartupConfiguration; -import org.apache.maven.surefire.booter.SurefireBooterForkException; -import org.apache.maven.surefire.extensions.ForkNodeFactory; +package org.apache.maven.plugin.surefire.booterclient; import javax.annotation.Nonnull; import javax.annotation.Nullable; + import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; @@ -50,53 +38,77 @@ import java.util.jar.Manifest; import java.util.zip.Deflater; +import org.apache.maven.plugin.surefire.booterclient.lazytestprovider.Commandline; +import org.apache.maven.plugin.surefire.booterclient.output.InPluginProcessDumpSingleton; +import org.apache.maven.plugin.surefire.log.api.ConsoleLogger; +import org.apache.maven.surefire.api.util.TempFileManager; +import org.apache.maven.surefire.booter.Classpath; +import org.apache.maven.surefire.booter.StartupConfiguration; +import org.apache.maven.surefire.booter.SurefireBooterForkException; +import org.apache.maven.surefire.extensions.ForkNodeFactory; +import org.apache.maven.surefire.shared.compress.archivers.zip.Zip64Mode; +import org.apache.maven.surefire.shared.compress.archivers.zip.ZipArchiveEntry; +import org.apache.maven.surefire.shared.compress.archivers.zip.ZipArchiveOutputStream; + import static java.nio.charset.StandardCharsets.UTF_8; import static java.nio.file.Files.isDirectory; import static org.apache.maven.plugin.surefire.SurefireHelper.escapeToPlatformPath; import static org.apache.maven.plugin.surefire.booterclient.JarManifestForkConfiguration.ClasspathElementUri.absolute; import static org.apache.maven.plugin.surefire.booterclient.JarManifestForkConfiguration.ClasspathElementUri.relative; -import static org.apache.maven.surefire.shared.utils.StringUtils.isNotBlank; import static org.apache.maven.surefire.api.util.internal.StringUtils.NL; +import static org.apache.maven.surefire.shared.utils.StringUtils.isNotBlank; /** * @author Tibor Digana (tibor17) * @since 2.21.0.Jigsaw */ -public final class JarManifestForkConfiguration - extends AbstractClasspathForkConfiguration -{ - @SuppressWarnings( "checkstyle:parameternumber" ) - public JarManifestForkConfiguration( @Nonnull Classpath bootClasspath, @Nonnull File tempDirectory, - @Nullable String debugLine, @Nonnull File workingDirectory, - @Nonnull Properties modelProperties, @Nullable String argLine, - @Nonnull Map environmentVariables, - @Nonnull String[] excludedEnvironmentVariables, - boolean debug, - int forkCount, boolean reuseForks, @Nonnull Platform pluginPlatform, - @Nonnull ConsoleLogger log, - @Nonnull ForkNodeFactory forkNodeFactory ) - { - super( bootClasspath, tempDirectory, debugLine, workingDirectory, modelProperties, argLine, - environmentVariables, excludedEnvironmentVariables, debug, forkCount, reuseForks, pluginPlatform, log, - forkNodeFactory ); +public final class JarManifestForkConfiguration extends AbstractClasspathForkConfiguration { + @SuppressWarnings("checkstyle:parameternumber") + public JarManifestForkConfiguration( + @Nonnull Classpath bootClasspath, + @Nonnull File tempDirectory, + @Nullable String debugLine, + @Nonnull File workingDirectory, + @Nonnull Properties modelProperties, + @Nullable String argLine, + @Nonnull Map environmentVariables, + @Nonnull String[] excludedEnvironmentVariables, + boolean debug, + int forkCount, + boolean reuseForks, + @Nonnull Platform pluginPlatform, + @Nonnull ConsoleLogger log, + @Nonnull ForkNodeFactory forkNodeFactory) { + super( + bootClasspath, + tempDirectory, + debugLine, + workingDirectory, + modelProperties, + argLine, + environmentVariables, + excludedEnvironmentVariables, + debug, + forkCount, + reuseForks, + pluginPlatform, + log, + forkNodeFactory); } @Override - protected void resolveClasspath( @Nonnull Commandline cli, - @Nonnull String booterThatHasMainMethod, - @Nonnull StartupConfiguration config, - @Nonnull File dumpLogDirectory ) - throws SurefireBooterForkException - { - try - { - File jar = createJar( toCompleteClasspath( config ), booterThatHasMainMethod, dumpLogDirectory ); - cli.createArg().setValue( "-jar" ); - cli.createArg().setValue( escapeToPlatformPath( jar.getAbsolutePath() ) ); - } - catch ( IOException e ) - { - throw new SurefireBooterForkException( "Error creating archive file", e ); + protected void resolveClasspath( + @Nonnull Commandline cli, + @Nonnull String booterThatHasMainMethod, + @Nonnull StartupConfiguration config, + @Nonnull File dumpLogDirectory) + throws SurefireBooterForkException { + try { + File jar = createJar(toCompleteClasspath(config), booterThatHasMainMethod, dumpLogDirectory); + cli.createArg().setValue("-jar"); + cli.createArg().setValue(escapeToPlatformPath(jar.getAbsolutePath())); + } catch (IOException e) { + throw new SurefireBooterForkException("Error creating archive file", e); } } @@ -110,25 +122,22 @@ protected void resolveClasspath( @Nonnull Commandline cli, * @throws IOException When a file operation fails. */ @Nonnull - private File createJar( @Nonnull List classPath, @Nonnull String startClassName, - @Nonnull File dumpLogDirectory ) - throws IOException - { - File file = TempFileManager.instance( getTempDirectory() ).createTempFile( "surefirebooter", ".jar" ); - if ( !isDebug() ) - { + private File createJar( + @Nonnull List classPath, @Nonnull String startClassName, @Nonnull File dumpLogDirectory) + throws IOException { + File file = TempFileManager.instance(getTempDirectory()).createTempFile("surefirebooter", ".jar"); + if (!isDebug()) { file.deleteOnExit(); } Path parent = file.getParentFile().toPath(); - OutputStream fos = new BufferedOutputStream( new FileOutputStream( file ), 64 * 1024 ); + OutputStream fos = new BufferedOutputStream(new FileOutputStream(file), 64 * 1024); - try ( ZipArchiveOutputStream zos = new ZipArchiveOutputStream( fos ) ) - { - zos.setUseZip64( Zip64Mode.Never ); - zos.setLevel( Deflater.NO_COMPRESSION ); + try (ZipArchiveOutputStream zos = new ZipArchiveOutputStream(fos)) { + zos.setUseZip64(Zip64Mode.Never); + zos.setLevel(Deflater.NO_COMPRESSION); - ZipArchiveEntry ze = new ZipArchiveEntry( "META-INF/MANIFEST.MF" ); - zos.putArchiveEntry( ze ); + ZipArchiveEntry ze = new ZipArchiveEntry("META-INF/MANIFEST.MF"); + zos.putArchiveEntry(ze); Manifest man = new Manifest(); @@ -137,30 +146,27 @@ private File createJar( @Nonnull List classPath, @Nonnull String startCl // we can't use StringUtils.join here since we need to add a '/' to // the end of directory entries - otherwise the jvm will ignore them. StringBuilder cp = new StringBuilder(); - for ( Iterator it = classPath.iterator(); it.hasNext(); ) - { - Path classPathElement = Paths.get( it.next() ); + for (Iterator it = classPath.iterator(); it.hasNext(); ) { + Path classPathElement = Paths.get(it.next()); ClasspathElementUri classpathElementUri = - toClasspathElementUri( parent, classPathElement, dumpLogDirectory, dumpError ); + toClasspathElementUri(parent, classPathElement, dumpLogDirectory, dumpError); // too many errors in dump file with the same root cause may slow down the Boot Manifest-JAR startup dumpError &= !classpathElementUri.absolute; - cp.append( classpathElementUri.uri ); - if ( isDirectory( classPathElement ) && !classpathElementUri.uri.endsWith( "/" ) ) - { - cp.append( '/' ); + cp.append(classpathElementUri.uri); + if (isDirectory(classPathElement) && !classpathElementUri.uri.endsWith("/")) { + cp.append('/'); } - if ( it.hasNext() ) - { - cp.append( ' ' ); + if (it.hasNext()) { + cp.append(' '); } } - man.getMainAttributes().putValue( "Manifest-Version", "1.0" ); - man.getMainAttributes().putValue( "Class-Path", cp.toString().trim() ); - man.getMainAttributes().putValue( "Main-Class", startClassName ); + man.getMainAttributes().putValue("Manifest-Version", "1.0"); + man.getMainAttributes().putValue("Class-Path", cp.toString().trim()); + man.getMainAttributes().putValue("Main-Class", startClassName); - man.write( zos ); + man.write(zos); zos.closeArchiveEntry(); @@ -168,89 +174,67 @@ private File createJar( @Nonnull List classPath, @Nonnull String startCl } } - static String relativize( @Nonnull Path parent, @Nonnull Path child ) - throws IllegalArgumentException - { - return parent.relativize( child ) - .toString(); + static String relativize(@Nonnull Path parent, @Nonnull Path child) throws IllegalArgumentException { + return parent.relativize(child).toString(); } - static String toAbsoluteUri( @Nonnull Path absolutePath ) - { - return absolutePath.toUri() - .toASCIIString(); + static String toAbsoluteUri(@Nonnull Path absolutePath) { + return absolutePath.toUri().toASCIIString(); } - static ClasspathElementUri toClasspathElementUri( @Nonnull Path parent, - @Nonnull Path classPathElement, - @Nonnull File dumpLogDirectory, - boolean dumpError ) - { - try - { - String relativePath = relativize( parent, classPathElement ); - return relative( escapeUri( relativePath, UTF_8 ) ); - } - catch ( IllegalArgumentException e ) - { - if ( dumpError ) - { + static ClasspathElementUri toClasspathElementUri( + @Nonnull Path parent, @Nonnull Path classPathElement, @Nonnull File dumpLogDirectory, boolean dumpError) { + try { + String relativePath = relativize(parent, classPathElement); + return relative(escapeUri(relativePath, UTF_8)); + } catch (IllegalArgumentException e) { + if (dumpError) { String error = "Boot Manifest-JAR contains absolute paths in classpath '" + classPathElement + "'" + NL + "Hint: -Djdk.net.URLClassPath.disableClassPathURLCheck=true"; - if ( isNotBlank( e.getLocalizedMessage() ) ) - { + if (isNotBlank(e.getLocalizedMessage())) { error += NL; error += e.getLocalizedMessage(); } - InPluginProcessDumpSingleton.getSingleton() - .dumpStreamText( error, dumpLogDirectory ); + InPluginProcessDumpSingleton.getSingleton().dumpStreamText(error, dumpLogDirectory); } - return absolute( toAbsoluteUri( classPathElement ) ); + return absolute(toAbsoluteUri(classPathElement)); } } - static final class ClasspathElementUri - { + static final class ClasspathElementUri { final String uri; final boolean absolute; - private ClasspathElementUri( String uri, boolean absolute ) - { + private ClasspathElementUri(String uri, boolean absolute) { this.uri = uri; this.absolute = absolute; } - static ClasspathElementUri absolute( String uri ) - { - return new ClasspathElementUri( uri, true ); + static ClasspathElementUri absolute(String uri) { + return new ClasspathElementUri(uri, true); } - static ClasspathElementUri relative( String uri ) - { - return new ClasspathElementUri( uri, false ); + static ClasspathElementUri relative(String uri) { + return new ClasspathElementUri(uri, false); } } - static String escapeUri( String input, Charset encoding ) - { - try - { - String uriFormEncoded = URLEncoder.encode( input, encoding.name() ); + static String escapeUri(String input, Charset encoding) { + try { + String uriFormEncoded = URLEncoder.encode(input, encoding.name()); - String uriPathEncoded = uriFormEncoded.replaceAll( "\\+", "%20" ); - uriPathEncoded = uriPathEncoded.replaceAll( "%2F|%5C", "/" ); + String uriPathEncoded = uriFormEncoded.replaceAll("\\+", "%20"); + uriPathEncoded = uriPathEncoded.replaceAll("%2F|%5C", "/"); return uriPathEncoded; - } - catch ( UnsupportedEncodingException e ) - { - throw new IllegalStateException( "avoided by using Charset" ); + } catch (UnsupportedEncodingException e) { + throw new IllegalStateException("avoided by using Charset"); } } } diff --git a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/ModularClasspathForkConfiguration.java b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/ModularClasspathForkConfiguration.java index 86c351b638..7473349208 100644 --- a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/ModularClasspathForkConfiguration.java +++ b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/ModularClasspathForkConfiguration.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire.booterclient; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,22 +16,12 @@ * specific language governing permissions and limitations * under the License. */ - -import org.apache.maven.plugin.surefire.booterclient.lazytestprovider.Commandline; -import org.apache.maven.plugin.surefire.booterclient.output.InPluginProcessDumpSingleton; -import org.apache.maven.plugin.surefire.log.api.ConsoleLogger; -import org.apache.maven.surefire.api.util.TempFileManager; -import org.apache.maven.surefire.booter.AbstractPathConfiguration; -import org.apache.maven.surefire.booter.Classpath; -import org.apache.maven.surefire.booter.ModularClasspath; -import org.apache.maven.surefire.booter.ModularClasspathConfiguration; -import org.apache.maven.surefire.booter.StartupConfiguration; -import org.apache.maven.surefire.booter.SurefireBooterForkException; -import org.apache.maven.surefire.extensions.ForkNodeFactory; +package org.apache.maven.plugin.surefire.booterclient; import javax.annotation.Nonnegative; import javax.annotation.Nonnull; import javax.annotation.Nullable; + import java.io.File; import java.io.FileWriter; import java.io.IOException; @@ -43,6 +31,18 @@ import java.util.Map; import java.util.Properties; +import org.apache.maven.plugin.surefire.booterclient.lazytestprovider.Commandline; +import org.apache.maven.plugin.surefire.booterclient.output.InPluginProcessDumpSingleton; +import org.apache.maven.plugin.surefire.log.api.ConsoleLogger; +import org.apache.maven.surefire.api.util.TempFileManager; +import org.apache.maven.surefire.booter.AbstractPathConfiguration; +import org.apache.maven.surefire.booter.Classpath; +import org.apache.maven.surefire.booter.ModularClasspath; +import org.apache.maven.surefire.booter.ModularClasspathConfiguration; +import org.apache.maven.surefire.booter.StartupConfiguration; +import org.apache.maven.surefire.booter.SurefireBooterForkException; +import org.apache.maven.surefire.extensions.ForkNodeFactory; + import static java.io.File.pathSeparatorChar; import static org.apache.maven.plugin.surefire.SurefireHelper.escapeToPlatformPath; import static org.apache.maven.surefire.api.util.internal.StringUtils.NL; @@ -52,41 +52,52 @@ * @author Tibor Digana (tibor17) * @since 2.21.0.Jigsaw */ -public class ModularClasspathForkConfiguration - extends DefaultForkConfiguration -{ - @SuppressWarnings( "checkstyle:parameternumber" ) - public ModularClasspathForkConfiguration( @Nonnull Classpath bootClasspath, - @Nonnull File tempDirectory, - @Nullable String debugLine, - @Nonnull File workingDirectory, - @Nonnull Properties modelProperties, - @Nullable String argLine, - @Nonnull Map environmentVariables, - @Nonnull String[] excludedEnvironmentVariables, - boolean debug, - @Nonnegative int forkCount, - boolean reuseForks, - @Nonnull Platform pluginPlatform, - @Nonnull ConsoleLogger log, - @Nonnull ForkNodeFactory forkNodeFactory ) - { - super( bootClasspath, tempDirectory, debugLine, workingDirectory, modelProperties, argLine, - environmentVariables, excludedEnvironmentVariables, debug, forkCount, reuseForks, pluginPlatform, log, - forkNodeFactory ); +public class ModularClasspathForkConfiguration extends DefaultForkConfiguration { + @SuppressWarnings("checkstyle:parameternumber") + public ModularClasspathForkConfiguration( + @Nonnull Classpath bootClasspath, + @Nonnull File tempDirectory, + @Nullable String debugLine, + @Nonnull File workingDirectory, + @Nonnull Properties modelProperties, + @Nullable String argLine, + @Nonnull Map environmentVariables, + @Nonnull String[] excludedEnvironmentVariables, + boolean debug, + @Nonnegative int forkCount, + boolean reuseForks, + @Nonnull Platform pluginPlatform, + @Nonnull ConsoleLogger log, + @Nonnull ForkNodeFactory forkNodeFactory) { + super( + bootClasspath, + tempDirectory, + debugLine, + workingDirectory, + modelProperties, + argLine, + environmentVariables, + excludedEnvironmentVariables, + debug, + forkCount, + reuseForks, + pluginPlatform, + log, + forkNodeFactory); } @Override - protected void resolveClasspath( @Nonnull Commandline cli, @Nonnull String startClass, - @Nonnull StartupConfiguration config, @Nonnull File dumpLogDirectory ) - throws SurefireBooterForkException - { - try - { + protected void resolveClasspath( + @Nonnull Commandline cli, + @Nonnull String startClass, + @Nonnull StartupConfiguration config, + @Nonnull File dumpLogDirectory) + throws SurefireBooterForkException { + try { AbstractPathConfiguration pathConfig = config.getClasspathConfiguration(); ModularClasspathConfiguration modularClasspathConfiguration = - pathConfig.toRealPath( ModularClasspathConfiguration.class ); + pathConfig.toRealPath(ModularClasspathConfiguration.class); ModularClasspath modularClasspath = modularClasspathConfiguration.getModularClasspath(); @@ -95,143 +106,121 @@ protected void resolveClasspath( @Nonnull Commandline cli, @Nonnull String start List modulePath = modularClasspath.getModulePath(); Collection packages = modularClasspath.getPackages(); File patchFile = modularClasspath.getPatchFile(); - List classpath = toCompleteClasspath( config ); - - File argsFile = createArgsFile( moduleName, modulePath, classpath, packages, patchFile, startClass, - isMainDescriptor, config.getJpmsArguments() ); - - cli.createArg().setValue( "@" + escapeToPlatformPath( argsFile.getAbsolutePath() ) ); - } - catch ( IOException e ) - { + List classpath = toCompleteClasspath(config); + + File argsFile = createArgsFile( + moduleName, + modulePath, + classpath, + packages, + patchFile, + startClass, + isMainDescriptor, + config.getJpmsArguments()); + + cli.createArg().setValue("@" + escapeToPlatformPath(argsFile.getAbsolutePath())); + } catch (IOException e) { String error = "Error creating args file"; - InPluginProcessDumpSingleton.getSingleton() - .dumpException( e, error, dumpLogDirectory ); - throw new SurefireBooterForkException( error, e ); + InPluginProcessDumpSingleton.getSingleton().dumpException(e, error, dumpLogDirectory); + throw new SurefireBooterForkException(error, e); } } @Nonnull - File createArgsFile( @Nonnull String moduleName, @Nonnull List modulePath, - @Nonnull List classPath, @Nonnull Collection packages, - File patchFile, @Nonnull String startClassName, boolean isMainDescriptor, - @Nonnull List providerJpmsArguments ) - throws IOException - { - File surefireArgs = TempFileManager.instance( getTempDirectory() ).createTempFile( "surefireargs", "" ); - if ( isDebug() ) - { - getLogger().debug( "Path to args file: " + surefireArgs.getCanonicalPath() ); - } - else - { + File createArgsFile( + @Nonnull String moduleName, + @Nonnull List modulePath, + @Nonnull List classPath, + @Nonnull Collection packages, + File patchFile, + @Nonnull String startClassName, + boolean isMainDescriptor, + @Nonnull List providerJpmsArguments) + throws IOException { + File surefireArgs = TempFileManager.instance(getTempDirectory()).createTempFile("surefireargs", ""); + if (isDebug()) { + getLogger().debug("Path to args file: " + surefireArgs.getCanonicalPath()); + } else { surefireArgs.deleteOnExit(); } - try ( FileWriter io = new FileWriter( surefireArgs ) ) - { - StringBuilder args = new StringBuilder( 64 * 1024 ); - if ( !modulePath.isEmpty() ) - { + try (FileWriter io = new FileWriter(surefireArgs)) { + StringBuilder args = new StringBuilder(64 * 1024); + if (!modulePath.isEmpty()) { // https://docs.oracle.com/en/java/javase/11/tools/java.html#GUID-4856361B-8BFD-4964-AE84-121F5F6CF111 - args.append( "--module-path" ) - .append( NL ) - .append( '"' ); - - for ( Iterator it = modulePath.iterator(); it.hasNext(); ) - { - args.append( replace( it.next(), "\\", "\\\\" ) ); - if ( it.hasNext() ) - { - args.append( pathSeparatorChar ); + args.append("--module-path").append(NL).append('"'); + + for (Iterator it = modulePath.iterator(); it.hasNext(); ) { + args.append(replace(it.next(), "\\", "\\\\")); + if (it.hasNext()) { + args.append(pathSeparatorChar); } } - args.append( '"' ) - .append( NL ); + args.append('"').append(NL); } - if ( !classPath.isEmpty() ) - { - args.append( "--class-path" ) - .append( NL ) - .append( '"' ); - - for ( Iterator it = classPath.iterator(); it.hasNext(); ) - { - args.append( replace( it.next(), "\\", "\\\\" ) ); - if ( it.hasNext() ) - { - args.append( pathSeparatorChar ); + if (!classPath.isEmpty()) { + args.append("--class-path").append(NL).append('"'); + + for (Iterator it = classPath.iterator(); it.hasNext(); ) { + args.append(replace(it.next(), "\\", "\\\\")); + if (it.hasNext()) { + args.append(pathSeparatorChar); } } - args.append( '"' ) - .append( NL ); + args.append('"').append(NL); } - if ( isMainDescriptor ) - { - args.append( "--patch-module" ) - .append( NL ) - .append( moduleName ) - .append( '=' ) - .append( '"' ) - .append( replace( patchFile.getPath(), "\\", "\\\\" ) ) - .append( '"' ) - .append( NL ); - - for ( String pkg : packages ) - { - args.append( "--add-opens" ) - .append( NL ) - .append( moduleName ) - .append( '/' ) - .append( pkg ) - .append( '=' ) - .append( "ALL-UNNAMED" ) - .append( NL ); + if (isMainDescriptor) { + args.append("--patch-module") + .append(NL) + .append(moduleName) + .append('=') + .append('"') + .append(replace(patchFile.getPath(), "\\", "\\\\")) + .append('"') + .append(NL); + + for (String pkg : packages) { + args.append("--add-opens") + .append(NL) + .append(moduleName) + .append('/') + .append(pkg) + .append('=') + .append("ALL-UNNAMED") + .append(NL); } - args.append( "--add-modules" ) - .append( NL ) - .append( moduleName ) - .append( NL ); - - args.append( "--add-reads" ) - .append( NL ) - .append( moduleName ) - .append( '=' ) - .append( "ALL-UNNAMED" ) - .append( NL ); - } - else - { - args.append( "--add-modules" ) - .append( NL ) - .append( moduleName ) - .append( NL ); + args.append("--add-modules").append(NL).append(moduleName).append(NL); + + args.append("--add-reads") + .append(NL) + .append(moduleName) + .append('=') + .append("ALL-UNNAMED") + .append(NL); + } else { + args.append("--add-modules").append(NL).append(moduleName).append(NL); } - for ( String[] entries : providerJpmsArguments ) - { - for ( String entry : entries ) - { - args.append( entry ) - .append( NL ); + for (String[] entries : providerJpmsArguments) { + for (String entry : entries) { + args.append(entry).append(NL); } } - args.append( startClassName ); + args.append(startClassName); String argsFileContent = args.toString(); - if ( isDebug() ) - { - getLogger().debug( "args file content:" + NL + argsFileContent ); + if (isDebug()) { + getLogger().debug("args file content:" + NL + argsFileContent); } - io.write( argsFileContent ); + io.write(argsFileContent); return surefireArgs; } diff --git a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/Platform.java b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/Platform.java index 852b274142..12d19c5e89 100644 --- a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/Platform.java +++ b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/Platform.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire.booterclient; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,14 +16,15 @@ * specific language governing permissions and limitations * under the License. */ - -import org.apache.maven.plugin.surefire.JdkAttributes; -import org.apache.maven.surefire.booter.SystemUtils; +package org.apache.maven.plugin.surefire.booterclient; import java.util.concurrent.Callable; import java.util.concurrent.FutureTask; import java.util.concurrent.RunnableFuture; +import org.apache.maven.plugin.surefire.JdkAttributes; +import org.apache.maven.surefire.booter.SystemUtils; + import static org.apache.maven.surefire.api.util.internal.DaemonThreadFactory.newDaemonThread; /** @@ -34,71 +33,56 @@ * @author Tibor Digana (tibor17) * @since 2.20.1 */ -public final class Platform -{ +public final class Platform { private final RunnableFuture pluginPidJob; private final JdkAttributes jdk; private volatile boolean shutdown; - public Platform() - { + public Platform() { // the job may take 50 or 80 ms - this( new FutureTask<>( pidJob() ), null ); - newDaemonThread( pluginPidJob ).start(); + this(new FutureTask<>(pidJob()), null); + newDaemonThread(pluginPidJob).start(); } - private Platform( RunnableFuture pluginPidJob, JdkAttributes jdk ) - { + private Platform(RunnableFuture pluginPidJob, JdkAttributes jdk) { this.pluginPidJob = pluginPidJob; this.jdk = jdk; } - public boolean isShutdown() - { + public boolean isShutdown() { return shutdown; } - public void setShutdownState() - { + public void setShutdownState() { this.shutdown = true; } - public void clearShutdownState() - { + public void clearShutdownState() { this.shutdown = false; } - public Long getPluginPid() - { - try - { + public Long getPluginPid() { + try { return pluginPidJob.get(); - } - catch ( Exception e ) - { + } catch (Exception e) { return null; } } - public JdkAttributes getJdkExecAttributesForTests() - { + public JdkAttributes getJdkExecAttributesForTests() { return jdk; } - public Platform withJdkExecAttributesForTests( JdkAttributes jdk ) - { - return new Platform( pluginPidJob, jdk ); + public Platform withJdkExecAttributesForTests(JdkAttributes jdk) { + return new Platform(pluginPidJob, jdk); } - private static Callable pidJob() - { - return new Callable() - { + private static Callable pidJob() { + return new Callable() { @Override - public Long call() throws Exception - { + public Long call() throws Exception { return SystemUtils.pid(); } }; diff --git a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/lazytestprovider/AbstractCommandReader.java b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/lazytestprovider/AbstractCommandReader.java index fbf487bcd2..3293a69a6f 100644 --- a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/lazytestprovider/AbstractCommandReader.java +++ b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/lazytestprovider/AbstractCommandReader.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire.booterclient.lazytestprovider; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,11 +16,12 @@ * specific language governing permissions and limitations * under the License. */ - -import org.apache.maven.surefire.extensions.CommandReader; +package org.apache.maven.plugin.surefire.booterclient.lazytestprovider; import java.io.Closeable; +import org.apache.maven.surefire.extensions.CommandReader; + /** * Stream reader returns bytes which are finally sent to the forked jvm std-input-stream. * Physical implementation of command sender:
@@ -31,7 +30,4 @@ * @author Tibor Digana (tibor17) * @since 2.19 */ -public abstract class AbstractCommandReader - implements CommandReader, NotifiableTestStream, Closeable -{ -} +public abstract class AbstractCommandReader implements CommandReader, NotifiableTestStream, Closeable {} diff --git a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/lazytestprovider/Commandline.java b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/lazytestprovider/Commandline.java index bbc14bfe8d..651e80ca3f 100644 --- a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/lazytestprovider/Commandline.java +++ b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/lazytestprovider/Commandline.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire.booterclient.lazytestprovider; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.surefire.booterclient.lazytestprovider; import java.util.Collection; import java.util.HashSet; @@ -34,44 +33,36 @@ * * @author Andreas Gudian */ -public class Commandline - extends org.apache.maven.surefire.shared.utils.cli.Commandline -{ +public class Commandline extends org.apache.maven.surefire.shared.utils.cli.Commandline { private final Collection excludedEnvironmentVariables; private final Set addedEnvironmentVariables; /** * for testing purposes only */ - public Commandline() - { - this( new String[0] ); + public Commandline() { + this(new String[0]); } - public Commandline( String[] excludedEnvironmentVariables ) - { + public Commandline(String[] excludedEnvironmentVariables) { this.excludedEnvironmentVariables = new ConcurrentLinkedDeque<>(); addedEnvironmentVariables = new HashSet<>(); - addAll( this.excludedEnvironmentVariables, excludedEnvironmentVariables ); + addAll(this.excludedEnvironmentVariables, excludedEnvironmentVariables); } @Override - public void addEnvironment( String name, String value ) - { - super.addEnvironment( name, value ); - addedEnvironmentVariables.add( name ); + public void addEnvironment(String name, String value) { + super.addEnvironment(name, value); + addedEnvironmentVariables.add(name); } @Override - public final void addSystemEnvironment() - { + public final void addSystemEnvironment() { Properties systemEnvVars = CommandLineUtils.getSystemEnvVars(); - for ( String key : systemEnvVars.stringPropertyNames() ) - { - if ( !addedEnvironmentVariables.contains( key ) && !excludedEnvironmentVariables.contains( key ) ) - { - addEnvironment( key, systemEnvVars.getProperty( key ) ); + for (String key : systemEnvVars.stringPropertyNames()) { + if (!addedEnvironmentVariables.contains(key) && !excludedEnvironmentVariables.contains(key)) { + addEnvironment(key, systemEnvVars.getProperty(key)); } } } diff --git a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/lazytestprovider/DefaultCommandReader.java b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/lazytestprovider/DefaultCommandReader.java index 60dbd0129f..42e3391bf0 100644 --- a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/lazytestprovider/DefaultCommandReader.java +++ b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/lazytestprovider/DefaultCommandReader.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire.booterclient.lazytestprovider; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,11 +16,12 @@ * specific language governing permissions and limitations * under the License. */ - -import org.apache.maven.surefire.api.booter.Command; +package org.apache.maven.plugin.surefire.booterclient.lazytestprovider; import java.io.IOException; +import org.apache.maven.surefire.api.booter.Command; + /** * Reader stream sends commands to forked jvm std-{@link java.io.InputStream input-stream}. * @@ -30,15 +29,12 @@ * @since 2.19 * @see Command */ -public abstract class DefaultCommandReader - extends AbstractCommandReader -{ +public abstract class DefaultCommandReader extends AbstractCommandReader { /** * Opposite to {@link #isClosed()}. * @return {@code true} if not closed */ - protected boolean canContinue() - { + protected boolean canContinue() { return !isClosed(); } @@ -48,10 +44,7 @@ protected boolean canContinue() * * @throws IOException stream error while waiting for notification regarding next test required by forked jvm */ - protected void beforeNextCommand() - throws IOException - { - } + protected void beforeNextCommand() throws IOException {} protected abstract Command nextCommand(); @@ -62,24 +55,19 @@ protected void beforeNextCommand() * @throws IOException {@inheritDoc} */ @Override - public Command readNextCommand() - throws IOException - { - if ( isClosed() ) - { + public Command readNextCommand() throws IOException { + if (isClosed()) { return null; } - if ( !canContinue() ) - { + if (!canContinue()) { close(); return null; } beforeNextCommand(); - if ( isClosed() ) - { + if (isClosed()) { return null; } diff --git a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/lazytestprovider/NotifiableTestStream.java b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/lazytestprovider/NotifiableTestStream.java index b23c532527..d12f3eddf9 100644 --- a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/lazytestprovider/NotifiableTestStream.java +++ b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/lazytestprovider/NotifiableTestStream.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire.booterclient.lazytestprovider; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.surefire.booterclient.lazytestprovider; import org.apache.maven.surefire.api.booter.Shutdown; @@ -34,8 +33,7 @@ * @see TestProvidingInputStream * @see TestLessInputStream */ -public interface NotifiableTestStream -{ +public interface NotifiableTestStream { /** * Forked jvm notifies master process to provide a new test. *
@@ -50,7 +48,7 @@ public interface NotifiableTestStream */ void skipSinceNextTest(); - void shutdown( Shutdown shutdownType ); + void shutdown(Shutdown shutdownType); void noop(); diff --git a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/lazytestprovider/TestLessInputStream.java b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/lazytestprovider/TestLessInputStream.java index 6c49a50c58..7b9aa3a0e4 100644 --- a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/lazytestprovider/TestLessInputStream.java +++ b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/lazytestprovider/TestLessInputStream.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire.booterclient.lazytestprovider; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,9 +16,7 @@ * specific language governing permissions and limitations * under the License. */ - -import org.apache.maven.surefire.api.booter.Command; -import org.apache.maven.surefire.api.booter.Shutdown; +package org.apache.maven.plugin.surefire.booterclient.lazytestprovider; import java.io.IOException; import java.util.Iterator; @@ -33,6 +29,9 @@ import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantReadWriteLock; +import org.apache.maven.surefire.api.booter.Command; +import org.apache.maven.surefire.api.booter.Shutdown; + import static org.apache.maven.surefire.api.booter.Command.BYE_ACK; import static org.apache.maven.surefire.api.booter.Command.NOOP; import static org.apache.maven.surefire.api.booter.Command.SKIP_SINCE_NEXT_TEST; @@ -44,10 +43,8 @@ * @author Tibor Digana (tibor17) * @since 2.19 */ -public final class TestLessInputStream - extends DefaultCommandReader -{ - private final Semaphore barrier = new Semaphore( 0 ); +public final class TestLessInputStream extends DefaultCommandReader { + private final Semaphore barrier = new Semaphore(0); private final AtomicBoolean closed = new AtomicBoolean(); @@ -57,70 +54,55 @@ public final class TestLessInputStream private Iterator cachableCommands; - private TestLessInputStream( TestLessInputStreamBuilder builder ) - { + private TestLessInputStream(TestLessInputStreamBuilder builder) { this.builder = builder; } @Override - public void provideNewTest() - { - } + public void provideNewTest() {} @Override - public void skipSinceNextTest() - { - if ( canContinue() ) - { - immediateCommands.add( SKIP_SINCE_NEXT_TEST ); + public void skipSinceNextTest() { + if (canContinue()) { + immediateCommands.add(SKIP_SINCE_NEXT_TEST); barrier.release(); } } @Override - public void shutdown( Shutdown shutdownType ) - { - if ( canContinue() ) - { - immediateCommands.add( toShutdown( shutdownType ) ); + public void shutdown(Shutdown shutdownType) { + if (canContinue()) { + immediateCommands.add(toShutdown(shutdownType)); barrier.release(); } } @Override - public void noop() - { - if ( canContinue() ) - { - immediateCommands.add( NOOP ); + public void noop() { + if (canContinue()) { + immediateCommands.add(NOOP); barrier.release(); } } @Override - public void acknowledgeByeEventReceived() - { - if ( canContinue() ) - { - immediateCommands.add( BYE_ACK ); + public void acknowledgeByeEventReceived() { + if (canContinue()) { + immediateCommands.add(BYE_ACK); barrier.release(); } } @Override - public boolean isClosed() - { + public boolean isClosed() { return closed.get(); } @Override - protected Command nextCommand() - { + protected Command nextCommand() { Command cmd = immediateCommands.poll(); - if ( cmd == null ) - { - if ( cachableCommands == null ) - { + if (cmd == null) { + if (cachableCommands == null) { cachableCommands = builder.getIterableCachable().iterator(); } @@ -130,17 +112,13 @@ protected Command nextCommand() } @Override - protected void beforeNextCommand() - throws IOException - { + protected void beforeNextCommand() throws IOException { awaitNextCommand(); } @Override - public void close() - { - if ( closed.compareAndSet( false, true ) ) - { + public void close() { + if (closed.compareAndSet(false, true)) { barrier.drainPermits(); barrier.release(); } @@ -151,21 +129,15 @@ public void close() * * @return permits used internally by {@link #beforeNextCommand()} */ - int availablePermits() - { + int availablePermits() { return barrier.availablePermits(); } - private void awaitNextCommand() - throws IOException - { - try - { + private void awaitNextCommand() throws IOException { + try { barrier.acquire(); - } - catch ( InterruptedException e ) - { - throw new IOException( e.getLocalizedMessage() ); + } catch (InterruptedException e) { + throw new IOException(e.getLocalizedMessage()); } } @@ -174,53 +146,41 @@ private void awaitNextCommand() * and provides accessible API to dispatch immediate commands to all atomically * alive streams. */ - public static final class TestLessInputStreamBuilder - { + public static final class TestLessInputStreamBuilder { private final ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock(); private final Queue aliveStreams = new ConcurrentLinkedQueue<>(); private final ImmediateCommands immediateCommands = new ImmediateCommands(); private final CachableCommands cachableCommands = new CachableCommands(); - private final Node head = new Node( null ); + private final Node head = new Node(null); private final Iterable iterableCachable; - public TestLessInputStreamBuilder() - { - iterableCachable = new Iterable() - { + public TestLessInputStreamBuilder() { + iterableCachable = new Iterable() { @Override - public Iterator iterator() - { + public Iterator iterator() { return new CIt(); } }; } - public TestLessInputStream build() - { + public TestLessInputStream build() { Lock lock = rwLock.writeLock(); lock.lock(); - try - { - TestLessInputStream is = new TestLessInputStream( this ); - aliveStreams.offer( is ); + try { + TestLessInputStream is = new TestLessInputStream(this); + aliveStreams.offer(is); return is; - } - finally - { + } finally { lock.unlock(); } } - public void removeStream( TestLessInputStream is ) - { + public void removeStream(TestLessInputStream is) { Lock lock = rwLock.writeLock(); lock.lock(); - try - { - aliveStreams.remove( is ); - } - finally - { + try { + aliveStreams.remove(is); + } finally { lock.unlock(); } } @@ -233,8 +193,7 @@ public void removeStream( TestLessInputStream is ) * to cached commands, the immediate commands disappear and cannot be seen by any fork initiated after * the command has dispatched. */ - public NotifiableTestStream getImmediateCommands() - { + public NotifiableTestStream getImmediateCommands() { return immediateCommands; } @@ -246,76 +205,61 @@ public NotifiableTestStream getImmediateCommands() * * @return commands which are cached for currently alive or future forks. */ - public NotifiableTestStream getCachableCommands() - { + public NotifiableTestStream getCachableCommands() { return cachableCommands; } /** * The iterator is not thread safe. */ - Iterable getIterableCachable() - { + Iterable getIterableCachable() { return iterableCachable; } - @SuppressWarnings( "checkstyle:innerassignment" ) - private boolean addTailNodeIfAbsent( Command command ) - { - Node newTail = new Node( command ); + @SuppressWarnings("checkstyle:innerassignment") + private boolean addTailNodeIfAbsent(Command command) { + Node newTail = new Node(command); Node currentTail = head; - do - { - for ( Node successor; ( successor = currentTail.next.get() ) != null; ) - { + do { + for (Node successor; (successor = currentTail.next.get()) != null; ) { currentTail = successor; - if ( command.equals( currentTail.command ) ) - { + if (command.equals(currentTail.command)) { return false; } } - } while ( !currentTail.next.compareAndSet( null, newTail ) ); + } while (!currentTail.next.compareAndSet(null, newTail)); return true; } - private static Node nextCachedNode( Node current ) - { + private static Node nextCachedNode(Node current) { return current.next.get(); } - private final class CIt - implements Iterator - { + private final class CIt implements Iterator { private Node node = TestLessInputStreamBuilder.this.head; @Override - public boolean hasNext() - { - return examineNext( false ) != null; + public boolean hasNext() { + return examineNext(false) != null; } @Override - public Command next() - { - Command command = examineNext( true ); - if ( command == null ) - { + public Command next() { + Command command = examineNext(true); + if (command == null) { throw new NoSuchElementException(); } return command; } @Override - public void remove() - { + public void remove() { throw new UnsupportedOperationException(); } - private Command examineNext( boolean store ) - { - Node next = nextCachedNode( node ); - if ( store && next != null ) - { + private Command examineNext(boolean store) { + Node next = nextCachedNode(node); + if (store && next != null) { node = next; } return next == null ? null : next.command; @@ -325,60 +269,45 @@ private Command examineNext( boolean store ) /** * Event is called just now for all alive streams and command is not persisted. */ - private final class ImmediateCommands - implements NotifiableTestStream - { + private final class ImmediateCommands implements NotifiableTestStream { @Override - public void provideNewTest() - { + public void provideNewTest() { throw new UnsupportedOperationException(); } @Override - public void skipSinceNextTest() - { + public void skipSinceNextTest() { throw new UnsupportedOperationException(); } @Override - public void shutdown( Shutdown shutdownType ) - { + public void shutdown(Shutdown shutdownType) { Lock lock = rwLock.readLock(); lock.lock(); - try - { - for ( TestLessInputStream aliveStream : TestLessInputStreamBuilder.this.aliveStreams ) - { - aliveStream.shutdown( shutdownType ); + try { + for (TestLessInputStream aliveStream : TestLessInputStreamBuilder.this.aliveStreams) { + aliveStream.shutdown(shutdownType); } - } - finally - { + } finally { lock.unlock(); } } @Override - public void noop() - { + public void noop() { Lock lock = rwLock.readLock(); lock.lock(); - try - { - for ( TestLessInputStream aliveStream : TestLessInputStreamBuilder.this.aliveStreams ) - { + try { + for (TestLessInputStream aliveStream : TestLessInputStreamBuilder.this.aliveStreams) { aliveStream.noop(); } - } - finally - { + } finally { lock.unlock(); } } @Override - public void acknowledgeByeEventReceived() - { + public void acknowledgeByeEventReceived() { throw new UnsupportedOperationException(); } } @@ -386,79 +315,60 @@ public void acknowledgeByeEventReceived() /** * Event is persisted. */ - private final class CachableCommands - implements NotifiableTestStream - { + private final class CachableCommands implements NotifiableTestStream { @Override - public void provideNewTest() - { + public void provideNewTest() { throw new UnsupportedOperationException(); } @Override - public void skipSinceNextTest() - { + public void skipSinceNextTest() { Lock lock = rwLock.readLock(); lock.lock(); - try - { - if ( TestLessInputStreamBuilder.this.addTailNodeIfAbsent( SKIP_SINCE_NEXT_TEST ) ) - { + try { + if (TestLessInputStreamBuilder.this.addTailNodeIfAbsent(SKIP_SINCE_NEXT_TEST)) { release(); } - } - finally - { + } finally { lock.unlock(); } } @Override - public void shutdown( Shutdown shutdownType ) - { + public void shutdown(Shutdown shutdownType) { Lock lock = rwLock.readLock(); lock.lock(); - try - { - if ( TestLessInputStreamBuilder.this.addTailNodeIfAbsent( toShutdown( shutdownType ) ) ) - { + try { + if (TestLessInputStreamBuilder.this.addTailNodeIfAbsent(toShutdown(shutdownType))) { release(); } - } - finally - { + } finally { lock.unlock(); } } @Override - public void noop() - { + public void noop() { throw new UnsupportedOperationException(); } @Override - public void acknowledgeByeEventReceived() - { + public void acknowledgeByeEventReceived() { throw new UnsupportedOperationException(); } - private void release() - { - for ( TestLessInputStream aliveStream : TestLessInputStreamBuilder.this.aliveStreams ) - { + private void release() { + for (TestLessInputStream aliveStream : TestLessInputStreamBuilder.this.aliveStreams) { aliveStream.barrier.release(); } } } - private static class Node - { + private static class Node { private final AtomicReference next = new AtomicReference<>(); private final Command command; - Node( Command command ) - { + Node(Command command) { this.command = command; } } diff --git a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/lazytestprovider/TestProvidingInputStream.java b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/lazytestprovider/TestProvidingInputStream.java index 1be8e6bc21..99b358afad 100644 --- a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/lazytestprovider/TestProvidingInputStream.java +++ b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/lazytestprovider/TestProvidingInputStream.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire.booterclient.lazytestprovider; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,9 +16,7 @@ * specific language governing permissions and limitations * under the License. */ - -import org.apache.maven.surefire.api.booter.Command; -import org.apache.maven.surefire.api.booter.Shutdown; +package org.apache.maven.plugin.surefire.booterclient.lazytestprovider; import java.io.IOException; import java.util.Queue; @@ -28,6 +24,9 @@ import java.util.concurrent.Semaphore; import java.util.concurrent.atomic.AtomicBoolean; +import org.apache.maven.surefire.api.booter.Command; +import org.apache.maven.surefire.api.booter.Shutdown; + import static org.apache.maven.surefire.api.booter.Command.BYE_ACK; import static org.apache.maven.surefire.api.booter.Command.NOOP; import static org.apache.maven.surefire.api.booter.Command.SKIP_SINCE_NEXT_TEST; @@ -46,10 +45,8 @@ * @author Andreas Gudian * @author Tibor Digana (tibor17) */ -public final class TestProvidingInputStream - extends DefaultCommandReader -{ - private final Semaphore barrier = new Semaphore( 0 ); +public final class TestProvidingInputStream extends DefaultCommandReader { + private final Semaphore barrier = new Semaphore(0); private final Queue commands = new ConcurrentLinkedQueue<>(); @@ -62,88 +59,70 @@ public final class TestProvidingInputStream * * @param testClassNames source of the tests to be read from this stream */ - public TestProvidingInputStream( Queue testClassNames ) - { + public TestProvidingInputStream(Queue testClassNames) { this.testClassNames = testClassNames; } /** * For testing purposes. */ - void testSetFinished() - { - if ( canContinue() ) - { - commands.add( TEST_SET_FINISHED ); + void testSetFinished() { + if (canContinue()) { + commands.add(TEST_SET_FINISHED); barrier.release(); } } @Override - public void skipSinceNextTest() - { - if ( canContinue() ) - { - commands.add( SKIP_SINCE_NEXT_TEST ); + public void skipSinceNextTest() { + if (canContinue()) { + commands.add(SKIP_SINCE_NEXT_TEST); barrier.release(); } } @Override - public void shutdown( Shutdown shutdownType ) - { - if ( canContinue() ) - { - commands.add( toShutdown( shutdownType ) ); + public void shutdown(Shutdown shutdownType) { + if (canContinue()) { + commands.add(toShutdown(shutdownType)); barrier.release(); } } @Override - public void noop() - { - if ( canContinue() ) - { - commands.add( NOOP ); + public void noop() { + if (canContinue()) { + commands.add(NOOP); barrier.release(); } } @Override - public void acknowledgeByeEventReceived() - { - if ( canContinue() ) - { - commands.add( BYE_ACK ); + public void acknowledgeByeEventReceived() { + if (canContinue()) { + commands.add(BYE_ACK); barrier.release(); } } @Override - protected Command nextCommand() - { + protected Command nextCommand() { Command cmd = commands.poll(); - if ( cmd == null ) - { + if (cmd == null) { String cmdData = testClassNames.poll(); - return cmdData == null ? TEST_SET_FINISHED : toRunClass( cmdData ); - } - else - { + return cmdData == null ? TEST_SET_FINISHED : toRunClass(cmdData); + } else { return cmd; } } @Override - protected void beforeNextCommand() - throws IOException - { + protected void beforeNextCommand() throws IOException { awaitNextTest(); } @Override - public boolean isClosed() - { + public boolean isClosed() { return closed.get(); } @@ -151,34 +130,25 @@ public boolean isClosed() * Signal that a new test is to be provided. */ @Override - public void provideNewTest() - { - if ( canContinue() ) - { + public void provideNewTest() { + if (canContinue()) { barrier.release(); } } @Override - public void close() - { - if ( closed.compareAndSet( false, true ) ) - { + public void close() { + if (closed.compareAndSet(false, true)) { barrier.drainPermits(); barrier.release(); } } - private void awaitNextTest() - throws IOException - { - try - { + private void awaitNextTest() throws IOException { + try { barrier.acquire(); - } - catch ( InterruptedException e ) - { - throw new IOException( e.getLocalizedMessage(), e ); + } catch (InterruptedException e) { + throw new IOException(e.getLocalizedMessage(), e); } } } diff --git a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/output/DeserializedStacktraceWriter.java b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/output/DeserializedStacktraceWriter.java index 460e4972c6..7ac2bb8761 100644 --- a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/output/DeserializedStacktraceWriter.java +++ b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/output/DeserializedStacktraceWriter.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire.booterclient.output; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.surefire.booterclient.output; import org.apache.maven.surefire.api.report.SafeThrowable; import org.apache.maven.surefire.api.report.StackTraceWriter; @@ -30,44 +29,37 @@ * * @author Kristian Rosenvold */ -public class DeserializedStacktraceWriter - implements StackTraceWriter -{ +public class DeserializedStacktraceWriter implements StackTraceWriter { private final String message; private final String smartTrimmed; private final String stackTrace; - public DeserializedStacktraceWriter( String message, String smartTrimmed, String stackTrace ) - { + public DeserializedStacktraceWriter(String message, String smartTrimmed, String stackTrace) { this.message = message; this.smartTrimmed = smartTrimmed; this.stackTrace = stackTrace; } @Override - public String smartTrimmedStackTrace() - { + public String smartTrimmedStackTrace() { return smartTrimmed; } // Trimming or not is decided on the forking side @Override - public String writeTraceToString() - { + public String writeTraceToString() { return stackTrace; } @Override - public String writeTrimmedTraceToString() - { + public String writeTrimmedTraceToString() { return stackTrace; } @Override - public SafeThrowable getThrowable() - { - return new SafeThrowable( message ); + public SafeThrowable getThrowable() { + return new SafeThrowable(message); } } diff --git a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/output/ForkClient.java b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/output/ForkClient.java index fe5b9cf263..abe2f3e5f6 100644 --- a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/output/ForkClient.java +++ b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/output/ForkClient.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire.booterclient.output; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,23 +16,10 @@ * specific language governing permissions and limitations * under the License. */ - -import org.apache.maven.plugin.surefire.booterclient.lazytestprovider.NotifiableTestStream; -import org.apache.maven.plugin.surefire.log.api.ConsoleLogger; -import org.apache.maven.plugin.surefire.report.DefaultReporterFactory; -import org.apache.maven.surefire.api.event.Event; -import org.apache.maven.surefire.api.report.TestOutputReportEntry; -import org.apache.maven.surefire.api.report.TestReportListener; -import org.apache.maven.surefire.extensions.EventHandler; -import org.apache.maven.surefire.api.booter.MasterProcessChannelEncoder; -import org.apache.maven.surefire.api.report.TestOutputReceiver; -import org.apache.maven.surefire.api.report.ReportEntry; -import org.apache.maven.surefire.api.report.RunListener; -import org.apache.maven.surefire.api.report.RunMode; -import org.apache.maven.surefire.api.report.StackTraceWriter; -import org.apache.maven.surefire.api.report.TestSetReportEntry; +package org.apache.maven.plugin.surefire.booterclient.output; import javax.annotation.Nonnull; + import java.io.File; import java.util.Map; import java.util.Queue; @@ -44,6 +29,21 @@ import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.atomic.AtomicLong; +import org.apache.maven.plugin.surefire.booterclient.lazytestprovider.NotifiableTestStream; +import org.apache.maven.plugin.surefire.log.api.ConsoleLogger; +import org.apache.maven.plugin.surefire.report.DefaultReporterFactory; +import org.apache.maven.surefire.api.booter.MasterProcessChannelEncoder; +import org.apache.maven.surefire.api.event.Event; +import org.apache.maven.surefire.api.report.ReportEntry; +import org.apache.maven.surefire.api.report.RunListener; +import org.apache.maven.surefire.api.report.RunMode; +import org.apache.maven.surefire.api.report.StackTraceWriter; +import org.apache.maven.surefire.api.report.TestOutputReceiver; +import org.apache.maven.surefire.api.report.TestOutputReportEntry; +import org.apache.maven.surefire.api.report.TestReportListener; +import org.apache.maven.surefire.api.report.TestSetReportEntry; +import org.apache.maven.surefire.extensions.EventHandler; + import static java.lang.System.currentTimeMillis; import static java.util.Collections.unmodifiableMap; import static org.apache.maven.surefire.api.booter.Shutdown.KILL; @@ -56,9 +56,7 @@ * * @author Kristian Rosenvold */ -public final class ForkClient - implements EventHandler -{ +public final class ForkClient implements EventHandler { private static final long START_TIME_ZERO = 0L; private static final long START_TIME_NEGATIVE_TIMEOUT = -1L; @@ -74,7 +72,7 @@ public final class ForkClient * testSetStartedAt is set to non-zero after received * {@link MasterProcessChannelEncoder#testSetStarting(TestSetReportEntry, boolean)}. */ - private final AtomicLong testSetStartedAt = new AtomicLong( START_TIME_ZERO ); + private final AtomicLong testSetStartedAt = new AtomicLong(START_TIME_ZERO); private final ForkedProcessEventNotifier notifier = new ForkedProcessEventNotifier(); @@ -89,235 +87,192 @@ public final class ForkClient private volatile StackTraceWriter errorInFork; - public ForkClient( DefaultReporterFactory defaultReporterFactory, - NotifiableTestStream notifiableTestStream, - int forkNumber ) - { + public ForkClient( + DefaultReporterFactory defaultReporterFactory, NotifiableTestStream notifiableTestStream, int forkNumber) { this.defaultReporterFactory = defaultReporterFactory; this.notifiableTestStream = notifiableTestStream; this.forkNumber = forkNumber; - notifier.setTestSetStartingListener( new TestSetStartingListener() ); - notifier.setTestSetCompletedListener( new TestSetCompletedListener() ); - notifier.setTestStartingListener( new TestStartingListener() ); - notifier.setTestSucceededListener( new TestSucceededListener() ); - notifier.setTestFailedListener( new TestFailedListener() ); - notifier.setTestSkippedListener( new TestSkippedListener() ); - notifier.setTestErrorListener( new TestErrorListener() ); - notifier.setTestAssumptionFailureListener( new TestAssumptionFailureListener() ); - notifier.setSystemPropertiesListener( new SystemPropertiesListener() ); - notifier.setStdOutListener( new StdOutListener() ); - notifier.setStdErrListener( new StdErrListener() ); - notifier.setConsoleInfoListener( new ConsoleListener() ); - notifier.setAcquireNextTestListener( new AcquireNextTestListener() ); - notifier.setConsoleErrorListener( new ErrorListener() ); - notifier.setByeListener( new ByeListener() ); - notifier.setConsoleDebugListener( new DebugListener() ); - notifier.setConsoleWarningListener( new WarningListener() ); - notifier.setExitErrorEventListener( new ExitErrorEventListener() ); - } - - public void setStopOnNextTestListener( ForkedProcessEventListener listener ) - { - notifier.setStopOnNextTestListener( listener ); - } - - private final class TestSetStartingListener - implements ForkedProcessReportEventListener - { + notifier.setTestSetStartingListener(new TestSetStartingListener()); + notifier.setTestSetCompletedListener(new TestSetCompletedListener()); + notifier.setTestStartingListener(new TestStartingListener()); + notifier.setTestSucceededListener(new TestSucceededListener()); + notifier.setTestFailedListener(new TestFailedListener()); + notifier.setTestSkippedListener(new TestSkippedListener()); + notifier.setTestErrorListener(new TestErrorListener()); + notifier.setTestAssumptionFailureListener(new TestAssumptionFailureListener()); + notifier.setSystemPropertiesListener(new SystemPropertiesListener()); + notifier.setStdOutListener(new StdOutListener()); + notifier.setStdErrListener(new StdErrListener()); + notifier.setConsoleInfoListener(new ConsoleListener()); + notifier.setAcquireNextTestListener(new AcquireNextTestListener()); + notifier.setConsoleErrorListener(new ErrorListener()); + notifier.setByeListener(new ByeListener()); + notifier.setConsoleDebugListener(new DebugListener()); + notifier.setConsoleWarningListener(new WarningListener()); + notifier.setExitErrorEventListener(new ExitErrorEventListener()); + } + + public void setStopOnNextTestListener(ForkedProcessEventListener listener) { + notifier.setStopOnNextTestListener(listener); + } + + private final class TestSetStartingListener implements ForkedProcessReportEventListener { @Override - public void handle( TestSetReportEntry reportEntry ) - { - getTestSetReporter().testSetStarting( reportEntry ); + public void handle(TestSetReportEntry reportEntry) { + getTestSetReporter().testSetStarting(reportEntry); setCurrentStartTime(); } } - private final class TestSetCompletedListener - implements ForkedProcessReportEventListener - { + private final class TestSetCompletedListener implements ForkedProcessReportEventListener { @Override - public void handle( TestSetReportEntry reportEntry ) - { + public void handle(TestSetReportEntry reportEntry) { testsInProgress.clear(); - TestSetReportEntry entry = reportEntry( reportEntry.getRunMode(), reportEntry.getTestRunId(), - reportEntry.getSourceName(), reportEntry.getSourceText(), - reportEntry.getName(), reportEntry.getNameText(), - reportEntry.getGroup(), reportEntry.getStackTraceWriter(), reportEntry.getElapsed(), - reportEntry.getMessage(), getTestVmSystemProperties() ); - getTestSetReporter().testSetCompleted( entry ); + TestSetReportEntry entry = reportEntry( + reportEntry.getRunMode(), + reportEntry.getTestRunId(), + reportEntry.getSourceName(), + reportEntry.getSourceText(), + reportEntry.getName(), + reportEntry.getNameText(), + reportEntry.getGroup(), + reportEntry.getStackTraceWriter(), + reportEntry.getElapsed(), + reportEntry.getMessage(), + getTestVmSystemProperties()); + getTestSetReporter().testSetCompleted(entry); } } - private final class TestStartingListener implements ForkedProcessReportEventListener - { + private final class TestStartingListener implements ForkedProcessReportEventListener { @Override - public void handle( ReportEntry reportEntry ) - { - testsInProgress.offer( reportEntry.getSourceName() ); - getTestSetReporter().testStarting( reportEntry ); + public void handle(ReportEntry reportEntry) { + testsInProgress.offer(reportEntry.getSourceName()); + getTestSetReporter().testStarting(reportEntry); } } - private final class TestSucceededListener implements ForkedProcessReportEventListener - { + private final class TestSucceededListener implements ForkedProcessReportEventListener { @Override - public void handle( ReportEntry reportEntry ) - { - testsInProgress.remove( reportEntry.getSourceName() ); - getTestSetReporter().testSucceeded( reportEntry ); + public void handle(ReportEntry reportEntry) { + testsInProgress.remove(reportEntry.getSourceName()); + getTestSetReporter().testSucceeded(reportEntry); } } - private final class TestFailedListener implements ForkedProcessReportEventListener - { + private final class TestFailedListener implements ForkedProcessReportEventListener { @Override - public void handle( ReportEntry reportEntry ) - { - testsInProgress.remove( reportEntry.getSourceName() ); - getTestSetReporter().testFailed( reportEntry ); + public void handle(ReportEntry reportEntry) { + testsInProgress.remove(reportEntry.getSourceName()); + getTestSetReporter().testFailed(reportEntry); } } - private final class TestSkippedListener implements ForkedProcessReportEventListener - { + private final class TestSkippedListener implements ForkedProcessReportEventListener { @Override - public void handle( ReportEntry reportEntry ) - { - testsInProgress.remove( reportEntry.getSourceName() ); - getTestSetReporter().testSkipped( reportEntry ); + public void handle(ReportEntry reportEntry) { + testsInProgress.remove(reportEntry.getSourceName()); + getTestSetReporter().testSkipped(reportEntry); } } - private final class TestErrorListener implements ForkedProcessReportEventListener - { + private final class TestErrorListener implements ForkedProcessReportEventListener { @Override - public void handle( ReportEntry reportEntry ) - { - testsInProgress.remove( reportEntry.getSourceName() ); - getTestSetReporter().testError( reportEntry ); + public void handle(ReportEntry reportEntry) { + testsInProgress.remove(reportEntry.getSourceName()); + getTestSetReporter().testError(reportEntry); } } - private final class TestAssumptionFailureListener implements ForkedProcessReportEventListener - { + private final class TestAssumptionFailureListener implements ForkedProcessReportEventListener { @Override - public void handle( ReportEntry reportEntry ) - { - testsInProgress.remove( reportEntry.getSourceName() ); - getTestSetReporter().testAssumptionFailure( reportEntry ); + public void handle(ReportEntry reportEntry) { + testsInProgress.remove(reportEntry.getSourceName()); + getTestSetReporter().testAssumptionFailure(reportEntry); } } - private final class SystemPropertiesListener implements ForkedProcessPropertyEventListener - { + private final class SystemPropertiesListener implements ForkedProcessPropertyEventListener { @Override - public void handle( String key, String value, RunMode runMode, Long testRunId ) - { - testVmSystemProperties.put( key, value ); + public void handle(String key, String value, RunMode runMode, Long testRunId) { + testVmSystemProperties.put(key, value); } } - private final class StdOutListener implements ForkedProcessStandardOutErrEventListener - { + private final class StdOutListener implements ForkedProcessStandardOutErrEventListener { @Override - public void handle( String output, boolean newLine, RunMode runMode, Long testRunId ) - { - writeTestOutput( output, true, newLine, runMode, testRunId ); + public void handle(String output, boolean newLine, RunMode runMode, Long testRunId) { + writeTestOutput(output, true, newLine, runMode, testRunId); } } - private final class StdErrListener implements ForkedProcessStandardOutErrEventListener - { + private final class StdErrListener implements ForkedProcessStandardOutErrEventListener { @Override - public void handle( String output, boolean newLine, RunMode runMode, Long testRunId ) - { - writeTestOutput( output, false, newLine, runMode, testRunId ); + public void handle(String output, boolean newLine, RunMode runMode, Long testRunId) { + writeTestOutput(output, false, newLine, runMode, testRunId); } } - private final class ConsoleListener implements ForkedProcessStringEventListener - { + private final class ConsoleListener implements ForkedProcessStringEventListener { @Override - public void handle( String msg ) - { - getOrCreateConsoleLogger() - .info( msg ); + public void handle(String msg) { + getOrCreateConsoleLogger().info(msg); } } - private final class AcquireNextTestListener implements ForkedProcessEventListener - { + private final class AcquireNextTestListener implements ForkedProcessEventListener { @Override - public void handle() - { + public void handle() { notifiableTestStream.provideNewTest(); } } - private class ErrorListener implements ForkedProcessStackTraceEventListener - { + private class ErrorListener implements ForkedProcessStackTraceEventListener { @Override - public void handle( @Nonnull StackTraceWriter stackTrace ) - { + public void handle(@Nonnull StackTraceWriter stackTrace) { String msg = stackTrace.getThrowable().getMessage(); - if ( errorInFork == null ) - { + if (errorInFork == null) { errorInFork = stackTrace.writeTraceToString() != null ? stackTrace : null; - if ( msg != null ) - { - getOrCreateConsoleLogger() - .error( msg ); + if (msg != null) { + getOrCreateConsoleLogger().error(msg); } } - dumpToLoFile( msg ); + dumpToLoFile(msg); } } - private final class ByeListener implements ForkedProcessEventListener - { + private final class ByeListener implements ForkedProcessEventListener { @Override - public void handle() - { + public void handle() { saidGoodBye = true; notifiableTestStream.acknowledgeByeEventReceived(); } } - private final class DebugListener implements ForkedProcessStringEventListener - { + private final class DebugListener implements ForkedProcessStringEventListener { @Override - public void handle( String msg ) - { - getOrCreateConsoleLogger() - .debug( msg ); + public void handle(String msg) { + getOrCreateConsoleLogger().debug(msg); } } - private final class WarningListener implements ForkedProcessStringEventListener - { + private final class WarningListener implements ForkedProcessStringEventListener { @Override - public void handle( String msg ) - { - getOrCreateConsoleLogger() - .warning( msg ); + public void handle(String msg) { + getOrCreateConsoleLogger().warning(msg); } } - private final class ExitErrorEventListener implements ForkedProcessExitErrorListener - { + private final class ExitErrorEventListener implements ForkedProcessExitErrorListener { @Override - public void handle( StackTraceWriter stackTrace ) - { - getOrCreateConsoleLogger() - .error( "The surefire booter JVM" + forkNumber + " was interrupted and exits." ); + public void handle(StackTraceWriter stackTrace) { + getOrCreateConsoleLogger().error("The surefire booter JVM" + forkNumber + " was interrupted and exits."); } } - public void kill() - { - if ( !saidGoodBye ) - { - notifiableTestStream.shutdown( KILL ); + public void kill() { + if (!saidGoodBye) { + notifiableTestStream.shutdown(KILL); } } @@ -328,57 +283,46 @@ public void kill() * @param currentTimeMillis current time in millis seconds * @param forkedProcessTimeoutInSeconds timeout in seconds given by MOJO */ - public void tryToTimeout( long currentTimeMillis, int forkedProcessTimeoutInSeconds ) - { - if ( forkedProcessTimeoutInSeconds > 0 ) - { + public void tryToTimeout(long currentTimeMillis, int forkedProcessTimeoutInSeconds) { + if (forkedProcessTimeoutInSeconds > 0) { final long forkedProcessTimeoutInMillis = 1000L * forkedProcessTimeoutInSeconds; final long startedAt = testSetStartedAt.get(); - if ( startedAt > START_TIME_ZERO && currentTimeMillis - startedAt >= forkedProcessTimeoutInMillis ) - { - testSetStartedAt.set( START_TIME_NEGATIVE_TIMEOUT ); - notifiableTestStream.shutdown( KILL ); + if (startedAt > START_TIME_ZERO && currentTimeMillis - startedAt >= forkedProcessTimeoutInMillis) { + testSetStartedAt.set(START_TIME_NEGATIVE_TIMEOUT); + notifiableTestStream.shutdown(KILL); } } } - public DefaultReporterFactory getDefaultReporterFactory() - { + public DefaultReporterFactory getDefaultReporterFactory() { return defaultReporterFactory; } @Override - public void handleEvent( @Nonnull Event event ) - { - notifier.notifyEvent( event ); + public void handleEvent(@Nonnull Event event) { + notifier.notifyEvent(event); } - private void setCurrentStartTime() - { - if ( testSetStartedAt.get() == START_TIME_ZERO ) // JIT can optimize <= no JNI call + private void setCurrentStartTime() { + if (testSetStartedAt.get() == START_TIME_ZERO) // JIT can optimize <= no JNI call { // Not necessary to call JNI library library #currentTimeMillis // which may waste 10 - 30 machine cycles in callback. Callbacks should be fast. - testSetStartedAt.compareAndSet( START_TIME_ZERO, currentTimeMillis() ); + testSetStartedAt.compareAndSet(START_TIME_ZERO, currentTimeMillis()); } } - public boolean hadTimeout() - { + public boolean hadTimeout() { return testSetStartedAt.get() == START_TIME_NEGATIVE_TIMEOUT; } /** * Only {@link #getConsoleOutputReceiver()} may call this method in another Thread. */ - private TestReportListener getTestSetReporter() - { - if ( testSetReporter == null ) - { - synchronized ( this ) - { - if ( testSetReporter == null ) - { + private TestReportListener getTestSetReporter() { + if (testSetReporter == null) { + synchronized (this) { + if (testSetReporter == null) { testSetReporter = defaultReporterFactory.createTestReportListener(); } } @@ -386,22 +330,19 @@ private TestReportListener getTestSetReporter() return testSetReporter; } - void dumpToLoFile( String msg ) - { + void dumpToLoFile(String msg) { File reportsDir = defaultReporterFactory.getReportsDirectory(); InPluginProcessDumpSingleton util = InPluginProcessDumpSingleton.getSingleton(); - util.dumpStreamText( msg, reportsDir, forkNumber ); + util.dumpStreamText(msg, reportsDir, forkNumber); } - private void writeTestOutput( String output, boolean isStdout, boolean newLine, RunMode runMode, Long testRunId ) - { + private void writeTestOutput(String output, boolean isStdout, boolean newLine, RunMode runMode, Long testRunId) { getConsoleOutputReceiver() - .writeTestOutput( new TestOutputReportEntry( output, isStdout, newLine, runMode, testRunId ) ); + .writeTestOutput(new TestOutputReportEntry(output, isStdout, newLine, runMode, testRunId)); } - public Map getTestVmSystemProperties() - { - return unmodifiableMap( testVmSystemProperties ); + public Map getTestVmSystemProperties() { + return unmodifiableMap(testVmSystemProperties); } /** @@ -410,48 +351,39 @@ public Map getTestVmSystemProperties() * * @return A mock provider reporter */ - public RunListener getReporter() - { + public RunListener getReporter() { return getTestSetReporter(); } - public TestOutputReceiver getConsoleOutputReceiver() - { + public TestOutputReceiver getConsoleOutputReceiver() { return getTestSetReporter(); } - private ConsoleLogger getOrCreateConsoleLogger() - { + private ConsoleLogger getOrCreateConsoleLogger() { return getTestSetReporter(); } - public void close( boolean hadTimeout ) - { + public void close(boolean hadTimeout) { // no op } - public boolean isSaidGoodBye() - { + public boolean isSaidGoodBye() { return saidGoodBye; } - public StackTraceWriter getErrorInFork() - { + public StackTraceWriter getErrorInFork() { return errorInFork; } - public boolean isErrorInFork() - { + public boolean isErrorInFork() { return errorInFork != null; } - public Set testsInProgress() - { - return new TreeSet<>( testsInProgress ); + public Set testsInProgress() { + return new TreeSet<>(testsInProgress); } - public boolean hasTestsInProgress() - { + public boolean hasTestsInProgress() { return !testsInProgress.isEmpty(); } } diff --git a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/output/ForkedProcessEventListener.java b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/output/ForkedProcessEventListener.java index 61482958ae..b768efde91 100644 --- a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/output/ForkedProcessEventListener.java +++ b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/output/ForkedProcessEventListener.java @@ -1,3 +1,21 @@ +/* + * 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.maven.plugin.surefire.booterclient.output; /* @@ -23,7 +41,6 @@ * @author Tibor Digana (tibor17) * @since 3.0.0-M4 */ -public interface ForkedProcessEventListener -{ +public interface ForkedProcessEventListener { void handle(); } diff --git a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/output/ForkedProcessEventNotifier.java b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/output/ForkedProcessEventNotifier.java index 8effa98cc8..a3cedd0350 100644 --- a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/output/ForkedProcessEventNotifier.java +++ b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/output/ForkedProcessEventNotifier.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire.booterclient.output; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,10 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.surefire.booterclient.output; + +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; import org.apache.maven.surefire.api.booter.ForkedProcessEventType; import org.apache.maven.surefire.api.event.AbstractConsoleEvent; @@ -30,9 +32,6 @@ import org.apache.maven.surefire.api.report.ReportEntry; import org.apache.maven.surefire.api.report.RunMode; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; - import static java.util.Objects.requireNonNull; import static org.apache.maven.surefire.api.booter.ForkedProcessEventType.BOOTERCODE_BYE; import static org.apache.maven.surefire.api.booter.ForkedProcessEventType.BOOTERCODE_CONSOLE_DEBUG; @@ -59,8 +58,7 @@ * @author Tibor Digana (tibor17) * @since 3.0.0-M4 */ -public final class ForkedProcessEventNotifier -{ +public final class ForkedProcessEventNotifier { private volatile ForkedProcessPropertyEventListener propertyEventListener; private volatile ForkedProcessStackTraceEventListener consoleErrorEventListener; private volatile ForkedProcessExitErrorListener exitErrorEventListener; @@ -69,7 +67,7 @@ public final class ForkedProcessEventNotifier new ConcurrentHashMap<>(); private final ConcurrentMap - stdOutErrEventListeners = new ConcurrentHashMap<>(); + stdOutErrEventListeners = new ConcurrentHashMap<>(); private final ConcurrentMap consoleEventListeners = new ConcurrentHashMap<>(); @@ -77,173 +75,134 @@ public final class ForkedProcessEventNotifier private final ConcurrentMap controlEventListeners = new ConcurrentHashMap<>(); - public void setSystemPropertiesListener( ForkedProcessPropertyEventListener listener ) - { - propertyEventListener = requireNonNull( listener ); + public void setSystemPropertiesListener(ForkedProcessPropertyEventListener listener) { + propertyEventListener = requireNonNull(listener); } - public void setTestSetStartingListener( ForkedProcessReportEventListener listener ) - { - reportEventListeners.put( BOOTERCODE_TESTSET_STARTING, requireNonNull( listener ) ); + public void setTestSetStartingListener(ForkedProcessReportEventListener listener) { + reportEventListeners.put(BOOTERCODE_TESTSET_STARTING, requireNonNull(listener)); } - public void setTestSetCompletedListener( ForkedProcessReportEventListener listener ) - { - reportEventListeners.put( BOOTERCODE_TESTSET_COMPLETED, requireNonNull( listener ) ); + public void setTestSetCompletedListener(ForkedProcessReportEventListener listener) { + reportEventListeners.put(BOOTERCODE_TESTSET_COMPLETED, requireNonNull(listener)); } - public void setTestStartingListener( ForkedProcessReportEventListener listener ) - { - reportEventListeners.put( BOOTERCODE_TEST_STARTING, requireNonNull( listener ) ); + public void setTestStartingListener(ForkedProcessReportEventListener listener) { + reportEventListeners.put(BOOTERCODE_TEST_STARTING, requireNonNull(listener)); } - public void setTestSucceededListener( ForkedProcessReportEventListener listener ) - { - reportEventListeners.put( BOOTERCODE_TEST_SUCCEEDED, requireNonNull( listener ) ); + public void setTestSucceededListener(ForkedProcessReportEventListener listener) { + reportEventListeners.put(BOOTERCODE_TEST_SUCCEEDED, requireNonNull(listener)); } - public void setTestFailedListener( ForkedProcessReportEventListener listener ) - { - reportEventListeners.put( BOOTERCODE_TEST_FAILED, requireNonNull( listener ) ); + public void setTestFailedListener(ForkedProcessReportEventListener listener) { + reportEventListeners.put(BOOTERCODE_TEST_FAILED, requireNonNull(listener)); } - public void setTestSkippedListener( ForkedProcessReportEventListener listener ) - { - reportEventListeners.put( BOOTERCODE_TEST_SKIPPED, requireNonNull( listener ) ); + public void setTestSkippedListener(ForkedProcessReportEventListener listener) { + reportEventListeners.put(BOOTERCODE_TEST_SKIPPED, requireNonNull(listener)); } - public void setTestErrorListener( ForkedProcessReportEventListener listener ) - { - reportEventListeners.put( BOOTERCODE_TEST_ERROR, requireNonNull( listener ) ); + public void setTestErrorListener(ForkedProcessReportEventListener listener) { + reportEventListeners.put(BOOTERCODE_TEST_ERROR, requireNonNull(listener)); } - public void setTestAssumptionFailureListener( ForkedProcessReportEventListener listener ) - { - reportEventListeners.put( BOOTERCODE_TEST_ASSUMPTIONFAILURE, requireNonNull( listener ) ); + public void setTestAssumptionFailureListener(ForkedProcessReportEventListener listener) { + reportEventListeners.put(BOOTERCODE_TEST_ASSUMPTIONFAILURE, requireNonNull(listener)); } - public void setStdOutListener( ForkedProcessStandardOutErrEventListener listener ) - { - stdOutErrEventListeners.put( BOOTERCODE_STDOUT, requireNonNull( listener ) ); - stdOutErrEventListeners.put( BOOTERCODE_STDOUT_NEW_LINE, requireNonNull( listener ) ); + public void setStdOutListener(ForkedProcessStandardOutErrEventListener listener) { + stdOutErrEventListeners.put(BOOTERCODE_STDOUT, requireNonNull(listener)); + stdOutErrEventListeners.put(BOOTERCODE_STDOUT_NEW_LINE, requireNonNull(listener)); } - public void setStdErrListener( ForkedProcessStandardOutErrEventListener listener ) - { - stdOutErrEventListeners.put( BOOTERCODE_STDERR, requireNonNull( listener ) ); - stdOutErrEventListeners.put( BOOTERCODE_STDERR_NEW_LINE, requireNonNull( listener ) ); + public void setStdErrListener(ForkedProcessStandardOutErrEventListener listener) { + stdOutErrEventListeners.put(BOOTERCODE_STDERR, requireNonNull(listener)); + stdOutErrEventListeners.put(BOOTERCODE_STDERR_NEW_LINE, requireNonNull(listener)); } - public void setConsoleInfoListener( ForkedProcessStringEventListener listener ) - { - consoleEventListeners.put( BOOTERCODE_CONSOLE_INFO, requireNonNull( listener ) ); + public void setConsoleInfoListener(ForkedProcessStringEventListener listener) { + consoleEventListeners.put(BOOTERCODE_CONSOLE_INFO, requireNonNull(listener)); } - public void setConsoleErrorListener( ForkedProcessStackTraceEventListener listener ) - { - consoleErrorEventListener = requireNonNull( listener ); + public void setConsoleErrorListener(ForkedProcessStackTraceEventListener listener) { + consoleErrorEventListener = requireNonNull(listener); } - public void setConsoleDebugListener( ForkedProcessStringEventListener listener ) - { - consoleEventListeners.put( BOOTERCODE_CONSOLE_DEBUG, requireNonNull( listener ) ); + public void setConsoleDebugListener(ForkedProcessStringEventListener listener) { + consoleEventListeners.put(BOOTERCODE_CONSOLE_DEBUG, requireNonNull(listener)); } - public void setConsoleWarningListener( ForkedProcessStringEventListener listener ) - { - consoleEventListeners.put( BOOTERCODE_CONSOLE_WARNING, requireNonNull( listener ) ); + public void setConsoleWarningListener(ForkedProcessStringEventListener listener) { + consoleEventListeners.put(BOOTERCODE_CONSOLE_WARNING, requireNonNull(listener)); } - public void setByeListener( ForkedProcessEventListener listener ) - { - controlEventListeners.put( BOOTERCODE_BYE, requireNonNull( listener ) ); + public void setByeListener(ForkedProcessEventListener listener) { + controlEventListeners.put(BOOTERCODE_BYE, requireNonNull(listener)); } - public void setStopOnNextTestListener( ForkedProcessEventListener listener ) - { - controlEventListeners.put( BOOTERCODE_STOP_ON_NEXT_TEST, requireNonNull( listener ) ); + public void setStopOnNextTestListener(ForkedProcessEventListener listener) { + controlEventListeners.put(BOOTERCODE_STOP_ON_NEXT_TEST, requireNonNull(listener)); } - public void setAcquireNextTestListener( ForkedProcessEventListener listener ) - { - controlEventListeners.put( BOOTERCODE_NEXT_TEST, requireNonNull( listener ) ); + public void setAcquireNextTestListener(ForkedProcessEventListener listener) { + controlEventListeners.put(BOOTERCODE_NEXT_TEST, requireNonNull(listener)); } - public void setExitErrorEventListener( ForkedProcessExitErrorListener listener ) - { - exitErrorEventListener = requireNonNull( listener ); + public void setExitErrorEventListener(ForkedProcessExitErrorListener listener) { + exitErrorEventListener = requireNonNull(listener); } - public void notifyEvent( Event event ) - { + public void notifyEvent(Event event) { ForkedProcessEventType eventType = event.getEventType(); - if ( event.isControlCategory() ) - { - ForkedProcessEventListener listener = controlEventListeners.get( eventType ); - if ( listener != null ) - { + if (event.isControlCategory()) { + ForkedProcessEventListener listener = controlEventListeners.get(eventType); + if (listener != null) { listener.handle(); } - } - else if ( event.isConsoleErrorCategory() ) - { - if ( consoleErrorEventListener != null ) - { - consoleErrorEventListener.handle( ( ( ConsoleErrorEvent ) event ).getStackTraceWriter() ); + } else if (event.isConsoleErrorCategory()) { + if (consoleErrorEventListener != null) { + consoleErrorEventListener.handle(((ConsoleErrorEvent) event).getStackTraceWriter()); } - } - else if ( event.isConsoleCategory() ) - { - ForkedProcessStringEventListener listener = consoleEventListeners.get( eventType ); - if ( listener != null ) - { - listener.handle( ( (AbstractConsoleEvent) event ).getMessage() ); + } else if (event.isConsoleCategory()) { + ForkedProcessStringEventListener listener = consoleEventListeners.get(eventType); + if (listener != null) { + listener.handle(((AbstractConsoleEvent) event).getMessage()); } - } - else if ( event.isStandardStreamCategory() ) - { + } else if (event.isStandardStreamCategory()) { boolean newLine = eventType == BOOTERCODE_STDOUT_NEW_LINE || eventType == BOOTERCODE_STDERR_NEW_LINE; AbstractStandardStreamEvent standardStreamEvent = (AbstractStandardStreamEvent) event; - ForkedProcessStandardOutErrEventListener listener = stdOutErrEventListeners.get( eventType ); - if ( listener != null ) - { - listener.handle( standardStreamEvent.getMessage(), newLine, - standardStreamEvent.getRunMode(), standardStreamEvent.getTestRunId() ); + ForkedProcessStandardOutErrEventListener listener = stdOutErrEventListeners.get(eventType); + if (listener != null) { + listener.handle( + standardStreamEvent.getMessage(), + newLine, + standardStreamEvent.getRunMode(), + standardStreamEvent.getTestRunId()); } - } - else if ( event.isSysPropCategory() ) - { + } else if (event.isSysPropCategory()) { SystemPropertyEvent systemPropertyEvent = (SystemPropertyEvent) event; RunMode runMode = systemPropertyEvent.getRunMode(); Long testRunId = systemPropertyEvent.getTestRunId(); String key = systemPropertyEvent.getKey(); String value = systemPropertyEvent.getValue(); - if ( propertyEventListener != null ) - { - propertyEventListener.handle( key, value, runMode, testRunId ); + if (propertyEventListener != null) { + propertyEventListener.handle(key, value, runMode, testRunId); } - } - else if ( event.isTestCategory() ) - { - ForkedProcessReportEventListener listener = reportEventListeners.get( eventType ); + } else if (event.isTestCategory()) { + ForkedProcessReportEventListener listener = reportEventListeners.get(eventType); AbstractTestControlEvent testControlEvent = (AbstractTestControlEvent) event; ReportEntry reportEntry = testControlEvent.getReportEntry(); - if ( listener != null ) - { - listener.handle( reportEntry ); + if (listener != null) { + listener.handle(reportEntry); } - } - else if ( event.isJvmExitError() ) - { + } else if (event.isJvmExitError()) { JvmExitErrorEvent jvmExitErrorEvent = (JvmExitErrorEvent) event; - if ( exitErrorEventListener != null ) - { - exitErrorEventListener.handle( jvmExitErrorEvent.getStackTraceWriter() ); + if (exitErrorEventListener != null) { + exitErrorEventListener.handle(jvmExitErrorEvent.getStackTraceWriter()); } - } - else - { - throw new IllegalArgumentException( "Unknown event type " + eventType ); + } else { + throw new IllegalArgumentException("Unknown event type " + eventType); } } } diff --git a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/output/ForkedProcessExitErrorListener.java b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/output/ForkedProcessExitErrorListener.java index b88a7e124d..a37fdea5dc 100644 --- a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/output/ForkedProcessExitErrorListener.java +++ b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/output/ForkedProcessExitErrorListener.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire.booterclient.output; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.surefire.booterclient.output; import org.apache.maven.surefire.api.report.StackTraceWriter; @@ -25,7 +24,6 @@ * @author Tibor Digana (tibor17) * @since 3.0.0-M4 */ -public interface ForkedProcessExitErrorListener -{ - void handle( StackTraceWriter stackTrace ); +public interface ForkedProcessExitErrorListener { + void handle(StackTraceWriter stackTrace); } diff --git a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/output/ForkedProcessPropertyEventListener.java b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/output/ForkedProcessPropertyEventListener.java index 271f367a85..cf678a5f56 100644 --- a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/output/ForkedProcessPropertyEventListener.java +++ b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/output/ForkedProcessPropertyEventListener.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire.booterclient.output; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.surefire.booterclient.output; import org.apache.maven.surefire.api.report.RunMode; @@ -25,7 +24,6 @@ * @author Tibor Digana (tibor17) * @since 3.0.0-M4 */ -public interface ForkedProcessPropertyEventListener -{ - void handle( String key, String value, RunMode runMode, Long testRunId ); +public interface ForkedProcessPropertyEventListener { + void handle(String key, String value, RunMode runMode, Long testRunId); } diff --git a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/output/ForkedProcessReportEventListener.java b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/output/ForkedProcessReportEventListener.java index 10f393d0d5..ec25a31004 100644 --- a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/output/ForkedProcessReportEventListener.java +++ b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/output/ForkedProcessReportEventListener.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire.booterclient.output; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.surefire.booterclient.output; import org.apache.maven.surefire.api.report.ReportEntry; @@ -26,7 +25,6 @@ * @since 3.0.0-M4 * @param report entry type */ -public interface ForkedProcessReportEventListener -{ - void handle( T reportEntry ); +public interface ForkedProcessReportEventListener { + void handle(T reportEntry); } diff --git a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/output/ForkedProcessStackTraceEventListener.java b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/output/ForkedProcessStackTraceEventListener.java index afedef50f0..6f652c95c6 100644 --- a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/output/ForkedProcessStackTraceEventListener.java +++ b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/output/ForkedProcessStackTraceEventListener.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire.booterclient.output; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,16 +16,16 @@ * specific language governing permissions and limitations * under the License. */ - -import org.apache.maven.surefire.api.report.StackTraceWriter; +package org.apache.maven.plugin.surefire.booterclient.output; import javax.annotation.Nonnull; +import org.apache.maven.surefire.api.report.StackTraceWriter; + /** * @author Tibor Digana (tibor17) * @since 3.0.0-M4 */ -public interface ForkedProcessStackTraceEventListener -{ - void handle( @Nonnull StackTraceWriter stackTrace ); +public interface ForkedProcessStackTraceEventListener { + void handle(@Nonnull StackTraceWriter stackTrace); } diff --git a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/output/ForkedProcessStandardOutErrEventListener.java b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/output/ForkedProcessStandardOutErrEventListener.java index be8b5663fa..fc966cd956 100644 --- a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/output/ForkedProcessStandardOutErrEventListener.java +++ b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/output/ForkedProcessStandardOutErrEventListener.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire.booterclient.output; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.surefire.booterclient.output; import org.apache.maven.surefire.api.report.RunMode; @@ -25,7 +24,6 @@ * @author Tibor Digana (tibor17) * @since 3.0.0-M4 */ -public interface ForkedProcessStandardOutErrEventListener -{ - void handle( String output, boolean newLine, RunMode runMode, Long testRunId ); +public interface ForkedProcessStandardOutErrEventListener { + void handle(String output, boolean newLine, RunMode runMode, Long testRunId); } diff --git a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/output/ForkedProcessStringEventListener.java b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/output/ForkedProcessStringEventListener.java index 9bd863aa3c..bc2f8264f0 100644 --- a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/output/ForkedProcessStringEventListener.java +++ b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/output/ForkedProcessStringEventListener.java @@ -1,3 +1,21 @@ +/* + * 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.maven.plugin.surefire.booterclient.output; /* @@ -23,7 +41,6 @@ * @author Tibor Digana (tibor17) * @since 3.0.0-M4 */ -public interface ForkedProcessStringEventListener -{ - void handle( String msg ); +public interface ForkedProcessStringEventListener { + void handle(String msg); } diff --git a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/output/InPluginProcessDumpSingleton.java b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/output/InPluginProcessDumpSingleton.java index 05c4235c44..8a4684c6d5 100644 --- a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/output/InPluginProcessDumpSingleton.java +++ b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/output/InPluginProcessDumpSingleton.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire.booterclient.output; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,94 +16,80 @@ * specific language governing permissions and limitations * under the License. */ - -import org.apache.maven.surefire.api.util.internal.DumpFileUtils; +package org.apache.maven.plugin.surefire.booterclient.output; import java.io.File; +import org.apache.maven.surefire.api.util.internal.DumpFileUtils; + import static java.lang.String.format; -import static org.apache.maven.plugin.surefire.SurefireHelper.DUMP_FILENAME; -import static org.apache.maven.plugin.surefire.SurefireHelper.DUMP_FILENAME_FORMATTER; import static org.apache.maven.plugin.surefire.SurefireHelper.DUMPSTREAM_FILENAME; import static org.apache.maven.plugin.surefire.SurefireHelper.DUMPSTREAM_FILENAME_FORMATTER; +import static org.apache.maven.plugin.surefire.SurefireHelper.DUMP_FILENAME; +import static org.apache.maven.plugin.surefire.SurefireHelper.DUMP_FILENAME_FORMATTER; import static org.apache.maven.plugin.surefire.SurefireHelper.EVENTS_BINARY_DUMP_FILENAME_FORMATTER; /** * Reports errors to dump file. * Used only within java process of the plugin itself and not the forked JVM. */ -public final class InPluginProcessDumpSingleton -{ +public final class InPluginProcessDumpSingleton { private static final InPluginProcessDumpSingleton SINGLETON = new InPluginProcessDumpSingleton(); - private InPluginProcessDumpSingleton() - { - } + private InPluginProcessDumpSingleton() {} - public static InPluginProcessDumpSingleton getSingleton() - { + public static InPluginProcessDumpSingleton getSingleton() { return SINGLETON; } - public synchronized File dumpStreamException( Throwable t, String msg, File reportsDirectory, int jvmRun ) - { - File dump = newDumpStreamFile( reportsDirectory, jvmRun ); - DumpFileUtils.dumpException( t, msg == null ? "null" : msg, dump ); + public synchronized File dumpStreamException(Throwable t, String msg, File reportsDirectory, int jvmRun) { + File dump = newDumpStreamFile(reportsDirectory, jvmRun); + DumpFileUtils.dumpException(t, msg == null ? "null" : msg, dump); return dump; } - public synchronized void dumpStreamException( Throwable t, String msg, File reportsDirectory ) - { - DumpFileUtils.dumpException( t, msg == null ? "null" : msg, newDumpStreamFile( reportsDirectory ) ); + public synchronized void dumpStreamException(Throwable t, String msg, File reportsDirectory) { + DumpFileUtils.dumpException(t, msg == null ? "null" : msg, newDumpStreamFile(reportsDirectory)); } - public synchronized File dumpStreamText( String msg, File reportsDirectory, int jvmRun ) - { - File dump = newDumpStreamFile( reportsDirectory, jvmRun ); - DumpFileUtils.dumpText( msg == null ? "null" : msg, dump ); + public synchronized File dumpStreamText(String msg, File reportsDirectory, int jvmRun) { + File dump = newDumpStreamFile(reportsDirectory, jvmRun); + DumpFileUtils.dumpText(msg == null ? "null" : msg, dump); return dump; } - public synchronized void dumpStreamText( String msg, File reportsDirectory ) - { - DumpFileUtils.dumpText( msg == null ? "null" : msg, newDumpStreamFile( reportsDirectory ) ); + public synchronized void dumpStreamText(String msg, File reportsDirectory) { + DumpFileUtils.dumpText(msg == null ? "null" : msg, newDumpStreamFile(reportsDirectory)); } - public synchronized void dumpException( Throwable t, String msg, File reportsDirectory, int jvmRun ) - { - File dump = newDumpFile( reportsDirectory, jvmRun ); - DumpFileUtils.dumpException( t, msg == null ? "null" : msg, dump ); + public synchronized void dumpException(Throwable t, String msg, File reportsDirectory, int jvmRun) { + File dump = newDumpFile(reportsDirectory, jvmRun); + DumpFileUtils.dumpException(t, msg == null ? "null" : msg, dump); } - public synchronized void dumpException( Throwable t, String msg, File reportsDirectory ) - { - File dump = newDumpFile( reportsDirectory ); - DumpFileUtils.dumpException( t, msg == null ? "null" : msg, dump ); + public synchronized void dumpException(Throwable t, String msg, File reportsDirectory) { + File dump = newDumpFile(reportsDirectory); + DumpFileUtils.dumpException(t, msg == null ? "null" : msg, dump); } - public File getEventStreamBinaryFile( File reportsDirectory, int jvmRun ) - { + public File getEventStreamBinaryFile(File reportsDirectory, int jvmRun) { reportsDirectory.mkdirs(); - return new File( reportsDirectory, format( EVENTS_BINARY_DUMP_FILENAME_FORMATTER, jvmRun ) ); + return new File(reportsDirectory, format(EVENTS_BINARY_DUMP_FILENAME_FORMATTER, jvmRun)); } - private File newDumpStreamFile( File reportsDirectory ) - { - return new File( reportsDirectory, DUMPSTREAM_FILENAME ); + private File newDumpStreamFile(File reportsDirectory) { + return new File(reportsDirectory, DUMPSTREAM_FILENAME); } - private static File newDumpStreamFile( File reportsDirectory, int jvmRun ) - { - return new File( reportsDirectory, format( DUMPSTREAM_FILENAME_FORMATTER, jvmRun ) ); + private static File newDumpStreamFile(File reportsDirectory, int jvmRun) { + return new File(reportsDirectory, format(DUMPSTREAM_FILENAME_FORMATTER, jvmRun)); } - private static File newDumpFile( File reportsDirectory, int jvmRun ) - { - return new File( reportsDirectory, format( DUMP_FILENAME_FORMATTER, jvmRun ) ); + private static File newDumpFile(File reportsDirectory, int jvmRun) { + return new File(reportsDirectory, format(DUMP_FILENAME_FORMATTER, jvmRun)); } - private static File newDumpFile( File reportsDirectory ) - { - return new File( reportsDirectory, DUMP_FILENAME ); + private static File newDumpFile(File reportsDirectory) { + return new File(reportsDirectory, DUMP_FILENAME); } } diff --git a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/output/MultipleFailureException.java b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/output/MultipleFailureException.java index ac621d3bdc..8b4f9a7d87 100644 --- a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/output/MultipleFailureException.java +++ b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/output/MultipleFailureException.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire.booterclient.output; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,46 +16,38 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.surefire.booterclient.output; import java.io.IOException; import java.util.function.Function; -final class MultipleFailureException - extends IOException -{ - void addException( Throwable exception ) - { - addSuppressed( exception ); +final class MultipleFailureException extends IOException { + void addException(Throwable exception) { + addSuppressed(exception); } - boolean hasNestedExceptions() - { + boolean hasNestedExceptions() { return getSuppressed().length != 0; } @Override - public String getLocalizedMessage() - { - return toMessage( Throwable::getLocalizedMessage ); + public String getLocalizedMessage() { + return toMessage(Throwable::getLocalizedMessage); } @Override - public String getMessage() - { - return toMessage( Throwable::getMessage ); + public String getMessage() { + return toMessage(Throwable::getMessage); } - private String toMessage( Function msg ) - { + private String toMessage(Function msg) { StringBuilder messages = new StringBuilder(); - for ( Throwable exception : getSuppressed() ) - { - if ( messages.length() != 0 ) - { - messages.append( '\n' ); + for (Throwable exception : getSuppressed()) { + if (messages.length() != 0) { + messages.append('\n'); } - String message = msg.apply( exception ); - messages.append( message == null ? exception.toString() : message ); + String message = msg.apply(exception); + messages.append(message == null ? exception.toString() : message); } return messages.toString(); } diff --git a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/output/NativeStdErrStreamConsumer.java b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/output/NativeStdErrStreamConsumer.java index 70e36f146a..a8e3d332a7 100644 --- a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/output/NativeStdErrStreamConsumer.java +++ b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/output/NativeStdErrStreamConsumer.java @@ -1,3 +1,21 @@ +/* + * 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.maven.plugin.surefire.booterclient.output; /* @@ -19,10 +37,10 @@ * under the License. */ -import org.apache.maven.surefire.extensions.EventHandler; - import javax.annotation.Nonnull; +import org.apache.maven.surefire.extensions.EventHandler; + /** * The standard error logger for the error stream of the forked JMV, * see {@link org.apache.maven.plugin.surefire.booterclient.ForkStarter}. @@ -31,22 +49,17 @@ * @since 2.20 * @see org.apache.maven.plugin.surefire.booterclient.ForkStarter */ -public final class NativeStdErrStreamConsumer - implements EventHandler -{ +public final class NativeStdErrStreamConsumer implements EventHandler { private final Object errStreamLock; - public NativeStdErrStreamConsumer( Object errStreamLock ) - { + public NativeStdErrStreamConsumer(Object errStreamLock) { this.errStreamLock = errStreamLock; } @Override - public void handleEvent( @Nonnull String message ) - { - synchronized ( errStreamLock ) - { - System.err.println( message ); + public void handleEvent(@Nonnull String message) { + synchronized (errStreamLock) { + System.err.println(message); } } } diff --git a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/output/NativeStdOutStreamConsumer.java b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/output/NativeStdOutStreamConsumer.java index 4d0a268539..a6dfdc66d7 100644 --- a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/output/NativeStdOutStreamConsumer.java +++ b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/output/NativeStdOutStreamConsumer.java @@ -1,3 +1,21 @@ +/* + * 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.maven.plugin.surefire.booterclient.output; /* @@ -19,10 +37,10 @@ * under the License. */ -import org.apache.maven.surefire.extensions.EventHandler; - import javax.annotation.Nonnull; +import org.apache.maven.surefire.extensions.EventHandler; + /** * The standard output logger for the output stream of the forked JMV, * see org.apache.maven.plugin.surefire.extensions.SurefireForkChannel. @@ -30,22 +48,17 @@ * @author Tibor Digana (tibor17) * @since 3.0.0-M5 */ -public final class NativeStdOutStreamConsumer - implements EventHandler -{ +public final class NativeStdOutStreamConsumer implements EventHandler { private final Object outStreamLock; - public NativeStdOutStreamConsumer( Object outStreamLock ) - { + public NativeStdOutStreamConsumer(Object outStreamLock) { this.outStreamLock = outStreamLock; } @Override - public void handleEvent( @Nonnull String message ) - { - synchronized ( outStreamLock ) - { - System.out.println( message ); + public void handleEvent(@Nonnull String message) { + synchronized (outStreamLock) { + System.out.println(message); } } } diff --git a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/output/ThreadedStreamConsumer.java b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/output/ThreadedStreamConsumer.java index fd9b6b7b5b..c0090543b7 100644 --- a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/output/ThreadedStreamConsumer.java +++ b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/output/ThreadedStreamConsumer.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire.booterclient.output; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.surefire.booterclient.output; import javax.annotation.Nonnull; @@ -44,27 +43,22 @@ * * @author Kristian Rosenvold */ -public final class ThreadedStreamConsumer - implements EventHandler, Closeable -{ +public final class ThreadedStreamConsumer implements EventHandler, Closeable { private static final int QUEUE_MAX_ITEMS = 10_000; private static final Event END_ITEM = new FinalEvent(); - private final QueueSynchronizer synchronizer = new QueueSynchronizer<>( QUEUE_MAX_ITEMS, END_ITEM ); + private final QueueSynchronizer synchronizer = new QueueSynchronizer<>(QUEUE_MAX_ITEMS, END_ITEM); private final AtomicBoolean stop = new AtomicBoolean(); - private final AtomicBoolean isAlive = new AtomicBoolean( true ); + private final AtomicBoolean isAlive = new AtomicBoolean(true); private final Thread consumer; private final Pumper pumper; - final class Pumper - implements Runnable - { + final class Pumper implements Runnable { private final EventHandler target; private final MultipleFailureException errors = new MultipleFailureException(); - Pumper( EventHandler target ) - { + Pumper(EventHandler target) { this.target = target; } @@ -80,85 +74,65 @@ final class Pumper * and therefore the plugin could be permanently in progress. */ @Override - public void run() - { - while ( !stop.get() || !synchronizer.isEmptyQueue() ) - { - try - { + public void run() { + while (!stop.get() || !synchronizer.isEmptyQueue()) { + try { Event item = synchronizer.awaitNext(); - if ( shouldStopQueueing( item ) ) - { + if (shouldStopQueueing(item)) { break; } - target.handleEvent( item ); - } - catch ( Throwable t ) - { + target.handleEvent(item); + } catch (Throwable t) { // ensure the stack trace to be at the instance of the exception t.getStackTrace(); - errors.addException( t ); + errors.addException(t); } } - isAlive.set( false ); + isAlive.set(false); } - boolean hasErrors() - { + boolean hasErrors() { return errors.hasNestedExceptions(); } - void throwErrors() throws IOException - { + void throwErrors() throws IOException { throw errors; } } - public ThreadedStreamConsumer( EventHandler target ) - { - pumper = new Pumper( target ); - Thread consumer = newDaemonThread( pumper, "ThreadedStreamConsumer" ); - consumer.setUncaughtExceptionHandler( ( t, e ) -> isAlive.set( false ) ); + public ThreadedStreamConsumer(EventHandler target) { + pumper = new Pumper(target); + Thread consumer = newDaemonThread(pumper, "ThreadedStreamConsumer"); + consumer.setUncaughtExceptionHandler((t, e) -> isAlive.set(false)); consumer.start(); this.consumer = consumer; } @Override - public void handleEvent( @Nonnull Event event ) - { + public void handleEvent(@Nonnull Event event) { // Do NOT call Thread.isAlive() - slow. // It makes worse performance from 790 millis to 1250 millis for 5 million messages. - if ( !stop.get() && isAlive.get() ) - { - synchronizer.pushNext( event ); + if (!stop.get() && isAlive.get()) { + synchronizer.pushNext(event); } } @Override - public void close() - throws IOException - { - isAlive.compareAndSet( true, consumer.isAlive() ); - if ( stop.compareAndSet( false, true ) && isAlive.get() ) - { - if ( currentThread().isInterrupted() ) - { + public void close() throws IOException { + isAlive.compareAndSet(true, consumer.isAlive()); + if (stop.compareAndSet(false, true) && isAlive.get()) { + if (currentThread().isInterrupted()) { synchronizer.markStopped(); consumer.interrupt(); - } - else - { + } else { synchronizer.markStopped(); - try - { + try { consumer.join(); - } - catch ( InterruptedException e ) - { + } catch (InterruptedException e) { // we should not set interrupted=true in this Thread // if consumer's Thread was interrupted which is indicated by InterruptedException } @@ -167,8 +141,7 @@ public void close() } } - if ( pumper.hasErrors() ) - { + if (pumper.hasErrors()) { pumper.throwErrors(); } } @@ -179,60 +152,50 @@ public void close() * @param item element from items * @return {@code true} if tail of the queue */ - private static boolean shouldStopQueueing( Event item ) - { + private static boolean shouldStopQueueing(Event item) { return item == END_ITEM; } /** * */ - private static class FinalEvent extends Event - { - FinalEvent() - { - super( null ); + private static class FinalEvent extends Event { + FinalEvent() { + super(null); } @Override - public boolean isControlCategory() - { + public boolean isControlCategory() { return false; } @Override - public boolean isConsoleCategory() - { + public boolean isConsoleCategory() { return false; } @Override - public boolean isConsoleErrorCategory() - { + public boolean isConsoleErrorCategory() { return false; } @Override - public boolean isStandardStreamCategory() - { + public boolean isStandardStreamCategory() { return false; } @Override - public boolean isSysPropCategory() - { + public boolean isSysPropCategory() { return false; } @Override - public boolean isTestCategory() - { + public boolean isTestCategory() { return false; } @Override - public boolean isJvmExitError() - { + public boolean isJvmExitError() { return false; } } @@ -244,8 +207,7 @@ public boolean isJvmExitError() * * @param element type in the queue */ - static class QueueSynchronizer - { + static class QueueSynchronizer { private final SyncT1 t1 = new SyncT1(); private final SyncT2 t2 = new SyncT2(); private final ConcurrentLinkedDeque queue = new ConcurrentLinkedDeque<>(); @@ -253,103 +215,84 @@ static class QueueSynchronizer private final int maxQueueSize; private final T stopItemMarker; - QueueSynchronizer( int maxQueueSize, T stopItemMarker ) - { + QueueSynchronizer(int maxQueueSize, T stopItemMarker) { this.maxQueueSize = maxQueueSize; this.stopItemMarker = stopItemMarker; } - private class SyncT1 extends AbstractQueuedSynchronizer - { + private class SyncT1 extends AbstractQueuedSynchronizer { private static final long serialVersionUID = 1L; @Override - protected int tryAcquireShared( int arg ) - { + protected int tryAcquireShared(int arg) { return queueSize.get() == 0 ? -1 : 1; } @Override - protected boolean tryReleaseShared( int arg ) - { + protected boolean tryReleaseShared(int arg) { return true; } - void waitIfZero() throws InterruptedException - { - acquireSharedInterruptibly( 1 ); + void waitIfZero() throws InterruptedException { + acquireSharedInterruptibly(1); } - void release() - { - releaseShared( 0 ); + void release() { + releaseShared(0); } } - private class SyncT2 extends AbstractQueuedSynchronizer - { + private class SyncT2 extends AbstractQueuedSynchronizer { private static final long serialVersionUID = 1L; @Override - protected int tryAcquireShared( int arg ) - { + protected int tryAcquireShared(int arg) { return queueSize.get() < maxQueueSize ? 1 : -1; } @Override - protected boolean tryReleaseShared( int arg ) - { + protected boolean tryReleaseShared(int arg) { return true; } - void awaitMax() - { - acquireShared( 1 ); + void awaitMax() { + acquireShared(1); } - void tryRelease() - { - if ( queueSize.get() == 0 ) - { - releaseShared( 0 ); + void tryRelease() { + if (queueSize.get() == 0) { + releaseShared(0); } } } - void markStopped() - { - addNext( stopItemMarker ); + void markStopped() { + addNext(stopItemMarker); } - void pushNext( T t ) - { + void pushNext(T t) { t2.awaitMax(); - addNext( t ); + addNext(t); } - T awaitNext() throws InterruptedException - { + T awaitNext() throws InterruptedException { t2.tryRelease(); t1.waitIfZero(); queueSize.decrementAndGet(); return queue.pollFirst(); } - boolean isEmptyQueue() - { + boolean isEmptyQueue() { return queue.isEmpty(); } - void clearQueue() - { + void clearQueue() { queue.clear(); } - private void addNext( T t ) - { - queue.addLast( t ); - if ( queueSize.getAndIncrement() == 0 ) - { + private void addNext(T t) { + queue.addLast(t); + if (queueSize.getAndIncrement() == 0) { t1.release(); } } diff --git a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/extensions/DefaultStatelessReportMojoConfiguration.java b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/extensions/DefaultStatelessReportMojoConfiguration.java index 0eb6b52f9d..f134e24a21 100644 --- a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/extensions/DefaultStatelessReportMojoConfiguration.java +++ b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/extensions/DefaultStatelessReportMojoConfiguration.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire.extensions; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,14 +16,15 @@ * specific language governing permissions and limitations * under the License. */ - -import org.apache.maven.plugin.surefire.report.WrappedReportEntry; -import org.apache.maven.surefire.extensions.StatelessReportMojoConfiguration; +package org.apache.maven.plugin.surefire.extensions; import java.io.File; import java.util.Deque; import java.util.Map; +import org.apache.maven.plugin.surefire.report.WrappedReportEntry; +import org.apache.maven.surefire.extensions.StatelessReportMojoConfiguration; + /** * Why Deprecated: The field {@code testClassMethodRunHistory} makes * {@link org.apache.maven.plugin.surefire.report.StatelessXmlReporter} stateful and overloads reporter by permanently @@ -35,24 +34,21 @@ * {@link org.apache.maven.plugin.surefire.report.TestSetRunListener} keeping it already stateful. */ @Deprecated -public class DefaultStatelessReportMojoConfiguration - extends StatelessReportMojoConfiguration -{ +public class DefaultStatelessReportMojoConfiguration extends StatelessReportMojoConfiguration { private final Map> testClassMethodRunHistory; - public DefaultStatelessReportMojoConfiguration( File reportsDirectory, - String reportNameSuffix, - boolean trimStackTrace, - int rerunFailingTestsCount, - String xsdSchemaLocation, - Map> testClassMethodRunHistory ) - { - super( reportsDirectory, reportNameSuffix, trimStackTrace, rerunFailingTestsCount, xsdSchemaLocation ); + public DefaultStatelessReportMojoConfiguration( + File reportsDirectory, + String reportNameSuffix, + boolean trimStackTrace, + int rerunFailingTestsCount, + String xsdSchemaLocation, + Map> testClassMethodRunHistory) { + super(reportsDirectory, reportNameSuffix, trimStackTrace, rerunFailingTestsCount, xsdSchemaLocation); this.testClassMethodRunHistory = testClassMethodRunHistory; } - public Map> getTestClassMethodRunHistory() - { + public Map> getTestClassMethodRunHistory() { return testClassMethodRunHistory; } } diff --git a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/extensions/EventConsumerThread.java b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/extensions/EventConsumerThread.java index 79d5c85ab1..cac48b67a8 100644 --- a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/extensions/EventConsumerThread.java +++ b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/extensions/EventConsumerThread.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire.extensions; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,15 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.surefire.extensions; + +import javax.annotation.Nonnull; + +import java.io.EOFException; +import java.io.IOException; +import java.io.InterruptedIOException; +import java.nio.channels.ClosedChannelException; +import java.nio.channels.ReadableByteChannel; import org.apache.maven.surefire.api.event.Event; import org.apache.maven.surefire.api.fork.ForkNodeArguments; @@ -27,18 +34,10 @@ import org.apache.maven.surefire.extensions.util.CountdownCloseable; import org.apache.maven.surefire.stream.EventDecoder; -import javax.annotation.Nonnull; -import java.io.EOFException; -import java.io.IOException; -import java.io.InterruptedIOException; -import java.nio.channels.ClosedChannelException; -import java.nio.channels.ReadableByteChannel; - /** * */ -public class EventConsumerThread extends CloseableDaemonThread -{ +public class EventConsumerThread extends CloseableDaemonThread { private final ReadableByteChannel channel; private final EventHandler eventHandler; private final CountdownCloseable countdownCloseable; @@ -46,14 +45,14 @@ public class EventConsumerThread extends CloseableDaemonThread private final ForkNodeArguments arguments; private volatile boolean disabled; - public EventConsumerThread( @Nonnull String threadName, - @Nonnull ReadableByteChannel channel, - @Nonnull EventHandler eventHandler, - @Nonnull CountdownCloseable countdownCloseable, - @Nonnull ForkNodeArguments arguments ) - { - super( threadName ); - decoder = new EventDecoder( channel, arguments ); + public EventConsumerThread( + @Nonnull String threadName, + @Nonnull ReadableByteChannel channel, + @Nonnull EventHandler eventHandler, + @Nonnull CountdownCloseable countdownCloseable, + @Nonnull ForkNodeArguments arguments) { + super(threadName); + decoder = new EventDecoder(channel, arguments); this.channel = channel; this.eventHandler = eventHandler; this.countdownCloseable = countdownCloseable; @@ -61,49 +60,35 @@ public EventConsumerThread( @Nonnull String threadName, } @Override - public void run() - { - try ( ReadableByteChannel stream = channel; - CountdownCloseable c = countdownCloseable; - EventDecoder eventDecoder = decoder ) - { + public void run() { + try (ReadableByteChannel stream = channel; + CountdownCloseable c = countdownCloseable; + EventDecoder eventDecoder = decoder) { Memento memento = eventDecoder.new Memento(); - do - { - Event event = eventDecoder.decode( memento ); - if ( event != null && !disabled ) - { - eventHandler.handleEvent( event ); + do { + Event event = eventDecoder.decode(memento); + if (event != null && !disabled) { + eventHandler.handleEvent(event); } - } - while ( true ); - } - catch ( EOFException | ClosedChannelException e ) - { + } while (true); + } catch (EOFException | ClosedChannelException e) { // - } - catch ( IOException e ) - { - if ( e instanceof InterruptedIOException || e.getCause() instanceof InterruptedException ) - { + } catch (IOException e) { + if (e instanceof InterruptedIOException || e.getCause() instanceof InterruptedException) { Thread.currentThread().interrupt(); - } - else - { - arguments.dumpStreamException( e ); + } else { + arguments.dumpStreamException(e); } } } @Override - public void disable() - { + public void disable() { disabled = true; } @Override - public void close() throws IOException - { + public void close() throws IOException { channel.close(); } } diff --git a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/extensions/InvalidSessionIdException.java b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/extensions/InvalidSessionIdException.java index 30664e239b..1b306832b6 100644 --- a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/extensions/InvalidSessionIdException.java +++ b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/extensions/InvalidSessionIdException.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire.extensions; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,12 +16,13 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.surefire.extensions; + +import java.io.IOException; import org.apache.maven.surefire.extensions.ForkChannel; import org.apache.maven.surefire.extensions.util.CommandlineExecutor; -import java.io.IOException; - /** * After the authentication has failed, {@link ForkChannel#tryConnectToClient()} * throws {@link InvalidSessionIdException} @@ -31,10 +30,8 @@ * * @since 3.0.0-M5 */ -public class InvalidSessionIdException extends IOException -{ - public InvalidSessionIdException( String actualSessionId, String expectedSessionId ) - { - super( "The actual sessionId '" + actualSessionId + "' does not match '" + expectedSessionId + "'." ); +public class InvalidSessionIdException extends IOException { + public InvalidSessionIdException(String actualSessionId, String expectedSessionId) { + super("The actual sessionId '" + actualSessionId + "' does not match '" + expectedSessionId + "'."); } } diff --git a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/extensions/LegacyForkChannel.java b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/extensions/LegacyForkChannel.java index b754535fcb..a6dfe36c51 100644 --- a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/extensions/LegacyForkChannel.java +++ b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/extensions/LegacyForkChannel.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire.extensions; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,19 +16,21 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.surefire.extensions; + +import javax.annotation.Nonnull; + +import java.nio.channels.ReadableByteChannel; +import java.nio.channels.WritableByteChannel; import org.apache.maven.surefire.api.event.Event; +import org.apache.maven.surefire.api.fork.ForkNodeArguments; import org.apache.maven.surefire.extensions.CloseableDaemonThread; import org.apache.maven.surefire.extensions.CommandReader; import org.apache.maven.surefire.extensions.EventHandler; import org.apache.maven.surefire.extensions.ForkChannel; -import org.apache.maven.surefire.api.fork.ForkNodeArguments; import org.apache.maven.surefire.extensions.util.CountdownCloseable; -import javax.annotation.Nonnull; -import java.nio.channels.ReadableByteChannel; -import java.nio.channels.WritableByteChannel; - /** * The main purpose of this class is to bind the * {@link #bindCommandReader(CommandReader, WritableByteChannel) command reader} reading the commands from @@ -39,69 +39,57 @@ * {@link #bindEventHandler(EventHandler, CountdownCloseable, ReadableByteChannel) event handler} deserializing * a received event and sends the event object to the {@link EventHandler event handler}. */ -final class LegacyForkChannel extends ForkChannel -{ +final class LegacyForkChannel extends ForkChannel { private CloseableDaemonThread commandReaderBindings; private CloseableDaemonThread eventHandlerBindings; - LegacyForkChannel( @Nonnull ForkNodeArguments arguments ) - { - super( arguments ); + LegacyForkChannel(@Nonnull ForkNodeArguments arguments) { + super(arguments); } @Override - public void tryConnectToClient() - { - } + public void tryConnectToClient() {} @Override - public String getForkNodeConnectionString() - { + public String getForkNodeConnectionString() { return "pipe://" + getArguments().getForkChannelId(); } @Override - public int getCountdownCloseablePermits() - { + public int getCountdownCloseablePermits() { return 2; } @Override - public void bindCommandReader( @Nonnull CommandReader commands, WritableByteChannel stdIn ) - { + public void bindCommandReader(@Nonnull CommandReader commands, WritableByteChannel stdIn) { ForkNodeArguments args = getArguments(); String threadName = "commands-fork-" + args.getForkChannelId(); - commandReaderBindings = new StreamFeeder( threadName, stdIn, commands, args.getConsoleLogger() ); + commandReaderBindings = new StreamFeeder(threadName, stdIn, commands, args.getConsoleLogger()); commandReaderBindings.start(); } @Override - public void bindEventHandler( @Nonnull EventHandler eventHandler, - @Nonnull CountdownCloseable countdownCloseable, - ReadableByteChannel stdOut ) - { + public void bindEventHandler( + @Nonnull EventHandler eventHandler, + @Nonnull CountdownCloseable countdownCloseable, + ReadableByteChannel stdOut) { ForkNodeArguments args = getArguments(); String threadName = "fork-" + args.getForkChannelId() + "-event-thread"; - eventHandlerBindings = new EventConsumerThread( threadName, stdOut, eventHandler, countdownCloseable, args ); + eventHandlerBindings = new EventConsumerThread(threadName, stdOut, eventHandler, countdownCloseable, args); eventHandlerBindings.start(); } @Override - public void disable() - { - if ( eventHandlerBindings != null ) - { + public void disable() { + if (eventHandlerBindings != null) { eventHandlerBindings.disable(); } - if ( commandReaderBindings != null ) - { + if (commandReaderBindings != null) { commandReaderBindings.disable(); } } @Override - public void close() - { - } + public void close() {} } diff --git a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/extensions/LegacyForkNodeFactory.java b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/extensions/LegacyForkNodeFactory.java index b4d47889cd..651da10d21 100644 --- a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/extensions/LegacyForkNodeFactory.java +++ b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/extensions/LegacyForkNodeFactory.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire.extensions; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,22 +16,21 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.surefire.extensions; + +import javax.annotation.Nonnull; -import org.apache.maven.surefire.extensions.ForkChannel; import org.apache.maven.surefire.api.fork.ForkNodeArguments; +import org.apache.maven.surefire.extensions.ForkChannel; import org.apache.maven.surefire.extensions.ForkNodeFactory; -import javax.annotation.Nonnull; - /** * The factory of {@link LegacyForkChannel}. */ -public class LegacyForkNodeFactory implements ForkNodeFactory -{ +public class LegacyForkNodeFactory implements ForkNodeFactory { @Nonnull @Override - public ForkChannel createForkChannel( @Nonnull ForkNodeArguments arguments ) - { - return new LegacyForkChannel( arguments ); + public ForkChannel createForkChannel(@Nonnull ForkNodeArguments arguments) { + return new LegacyForkChannel(arguments); } } diff --git a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/extensions/StreamFeeder.java b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/extensions/StreamFeeder.java index 0dcf5ef0e0..ef5349d618 100644 --- a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/extensions/StreamFeeder.java +++ b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/extensions/StreamFeeder.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire.extensions; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,19 +16,21 @@ * specific language governing permissions and limitations * under the License. */ - -import org.apache.maven.plugin.surefire.log.api.ConsoleLogger; -import org.apache.maven.surefire.api.booter.Command; -import org.apache.maven.surefire.extensions.CloseableDaemonThread; -import org.apache.maven.surefire.extensions.CommandReader; -import org.apache.maven.surefire.stream.CommandEncoder; +package org.apache.maven.plugin.surefire.extensions; import javax.annotation.Nonnull; + import java.io.IOException; import java.nio.channels.ClosedChannelException; import java.nio.channels.NonWritableChannelException; import java.nio.channels.WritableByteChannel; +import org.apache.maven.plugin.surefire.log.api.ConsoleLogger; +import org.apache.maven.surefire.api.booter.Command; +import org.apache.maven.surefire.extensions.CloseableDaemonThread; +import org.apache.maven.surefire.extensions.CommandReader; +import org.apache.maven.surefire.stream.CommandEncoder; + /** * Commands which are sent from plugin to the forked jvm. *
@@ -44,8 +44,7 @@ * @author Tibor Digana (tibor17) * @since 3.0.0-M5 */ -public class StreamFeeder extends CloseableDaemonThread -{ +public class StreamFeeder extends CloseableDaemonThread { private final WritableByteChannel channel; private final CommandReader commandReader; private final ConsoleLogger logger; @@ -53,29 +52,26 @@ public class StreamFeeder extends CloseableDaemonThread private volatile boolean disabled; private volatile Throwable exception; - public StreamFeeder( @Nonnull String threadName, @Nonnull WritableByteChannel channel, - @Nonnull CommandReader commandReader, @Nonnull ConsoleLogger logger ) - { - super( threadName ); + public StreamFeeder( + @Nonnull String threadName, + @Nonnull WritableByteChannel channel, + @Nonnull CommandReader commandReader, + @Nonnull ConsoleLogger logger) { + super(threadName); this.channel = channel; this.commandReader = commandReader; this.logger = logger; } @Override - @SuppressWarnings( "checkstyle:innerassignment" ) - public void run() - { - try ( CommandEncoder encoder = new CommandEncoder( channel ) ) - { - for ( Command cmd; ( cmd = commandReader.readNextCommand() ) != null; ) - { - if ( !disabled ) - { - switch ( cmd.getCommandType() ) - { + @SuppressWarnings("checkstyle:innerassignment") + public void run() { + try (CommandEncoder encoder = new CommandEncoder(channel)) { + for (Command cmd; (cmd = commandReader.readNextCommand()) != null; ) { + if (!disabled) { + switch (cmd.getCommandType()) { case RUN_CLASS: - encoder.sendRunClass( cmd.getData() ); + encoder.sendRunClass(cmd.getData()); break; case TEST_SET_FINISHED: encoder.sendTestSetFinished(); @@ -84,7 +80,7 @@ public void run() encoder.sendSkipSinceNextTest(); break; case SHUTDOWN: - encoder.sendShutdown( cmd.getData() ); + encoder.sendShutdown(cmd.getData()); break; case NOOP: encoder.sendNoop(); @@ -93,38 +89,29 @@ public void run() encoder.sendByeAck(); break; default: - logger.error( "Unknown enum " + cmd.getCommandType().name() ); + logger.error("Unknown enum " + cmd.getCommandType().name()); } } } - } - catch ( ClosedChannelException e ) - { + } catch (ClosedChannelException e) { // closed externally - } - catch ( IOException | NonWritableChannelException e ) - { + } catch (IOException | NonWritableChannelException e) { exception = e.getCause() == null ? e : e.getCause(); - } - catch ( IllegalArgumentException e ) - { - logger.error( e.getLocalizedMessage() ); + } catch (IllegalArgumentException e) { + logger.error(e.getLocalizedMessage()); } } - public void disable() - { + public void disable() { disabled = true; } - public Throwable getException() - { + public Throwable getException() { return exception; } @Override - public void close() throws IOException - { + public void close() throws IOException { channel.close(); } } diff --git a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/extensions/SurefireConsoleOutputReporter.java b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/extensions/SurefireConsoleOutputReporter.java index d339f27a3a..180bc8de25 100644 --- a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/extensions/SurefireConsoleOutputReporter.java +++ b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/extensions/SurefireConsoleOutputReporter.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire.extensions; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,15 +16,16 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.surefire.extensions; + +import java.io.File; +import java.io.PrintStream; import org.apache.maven.plugin.surefire.report.ConsoleOutputFileReporter; import org.apache.maven.plugin.surefire.report.DirectConsoleOutput; +import org.apache.maven.surefire.api.util.ReflectionUtils; import org.apache.maven.surefire.extensions.ConsoleOutputReportEventListener; import org.apache.maven.surefire.extensions.ConsoleOutputReporter; -import org.apache.maven.surefire.api.util.ReflectionUtils; - -import java.io.File; -import java.io.PrintStream; /** * Default implementation for extension of console logger. @@ -38,49 +37,35 @@ * @author Tibor Digana (tibor17) * @since 3.0.0-M4 */ -public class SurefireConsoleOutputReporter - extends ConsoleOutputReporter -{ +public class SurefireConsoleOutputReporter extends ConsoleOutputReporter { @Override - public ConsoleOutputReportEventListener createListener( File reportsDirectory, String reportNameSuffix, - Integer forkNumber ) - { - return new ConsoleOutputFileReporter( reportsDirectory, reportNameSuffix, false, forkNumber, getEncoding() ); + public ConsoleOutputReportEventListener createListener( + File reportsDirectory, String reportNameSuffix, Integer forkNumber) { + return new ConsoleOutputFileReporter(reportsDirectory, reportNameSuffix, false, forkNumber, getEncoding()); } @Override - public ConsoleOutputReportEventListener createListener( PrintStream out, PrintStream err ) - { - return new DirectConsoleOutput( out, err ); + public ConsoleOutputReportEventListener createListener(PrintStream out, PrintStream err) { + return new DirectConsoleOutput(out, err); } @Override - public Object clone( ClassLoader target ) - { - try - { - Class cls = ReflectionUtils.reloadClass( target, this ); + public Object clone(ClassLoader target) { + try { + Class cls = ReflectionUtils.reloadClass(target, this); Object clone = cls.newInstance(); - cls.getMethod( "setDisable", boolean.class ) - .invoke( clone, isDisable() ); - cls.getMethod( "setEncoding", String.class ) - .invoke( clone, getEncoding() ); + cls.getMethod("setDisable", boolean.class).invoke(clone, isDisable()); + cls.getMethod("setEncoding", String.class).invoke(clone, getEncoding()); return clone; - } - catch ( ReflectiveOperationException e ) - { - throw new IllegalStateException( e.getLocalizedMessage() ); + } catch (ReflectiveOperationException e) { + throw new IllegalStateException(e.getLocalizedMessage()); } } @Override - public String toString() - { - return "SurefireConsoleOutputReporter{" - + "disable=" + isDisable() - + ", encoding=" + getEncoding() - + '}'; + public String toString() { + return "SurefireConsoleOutputReporter{" + "disable=" + isDisable() + ", encoding=" + getEncoding() + '}'; } } diff --git a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/extensions/SurefireForkChannel.java b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/extensions/SurefireForkChannel.java index f0c5bbfef1..99e6e0304b 100644 --- a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/extensions/SurefireForkChannel.java +++ b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/extensions/SurefireForkChannel.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire.extensions; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,19 +16,10 @@ * specific language governing permissions and limitations * under the License. */ - -import org.apache.maven.plugin.surefire.booterclient.output.NativeStdOutStreamConsumer; -import org.apache.maven.surefire.api.event.Event; -import org.apache.maven.surefire.api.fork.ForkNodeArguments; -import org.apache.maven.surefire.extensions.CloseableDaemonThread; -import org.apache.maven.surefire.extensions.CommandReader; -import org.apache.maven.surefire.extensions.EventHandler; -import org.apache.maven.surefire.extensions.ForkChannel; -import org.apache.maven.surefire.extensions.util.CountDownLauncher; -import org.apache.maven.surefire.extensions.util.CountdownCloseable; -import org.apache.maven.surefire.extensions.util.LineConsumerThread; +package org.apache.maven.plugin.surefire.extensions; import javax.annotation.Nonnull; + import java.io.Closeable; import java.io.IOException; import java.net.InetAddress; @@ -47,6 +36,17 @@ import java.util.concurrent.Executors; import java.util.concurrent.Future; +import org.apache.maven.plugin.surefire.booterclient.output.NativeStdOutStreamConsumer; +import org.apache.maven.surefire.api.event.Event; +import org.apache.maven.surefire.api.fork.ForkNodeArguments; +import org.apache.maven.surefire.extensions.CloseableDaemonThread; +import org.apache.maven.surefire.extensions.CommandReader; +import org.apache.maven.surefire.extensions.EventHandler; +import org.apache.maven.surefire.extensions.ForkChannel; +import org.apache.maven.surefire.extensions.util.CountDownLauncher; +import org.apache.maven.surefire.extensions.util.CountdownCloseable; +import org.apache.maven.surefire.extensions.util.LineConsumerThread; + import static java.net.StandardSocketOptions.SO_KEEPALIVE; import static java.net.StandardSocketOptions.SO_REUSEADDR; import static java.net.StandardSocketOptions.TCP_NODELAY; @@ -75,15 +75,14 @@ *
* The channel is closed after the forked JVM has finished normally or the shutdown hook is executed in the plugin. */ -final class SurefireForkChannel extends ForkChannel -{ - private static final ExecutorService THREAD_POOL = Executors.newCachedThreadPool( newDaemonThreadFactory() ); +final class SurefireForkChannel extends ForkChannel { + private static final ExecutorService THREAD_POOL = Executors.newCachedThreadPool(newDaemonThreadFactory()); private final AsynchronousServerSocketChannel server; private final String localHost; private final int localPort; private final String sessionId; - private final Bindings bindings = new Bindings( 2 ); + private final Bindings bindings = new Bindings(2); private volatile Future session; private volatile LineConsumerThread out; private volatile CloseableDaemonThread commandReaderBindings; @@ -91,13 +90,12 @@ final class SurefireForkChannel extends ForkChannel private volatile EventBindings eventBindings; private volatile CommandBindings commandBindings; - SurefireForkChannel( @Nonnull ForkNodeArguments arguments ) throws IOException - { - super( arguments ); - server = open( withThreadPool( THREAD_POOL ) ); - setTrueOptions( SO_REUSEADDR, TCP_NODELAY, SO_KEEPALIVE ); + SurefireForkChannel(@Nonnull ForkNodeArguments arguments) throws IOException { + super(arguments); + server = open(withThreadPool(THREAD_POOL)); + setTrueOptions(SO_REUSEADDR, TCP_NODELAY, SO_KEEPALIVE); InetAddress ip = InetAddress.getLoopbackAddress(); - server.bind( new InetSocketAddress( ip, 0 ), 1 ); + server.bind(new InetSocketAddress(ip, 0), 1); InetSocketAddress localAddress = (InetSocketAddress) server.getLocalAddress(); localHost = localAddress.getHostString(); localPort = localAddress.getPort(); @@ -105,198 +103,165 @@ final class SurefireForkChannel extends ForkChannel } @Override - public void tryConnectToClient() - { - if ( session != null ) - { - throw new IllegalStateException( "already accepted TCP client connection" ); + public void tryConnectToClient() { + if (session != null) { + throw new IllegalStateException("already accepted TCP client connection"); } session = server.accept(); } @Override - public String getForkNodeConnectionString() - { - return "tcp://" + localHost + ":" + localPort + ( isBlank( sessionId ) ? "" : "?sessionId=" + sessionId ); + public String getForkNodeConnectionString() { + return "tcp://" + localHost + ":" + localPort + (isBlank(sessionId) ? "" : "?sessionId=" + sessionId); } @Override - public int getCountdownCloseablePermits() - { + public int getCountdownCloseablePermits() { return 3; } @Override - public void bindCommandReader( @Nonnull CommandReader commands, WritableByteChannel stdIn ) - throws IOException, InterruptedException - { - commandBindings = new CommandBindings( commands ); + public void bindCommandReader(@Nonnull CommandReader commands, WritableByteChannel stdIn) + throws IOException, InterruptedException { + commandBindings = new CommandBindings(commands); bindings.countDown(); } @Override - public void bindEventHandler( @Nonnull EventHandler eventHandler, - @Nonnull CountdownCloseable countdown, - ReadableByteChannel stdOut ) - throws IOException, InterruptedException - { + public void bindEventHandler( + @Nonnull EventHandler eventHandler, + @Nonnull CountdownCloseable countdown, + ReadableByteChannel stdOut) + throws IOException, InterruptedException { ForkNodeArguments args = getArguments(); - out = new LineConsumerThread( "fork-" + args.getForkChannelId() + "-out-thread", stdOut, - new NativeStdOutStreamConsumer( args.getConsoleLock() ), countdown ); + out = new LineConsumerThread( + "fork-" + args.getForkChannelId() + "-out-thread", + stdOut, + new NativeStdOutStreamConsumer(args.getConsoleLock()), + countdown); out.start(); - eventBindings = new EventBindings( eventHandler, countdown ); + eventBindings = new EventBindings(eventHandler, countdown); bindings.countDown(); } @Override - public void disable() - { - if ( eventHandlerBindings != null ) - { + public void disable() { + if (eventHandlerBindings != null) { eventHandlerBindings.disable(); } - if ( commandReaderBindings != null ) - { + if (commandReaderBindings != null) { commandReaderBindings.disable(); } } @Override - public void close() throws IOException - { + public void close() throws IOException { //noinspection unused,EmptyTryBlock,EmptyTryBlock - try ( Closeable c1 = getChannel(); Closeable c2 = server; Closeable c3 = out ) - { + try (Closeable c1 = getChannel(); + Closeable c2 = server; + Closeable c3 = out) { // only close all channels - } - catch ( InterruptedException e ) - { + } catch (InterruptedException e) { Throwable cause = e.getCause(); - throw cause instanceof IOException ? (IOException) cause : new IOException( cause ); + throw cause instanceof IOException ? (IOException) cause : new IOException(cause); } } - private void verifySessionId() throws InterruptedException, IOException - { - try - { - ByteBuffer buffer = ByteBuffer.allocate( sessionId.length() ); + private void verifySessionId() throws InterruptedException, IOException { + try { + ByteBuffer buffer = ByteBuffer.allocate(sessionId.length()); int read; - do - { - read = getChannel().read( buffer ).get(); - } while ( read != -1 && buffer.hasRemaining() ); + do { + read = getChannel().read(buffer).get(); + } while (read != -1 && buffer.hasRemaining()); - if ( read == -1 ) - { - throw new IOException( "Channel closed while verifying the client." ); + if (read == -1) { + throw new IOException("Channel closed while verifying the client."); } - ( (Buffer) buffer ).flip(); - String clientSessionId = new String( buffer.array(), US_ASCII ); - if ( !clientSessionId.equals( sessionId ) ) - { - throw new InvalidSessionIdException( clientSessionId, sessionId ); + ((Buffer) buffer).flip(); + String clientSessionId = new String(buffer.array(), US_ASCII); + if (!clientSessionId.equals(sessionId)) { + throw new InvalidSessionIdException(clientSessionId, sessionId); } - } - catch ( ExecutionException e ) - { + } catch (ExecutionException e) { Throwable cause = e.getCause(); - throw cause instanceof IOException ? (IOException) cause : new IOException( cause ); + throw cause instanceof IOException ? (IOException) cause : new IOException(cause); } } @SafeVarargs - private final void setTrueOptions( SocketOption... options ) - throws IOException - { - for ( SocketOption option : options ) - { - if ( server.supportedOptions().contains( option ) ) - { - server.setOption( option, true ); + private final void setTrueOptions(SocketOption... options) throws IOException { + for (SocketOption option : options) { + if (server.supportedOptions().contains(option)) { + server.setOption(option, true); } } } - private class EventBindings - { + private class EventBindings { private final EventHandler eventHandler; private final CountdownCloseable countdown; - private EventBindings( EventHandler eventHandler, CountdownCloseable countdown ) - { + private EventBindings(EventHandler eventHandler, CountdownCloseable countdown) { this.eventHandler = eventHandler; this.countdown = countdown; } - void bindEventHandler( AsynchronousSocketChannel source ) - { + void bindEventHandler(AsynchronousSocketChannel source) { ForkNodeArguments args = getArguments(); String threadName = "fork-" + args.getForkChannelId() + "-event-thread"; - ReadableByteChannel channel = newBufferedChannel( newInputStream( source ) ); - eventHandlerBindings = new EventConsumerThread( threadName, channel, eventHandler, countdown, args ); + ReadableByteChannel channel = newBufferedChannel(newInputStream(source)); + eventHandlerBindings = new EventConsumerThread(threadName, channel, eventHandler, countdown, args); eventHandlerBindings.start(); } } - private class CommandBindings - { + private class CommandBindings { private final CommandReader commands; - private CommandBindings( CommandReader commands ) - { + private CommandBindings(CommandReader commands) { this.commands = commands; } - void bindCommandSender( AsynchronousSocketChannel source ) - { + void bindCommandSender(AsynchronousSocketChannel source) { // don't use newBufferedChannel here - may cause the command is not sent and the JVM hangs // only newChannel flushes the message // newBufferedChannel does not flush ForkNodeArguments args = getArguments(); - WritableByteChannel channel = newChannel( newOutputStream( source ) ); + WritableByteChannel channel = newChannel(newOutputStream(source)); String threadName = "commands-fork-" + args.getForkChannelId(); - commandReaderBindings = new StreamFeeder( threadName, channel, commands, args.getConsoleLogger() ); + commandReaderBindings = new StreamFeeder(threadName, channel, commands, args.getConsoleLogger()); commandReaderBindings.start(); } } - private class Bindings extends CountDownLauncher - { - private Bindings( int count ) - { - super( count ); + private class Bindings extends CountDownLauncher { + private Bindings(int count) { + super(count); } @Override - protected void job() throws IOException, InterruptedException - { + protected void job() throws IOException, InterruptedException { AsynchronousSocketChannel channel = getChannel(); - if ( isNotBlank( sessionId ) ) - { + if (isNotBlank(sessionId)) { verifySessionId(); } - eventBindings.bindEventHandler( channel ); - commandBindings.bindCommandSender( channel ); + eventBindings.bindEventHandler(channel); + commandBindings.bindCommandSender(channel); } } - private AsynchronousSocketChannel getChannel() - throws InterruptedException, IOException - { - try - { + private AsynchronousSocketChannel getChannel() throws InterruptedException, IOException { + try { return session == null ? null : session.get(); - } - catch ( ExecutionException e ) - { + } catch (ExecutionException e) { Throwable cause = e.getCause(); - throw cause instanceof IOException ? (IOException) cause : new IOException( cause ); + throw cause instanceof IOException ? (IOException) cause : new IOException(cause); } } } diff --git a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/extensions/SurefireForkNodeFactory.java b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/extensions/SurefireForkNodeFactory.java index f9c6d71f91..8637eae812 100644 --- a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/extensions/SurefireForkNodeFactory.java +++ b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/extensions/SurefireForkNodeFactory.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire.extensions; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,24 +16,23 @@ * specific language governing permissions and limitations * under the License. */ - -import org.apache.maven.surefire.extensions.ForkChannel; -import org.apache.maven.surefire.api.fork.ForkNodeArguments; -import org.apache.maven.surefire.extensions.ForkNodeFactory; +package org.apache.maven.plugin.surefire.extensions; import javax.annotation.Nonnull; + import java.io.IOException; +import org.apache.maven.surefire.api.fork.ForkNodeArguments; +import org.apache.maven.surefire.extensions.ForkChannel; +import org.apache.maven.surefire.extensions.ForkNodeFactory; + /** * The factory of {@link SurefireForkChannel}. */ -public class SurefireForkNodeFactory implements ForkNodeFactory -{ +public class SurefireForkNodeFactory implements ForkNodeFactory { @Nonnull @Override - public ForkChannel createForkChannel( @Nonnull ForkNodeArguments arguments ) - throws IOException - { - return new SurefireForkChannel( arguments ); + public ForkChannel createForkChannel(@Nonnull ForkNodeArguments arguments) throws IOException { + return new SurefireForkChannel(arguments); } } diff --git a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/extensions/SurefireStatelessReporter.java b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/extensions/SurefireStatelessReporter.java index f8c5bd6397..7e73432fb6 100644 --- a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/extensions/SurefireStatelessReporter.java +++ b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/extensions/SurefireStatelessReporter.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire.extensions; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,13 +16,14 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.surefire.extensions; import org.apache.maven.plugin.surefire.report.StatelessXmlReporter; import org.apache.maven.plugin.surefire.report.TestSetStats; import org.apache.maven.plugin.surefire.report.WrappedReportEntry; +import org.apache.maven.surefire.api.util.ReflectionUtils; import org.apache.maven.surefire.extensions.StatelessReportEventListener; import org.apache.maven.surefire.extensions.StatelessReporter; -import org.apache.maven.surefire.api.util.ReflectionUtils; /** * Default implementation for extension of {@link StatelessXmlReporter} in plugin. @@ -37,14 +36,12 @@ * @since 3.0.0-M4 */ public class SurefireStatelessReporter - extends StatelessReporter -{ + extends StatelessReporter { /** * Activated in the injection point of MOJO. */ - public SurefireStatelessReporter() - { - this( false, "3.0" ); + public SurefireStatelessReporter() { + this(false, "3.0"); } /** @@ -52,17 +49,16 @@ public SurefireStatelessReporter() * @param disable {@code true} to disable performing the report * @param version (xsd 3.0) version of the schema */ - public SurefireStatelessReporter( boolean disable, String version ) - { - setDisable( disable ); - setVersion( version ); + public SurefireStatelessReporter(boolean disable, String version) { + setDisable(disable); + setVersion(version); } @Override public StatelessReportEventListener createListener( - DefaultStatelessReportMojoConfiguration configuration ) - { - return new StatelessXmlReporter( configuration.getReportsDirectory(), + DefaultStatelessReportMojoConfiguration configuration) { + return new StatelessXmlReporter( + configuration.getReportsDirectory(), configuration.getReportNameSuffix(), configuration.isTrimStackTrace(), configuration.getRerunFailingTestsCount(), @@ -72,27 +68,21 @@ public StatelessReportEventListener createList false, false, false, - false ); + false); } @Override - public Object clone( ClassLoader target ) - { - try - { - Class cls = ReflectionUtils.reloadClass( target, this ); + public Object clone(ClassLoader target) { + try { + Class cls = ReflectionUtils.reloadClass(target, this); Object clone = cls.newInstance(); - cls.getMethod( "setDisable", boolean.class ) - .invoke( clone, isDisable() ); - cls.getMethod( "setVersion", String.class ) - .invoke( clone, getVersion() ); + cls.getMethod("setDisable", boolean.class).invoke(clone, isDisable()); + cls.getMethod("setVersion", String.class).invoke(clone, getVersion()); return clone; - } - catch ( ReflectiveOperationException e ) - { - throw new IllegalStateException( e.getLocalizedMessage() ); + } catch (ReflectiveOperationException e) { + throw new IllegalStateException(e.getLocalizedMessage()); } } } diff --git a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/extensions/SurefireStatelessTestsetInfoReporter.java b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/extensions/SurefireStatelessTestsetInfoReporter.java index 2fb5bf7d9c..c9acec1f20 100644 --- a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/extensions/SurefireStatelessTestsetInfoReporter.java +++ b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/extensions/SurefireStatelessTestsetInfoReporter.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire.extensions; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,19 +16,20 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.surefire.extensions; + +import java.io.File; +import java.nio.charset.Charset; import org.apache.maven.plugin.surefire.log.api.ConsoleLogger; import org.apache.maven.plugin.surefire.report.ConsoleReporter; import org.apache.maven.plugin.surefire.report.FileReporter; import org.apache.maven.plugin.surefire.report.TestSetStats; import org.apache.maven.plugin.surefire.report.WrappedReportEntry; +import org.apache.maven.surefire.api.util.ReflectionUtils; import org.apache.maven.surefire.extensions.StatelessTestsetInfoConsoleReportEventListener; import org.apache.maven.surefire.extensions.StatelessTestsetInfoFileReportEventListener; import org.apache.maven.surefire.extensions.StatelessTestsetInfoReporter; -import org.apache.maven.surefire.api.util.ReflectionUtils; - -import java.io.File; -import java.nio.charset.Charset; /** * Default implementation for extension of @@ -44,44 +43,35 @@ * @since 3.0.0-M4 */ public class SurefireStatelessTestsetInfoReporter - extends StatelessTestsetInfoReporter -{ + extends StatelessTestsetInfoReporter { @Override public StatelessTestsetInfoConsoleReportEventListener createListener( - ConsoleLogger logger ) - { - return new ConsoleReporter( logger, false, false ); + ConsoleLogger logger) { + return new ConsoleReporter(logger, false, false); } @Override public StatelessTestsetInfoFileReportEventListener createListener( - File reportsDirectory, String reportNameSuffix, Charset encoding ) - { - return new FileReporter( reportsDirectory, reportNameSuffix, encoding, false, false, false ); + File reportsDirectory, String reportNameSuffix, Charset encoding) { + return new FileReporter(reportsDirectory, reportNameSuffix, encoding, false, false, false); } @Override - public Object clone( ClassLoader target ) - { - try - { - Class cls = ReflectionUtils.reloadClass( target, this ); + public Object clone(ClassLoader target) { + try { + Class cls = ReflectionUtils.reloadClass(target, this); Object clone = cls.newInstance(); - cls.getMethod( "setDisable", boolean.class ) - .invoke( clone, isDisable() ); + cls.getMethod("setDisable", boolean.class).invoke(clone, isDisable()); return clone; - } - catch ( ReflectiveOperationException e ) - { - throw new IllegalStateException( e.getLocalizedMessage() ); + } catch (ReflectiveOperationException e) { + throw new IllegalStateException(e.getLocalizedMessage()); } } @Override - public String toString() - { + public String toString() { return "SurefireStatelessTestsetInfoReporter{disable=" + isDisable() + "}"; } } diff --git a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/extensions/junit5/JUnit5ConsoleOutputReporter.java b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/extensions/junit5/JUnit5ConsoleOutputReporter.java index 3d8e8b0165..a5290eab1e 100644 --- a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/extensions/junit5/JUnit5ConsoleOutputReporter.java +++ b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/extensions/junit5/JUnit5ConsoleOutputReporter.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire.extensions.junit5; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,13 +16,14 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.surefire.extensions.junit5; + +import java.io.File; import org.apache.maven.plugin.surefire.extensions.SurefireConsoleOutputReporter; import org.apache.maven.plugin.surefire.report.ConsoleOutputFileReporter; import org.apache.maven.surefire.extensions.ConsoleOutputReportEventListener; -import java.io.File; - /** * The extension of {@link ConsoleOutputReportEventListener logger} for JUnit5. * Selectively enables report files upon JUnit5 annotation DisplayName. @@ -32,9 +31,7 @@ * author Tibor Digana (tibor17) * @since 3.0.0-M4 */ -public class JUnit5ConsoleOutputReporter - extends SurefireConsoleOutputReporter -{ +public class JUnit5ConsoleOutputReporter extends SurefireConsoleOutputReporter { /** * {@code false} by default. *
@@ -42,46 +39,37 @@ public class JUnit5ConsoleOutputReporter */ private boolean usePhrasedFileName; - public boolean isUsePhrasedFileName() - { + public boolean isUsePhrasedFileName() { return usePhrasedFileName; } - public void setUsePhrasedFileName( boolean usePhrasedFileName ) - { + public void setUsePhrasedFileName(boolean usePhrasedFileName) { this.usePhrasedFileName = usePhrasedFileName; } @Override - public ConsoleOutputReportEventListener createListener( File reportsDirectory, String reportNameSuffix, - Integer forkNumber ) - { - return new ConsoleOutputFileReporter( reportsDirectory, reportNameSuffix, isUsePhrasedFileName(), forkNumber, - getEncoding() ); + public ConsoleOutputReportEventListener createListener( + File reportsDirectory, String reportNameSuffix, Integer forkNumber) { + return new ConsoleOutputFileReporter( + reportsDirectory, reportNameSuffix, isUsePhrasedFileName(), forkNumber, getEncoding()); } @Override - public Object clone( ClassLoader target ) - { - try - { - Object clone = super.clone( target ); + public Object clone(ClassLoader target) { + try { + Object clone = super.clone(target); Class cls = clone.getClass(); - cls.getMethod( "setUsePhrasedFileName", boolean.class ) - .invoke( clone, isUsePhrasedFileName() ); + cls.getMethod("setUsePhrasedFileName", boolean.class).invoke(clone, isUsePhrasedFileName()); return clone; - } - catch ( ReflectiveOperationException e ) - { - throw new IllegalStateException( e.getLocalizedMessage() ); + } catch (ReflectiveOperationException e) { + throw new IllegalStateException(e.getLocalizedMessage()); } } @Override - public String toString() - { + public String toString() { return "JUnit5ConsoleOutputReporter{" + "disable=" + isDisable() + ", encoding=" + getEncoding() diff --git a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/extensions/junit5/JUnit5StatelessTestsetInfoReporter.java b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/extensions/junit5/JUnit5StatelessTestsetInfoReporter.java index 3c1b76ba52..ef44a77553 100644 --- a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/extensions/junit5/JUnit5StatelessTestsetInfoReporter.java +++ b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/extensions/junit5/JUnit5StatelessTestsetInfoReporter.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire.extensions.junit5; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,10 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.surefire.extensions.junit5; + +import java.io.File; +import java.nio.charset.Charset; import org.apache.maven.plugin.surefire.extensions.SurefireStatelessTestsetInfoReporter; import org.apache.maven.plugin.surefire.log.api.ConsoleLogger; @@ -28,9 +30,6 @@ import org.apache.maven.surefire.extensions.StatelessTestsetInfoConsoleReportEventListener; import org.apache.maven.surefire.extensions.StatelessTestsetInfoFileReportEventListener; -import java.io.File; -import java.nio.charset.Charset; - /** * Extension of {@link StatelessTestsetInfoConsoleReportEventListener file and console reporter of test-set} for JUnit5. * Signatures can be changed between major, minor versions or milestones. @@ -38,9 +37,7 @@ * @author Tibor Digana (tibor17) * @since 3.0.0-M4 */ -public class JUnit5StatelessTestsetInfoReporter - extends SurefireStatelessTestsetInfoReporter -{ +public class JUnit5StatelessTestsetInfoReporter extends SurefireStatelessTestsetInfoReporter { /** * {@code false} by default. *
@@ -66,78 +63,67 @@ public class JUnit5StatelessTestsetInfoReporter */ private boolean usePhrasedClassNameInTestCaseSummary; - public boolean isUsePhrasedFileName() - { + public boolean isUsePhrasedFileName() { return usePhrasedFileName; } - public void setUsePhrasedFileName( boolean usePhrasedFileName ) - { + public void setUsePhrasedFileName(boolean usePhrasedFileName) { this.usePhrasedFileName = usePhrasedFileName; } - public boolean isUsePhrasedClassNameInRunning() - { + public boolean isUsePhrasedClassNameInRunning() { return usePhrasedClassNameInRunning; } - public void setUsePhrasedClassNameInRunning( boolean usePhrasedClassNameInRunning ) - { + public void setUsePhrasedClassNameInRunning(boolean usePhrasedClassNameInRunning) { this.usePhrasedClassNameInRunning = usePhrasedClassNameInRunning; } - public boolean isUsePhrasedClassNameInTestCaseSummary() - { + public boolean isUsePhrasedClassNameInTestCaseSummary() { return usePhrasedClassNameInTestCaseSummary; } - public void setUsePhrasedClassNameInTestCaseSummary( boolean usePhrasedClassNameInTestCaseSummary ) - { + public void setUsePhrasedClassNameInTestCaseSummary(boolean usePhrasedClassNameInTestCaseSummary) { this.usePhrasedClassNameInTestCaseSummary = usePhrasedClassNameInTestCaseSummary; } @Override public StatelessTestsetInfoConsoleReportEventListener createListener( - ConsoleLogger logger ) - { - return new ConsoleReporter( logger, isUsePhrasedClassNameInRunning(), - isUsePhrasedClassNameInTestCaseSummary() ); + ConsoleLogger logger) { + return new ConsoleReporter(logger, isUsePhrasedClassNameInRunning(), isUsePhrasedClassNameInTestCaseSummary()); } @Override public StatelessTestsetInfoFileReportEventListener createListener( - File reportsDirectory, String reportNameSuffix, Charset encoding ) - { - return new FileReporter( reportsDirectory, reportNameSuffix, encoding, isUsePhrasedFileName(), - isUsePhrasedClassNameInRunning(), isUsePhrasedClassNameInTestCaseSummary() ); + File reportsDirectory, String reportNameSuffix, Charset encoding) { + return new FileReporter( + reportsDirectory, + reportNameSuffix, + encoding, + isUsePhrasedFileName(), + isUsePhrasedClassNameInRunning(), + isUsePhrasedClassNameInTestCaseSummary()); } @Override - public Object clone( ClassLoader target ) - { - try - { - Object clone = super.clone( target ); + public Object clone(ClassLoader target) { + try { + Object clone = super.clone(target); Class cls = clone.getClass(); - cls.getMethod( "setUsePhrasedFileName", boolean.class ) - .invoke( clone, isUsePhrasedFileName() ); - cls.getMethod( "setUsePhrasedClassNameInTestCaseSummary", boolean.class ) - .invoke( clone, isUsePhrasedFileName() ); - cls.getMethod( "setUsePhrasedClassNameInRunning", boolean.class ) - .invoke( clone, isUsePhrasedFileName() ); + cls.getMethod("setUsePhrasedFileName", boolean.class).invoke(clone, isUsePhrasedFileName()); + cls.getMethod("setUsePhrasedClassNameInTestCaseSummary", boolean.class) + .invoke(clone, isUsePhrasedFileName()); + cls.getMethod("setUsePhrasedClassNameInRunning", boolean.class).invoke(clone, isUsePhrasedFileName()); return clone; - } - catch ( ReflectiveOperationException e ) - { - throw new IllegalStateException( e.getLocalizedMessage() ); + } catch (ReflectiveOperationException e) { + throw new IllegalStateException(e.getLocalizedMessage()); } } @Override - public String toString() - { + public String toString() { return "JUnit5StatelessTestsetInfoReporter{" + "disable=" + isDisable() + ", usePhrasedFileName=" + isUsePhrasedFileName() diff --git a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/extensions/junit5/JUnit5Xml30StatelessReporter.java b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/extensions/junit5/JUnit5Xml30StatelessReporter.java index cc45d5a743..91182c5650 100644 --- a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/extensions/junit5/JUnit5Xml30StatelessReporter.java +++ b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/extensions/junit5/JUnit5Xml30StatelessReporter.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire.extensions.junit5; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.surefire.extensions.junit5; import org.apache.maven.plugin.surefire.extensions.DefaultStatelessReportMojoConfiguration; import org.apache.maven.plugin.surefire.extensions.SurefireStatelessReporter; @@ -33,9 +32,7 @@ * author Tibor Digana (tibor17) * @since 3.0.0-M4 */ -public class JUnit5Xml30StatelessReporter - extends SurefireStatelessReporter -{ +public class JUnit5Xml30StatelessReporter extends SurefireStatelessReporter { /** * {@code false} by default. *
@@ -64,51 +61,43 @@ public class JUnit5Xml30StatelessReporter */ private boolean usePhrasedTestCaseMethodName; - public boolean getUsePhrasedFileName() - { + public boolean getUsePhrasedFileName() { return usePhrasedFileName; } - public void setUsePhrasedFileName( boolean usePhrasedFileName ) - { + public void setUsePhrasedFileName(boolean usePhrasedFileName) { this.usePhrasedFileName = usePhrasedFileName; } - public boolean getUsePhrasedTestSuiteClassName() - { + public boolean getUsePhrasedTestSuiteClassName() { return usePhrasedTestSuiteClassName; } - public void setUsePhrasedTestSuiteClassName( boolean usePhrasedTestSuiteClassName ) - { + public void setUsePhrasedTestSuiteClassName(boolean usePhrasedTestSuiteClassName) { this.usePhrasedTestSuiteClassName = usePhrasedTestSuiteClassName; } - public boolean getUsePhrasedTestCaseClassName() - { + public boolean getUsePhrasedTestCaseClassName() { return usePhrasedTestCaseClassName; } - public void setUsePhrasedTestCaseClassName( boolean usePhrasedTestCaseClassName ) - { + public void setUsePhrasedTestCaseClassName(boolean usePhrasedTestCaseClassName) { this.usePhrasedTestCaseClassName = usePhrasedTestCaseClassName; } - public boolean getUsePhrasedTestCaseMethodName() - { + public boolean getUsePhrasedTestCaseMethodName() { return usePhrasedTestCaseMethodName; } - public void setUsePhrasedTestCaseMethodName( boolean usePhrasedTestCaseMethodName ) - { + public void setUsePhrasedTestCaseMethodName(boolean usePhrasedTestCaseMethodName) { this.usePhrasedTestCaseMethodName = usePhrasedTestCaseMethodName; } @Override public StatelessReportEventListener createListener( - DefaultStatelessReportMojoConfiguration configuration ) - { - return new StatelessXmlReporter( configuration.getReportsDirectory(), + DefaultStatelessReportMojoConfiguration configuration) { + return new StatelessXmlReporter( + configuration.getReportsDirectory(), configuration.getReportNameSuffix(), configuration.isTrimStackTrace(), configuration.getRerunFailingTestsCount(), @@ -118,37 +107,31 @@ public StatelessReportEventListener createList getUsePhrasedFileName(), getUsePhrasedTestSuiteClassName(), getUsePhrasedTestCaseClassName(), - getUsePhrasedTestCaseMethodName() ); + getUsePhrasedTestCaseMethodName()); } @Override - public Object clone( ClassLoader target ) - { - try - { - Object clone = super.clone( target ); + public Object clone(ClassLoader target) { + try { + Object clone = super.clone(target); Class cls = clone.getClass(); - cls.getMethod( "setUsePhrasedFileName", boolean.class ) - .invoke( clone, getUsePhrasedFileName() ); - cls.getMethod( "setUsePhrasedTestSuiteClassName", boolean.class ) - .invoke( clone, getUsePhrasedTestSuiteClassName() ); - cls.getMethod( "setUsePhrasedTestCaseClassName", boolean.class ) - .invoke( clone, getUsePhrasedTestCaseClassName() ); - cls.getMethod( "setUsePhrasedTestCaseMethodName", boolean.class ) - .invoke( clone, getUsePhrasedTestCaseMethodName() ); + cls.getMethod("setUsePhrasedFileName", boolean.class).invoke(clone, getUsePhrasedFileName()); + cls.getMethod("setUsePhrasedTestSuiteClassName", boolean.class) + .invoke(clone, getUsePhrasedTestSuiteClassName()); + cls.getMethod("setUsePhrasedTestCaseClassName", boolean.class) + .invoke(clone, getUsePhrasedTestCaseClassName()); + cls.getMethod("setUsePhrasedTestCaseMethodName", boolean.class) + .invoke(clone, getUsePhrasedTestCaseMethodName()); return clone; - } - catch ( ReflectiveOperationException e ) - { - throw new IllegalStateException( e.getLocalizedMessage() ); + } catch (ReflectiveOperationException e) { + throw new IllegalStateException(e.getLocalizedMessage()); } } @Override - public String toString() - { + public String toString() { return "JUnit5Xml30StatelessReporter{" + "version=" + getVersion() + ", disable=" + isDisable() diff --git a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/log/PluginConsoleLogger.java b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/log/PluginConsoleLogger.java index e5b4041210..ca41c82764 100644 --- a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/log/PluginConsoleLogger.java +++ b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/log/PluginConsoleLogger.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire.log; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.surefire.log; import org.apache.maven.plugin.surefire.log.api.ConsoleLogger; import org.codehaus.plexus.logging.Logger; @@ -33,83 +32,68 @@ * @since 2.20 * @see ConsoleLogger */ -public final class PluginConsoleLogger - implements ConsoleLogger -{ +public final class PluginConsoleLogger implements ConsoleLogger { private final Logger plexusLogger; - public PluginConsoleLogger( Logger plexusLogger ) - { + public PluginConsoleLogger(Logger plexusLogger) { this.plexusLogger = plexusLogger; } @Override - public boolean isDebugEnabled() - { + public boolean isDebugEnabled() { return plexusLogger.isDebugEnabled(); } @Override - public synchronized void debug( String message ) - { - plexusLogger.debug( message ); + public synchronized void debug(String message) { + plexusLogger.debug(message); } - public synchronized void debug( CharSequence content, Throwable error ) - { - plexusLogger.debug( content == null ? "" : content.toString(), error ); + public synchronized void debug(CharSequence content, Throwable error) { + plexusLogger.debug(content == null ? "" : content.toString(), error); } @Override - public boolean isInfoEnabled() - { + public boolean isInfoEnabled() { return plexusLogger.isInfoEnabled(); } @Override - public synchronized void info( String message ) - { - plexusLogger.info( message ); + public synchronized void info(String message) { + plexusLogger.info(message); } @Override - public boolean isWarnEnabled() - { + public boolean isWarnEnabled() { return plexusLogger.isWarnEnabled(); } @Override - public synchronized void warning( String message ) - { - plexusLogger.warn( message ); + public synchronized void warning(String message) { + plexusLogger.warn(message); } - public synchronized void warning( CharSequence content, Throwable error ) - { - plexusLogger.warn( content == null ? "" : content.toString(), error ); + public synchronized void warning(CharSequence content, Throwable error) { + plexusLogger.warn(content == null ? "" : content.toString(), error); } @Override - public boolean isErrorEnabled() - { + public boolean isErrorEnabled() { return plexusLogger.isErrorEnabled() || plexusLogger.isFatalErrorEnabled(); } @Override - public synchronized void error( String message ) - { - plexusLogger.error( message ); + public synchronized void error(String message) { + plexusLogger.error(message); } @Override - public synchronized void error( String message, Throwable t ) - { - plexusLogger.error( message, t ); + public synchronized void error(String message, Throwable t) { + plexusLogger.error(message, t); } @Override - public synchronized void error( Throwable t ) - { - plexusLogger.error( "", t ); + public synchronized void error(Throwable t) { + plexusLogger.error("", t); } } diff --git a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/report/ConsoleOutputFileReporter.java b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/report/ConsoleOutputFileReporter.java index 6d3a7c737b..19a11ae777 100644 --- a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/report/ConsoleOutputFileReporter.java +++ b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/report/ConsoleOutputFileReporter.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire.report; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,11 +16,7 @@ * specific language governing permissions and limitations * under the License. */ - -import org.apache.maven.plugin.surefire.booterclient.output.InPluginProcessDumpSingleton; -import org.apache.maven.surefire.api.report.ReportEntry; -import org.apache.maven.surefire.api.report.TestOutputReportEntry; -import org.apache.maven.surefire.api.report.TestSetReportEntry; +package org.apache.maven.plugin.surefire.report; import java.io.BufferedOutputStream; import java.io.File; @@ -33,6 +27,11 @@ import java.nio.charset.Charset; import java.util.concurrent.atomic.AtomicStampedReference; +import org.apache.maven.plugin.surefire.booterclient.output.InPluginProcessDumpSingleton; +import org.apache.maven.surefire.api.report.ReportEntry; +import org.apache.maven.surefire.api.report.TestOutputReportEntry; +import org.apache.maven.surefire.api.report.TestSetReportEntry; + import static org.apache.maven.plugin.surefire.report.FileReporter.getReportFile; import static org.apache.maven.surefire.api.util.internal.StringUtils.NL; @@ -42,9 +41,7 @@ * @author Kristian Rosenvold * @author Carlos Sanchez */ -public class ConsoleOutputFileReporter - implements TestcycleConsoleOutputReceiver -{ +public class ConsoleOutputFileReporter implements TestcycleConsoleOutputReceiver { private static final int STREAM_BUFFER_SIZE = 64 * 1024; private static final int OPEN = 0; private static final int CLOSED_TO_REOPEN = 1; @@ -57,13 +54,16 @@ public class ConsoleOutputFileReporter private final String encoding; private final AtomicStampedReference fileOutputStream = - new AtomicStampedReference<>( null, OPEN ); + new AtomicStampedReference<>(null, OPEN); private volatile String reportEntryName; - public ConsoleOutputFileReporter( File reportsDirectory, String reportNameSuffix, boolean usePhrasedFileName, - Integer forkNumber, String encoding ) - { + public ConsoleOutputFileReporter( + File reportsDirectory, + String reportNameSuffix, + boolean usePhrasedFileName, + Integer forkNumber, + String encoding) { this.reportsDirectory = reportsDirectory; this.reportNameSuffix = reportNameSuffix; this.usePhrasedFileName = usePhrasedFileName; @@ -72,123 +72,91 @@ public ConsoleOutputFileReporter( File reportsDirectory, String reportNameSuffix } @Override - public synchronized void testSetStarting( TestSetReportEntry reportEntry ) - { - closeNullReportFile( reportEntry ); + public synchronized void testSetStarting(TestSetReportEntry reportEntry) { + closeNullReportFile(reportEntry); } @Override - public void testSetCompleted( TestSetReportEntry report ) - { - } + public void testSetCompleted(TestSetReportEntry report) {} @Override - public synchronized void close() - { + public synchronized void close() { // The close() method is called in main Thread T2. closeReportFile(); } @Override - public synchronized void writeTestOutput( TestOutputReportEntry reportEntry ) - { - try - { + public synchronized void writeTestOutput(TestOutputReportEntry reportEntry) { + try { // This method is called in single thread T1 per fork JVM (see ThreadedStreamConsumer). // The close() method is called in main Thread T2. int[] status = new int[1]; - FilterOutputStream os = fileOutputStream.get( status ); - if ( status[0] != CLOSED ) - { - if ( os == null ) - { - if ( !reportsDirectory.exists() ) - { + FilterOutputStream os = fileOutputStream.get(status); + if (status[0] != CLOSED) { + if (os == null) { + if (!reportsDirectory.exists()) { //noinspection ResultOfMethodCallIgnored reportsDirectory.mkdirs(); } - File file = getReportFile( reportsDirectory, reportEntryName, reportNameSuffix, "-output.txt" ); - os = new BufferedOutputStream( new FileOutputStream( file ), STREAM_BUFFER_SIZE ); - fileOutputStream.set( os, OPEN ); + File file = getReportFile(reportsDirectory, reportEntryName, reportNameSuffix, "-output.txt"); + os = new BufferedOutputStream(new FileOutputStream(file), STREAM_BUFFER_SIZE); + fileOutputStream.set(os, OPEN); } String output = reportEntry.getLog(); - if ( output == null ) - { + if (output == null) { output = "null"; } - Charset charset = Charset.forName( encoding ); - os.write( output.getBytes( charset ) ); - if ( reportEntry.isNewLine() ) - { - os.write( NL.getBytes( charset ) ); + Charset charset = Charset.forName(encoding); + os.write(output.getBytes(charset)); + if (reportEntry.isNewLine()) { + os.write(NL.getBytes(charset)); } } - } - catch ( IOException e ) - { - dumpException( e ); - throw new UncheckedIOException( e ); + } catch (IOException e) { + dumpException(e); + throw new UncheckedIOException(e); } } - @SuppressWarnings( "checkstyle:emptyblock" ) - private void closeNullReportFile( ReportEntry reportEntry ) - { - try - { + @SuppressWarnings("checkstyle:emptyblock") + private void closeNullReportFile(ReportEntry reportEntry) { + try { // close null-output.txt report file - close( true ); - } - catch ( IOException e ) - { - dumpException( e ); - } - finally - { + close(true); + } catch (IOException e) { + dumpException(e); + } finally { // prepare -output.txt report file reportEntryName = usePhrasedFileName ? reportEntry.getSourceText() : reportEntry.getSourceName(); } } - @SuppressWarnings( "checkstyle:emptyblock" ) - private void closeReportFile() - { - try - { - close( false ); - } - catch ( IOException e ) - { - dumpException( e ); + @SuppressWarnings("checkstyle:emptyblock") + private void closeReportFile() { + try { + close(false); + } catch (IOException e) { + dumpException(e); } } - private void close( boolean closeReattempt ) - throws IOException - { + private void close(boolean closeReattempt) throws IOException { int[] status = new int[1]; - FilterOutputStream os = fileOutputStream.get( status ); - if ( status[0] != CLOSED ) - { - fileOutputStream.set( null, closeReattempt ? CLOSED_TO_REOPEN : CLOSED ); - if ( os != null && status[0] == OPEN ) - { + FilterOutputStream os = fileOutputStream.get(status); + if (status[0] != CLOSED) { + fileOutputStream.set(null, closeReattempt ? CLOSED_TO_REOPEN : CLOSED); + if (os != null && status[0] == OPEN) { os.close(); } } } - private void dumpException( IOException e ) - { - if ( forkNumber == null ) - { - InPluginProcessDumpSingleton.getSingleton() - .dumpException( e, e.getLocalizedMessage(), reportsDirectory ); - } - else - { + private void dumpException(IOException e) { + if (forkNumber == null) { + InPluginProcessDumpSingleton.getSingleton().dumpException(e, e.getLocalizedMessage(), reportsDirectory); + } else { InPluginProcessDumpSingleton.getSingleton() - .dumpException( e, e.getLocalizedMessage(), reportsDirectory, forkNumber ); + .dumpException(e, e.getLocalizedMessage(), reportsDirectory, forkNumber); } } } diff --git a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/report/ConsoleReporter.java b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/report/ConsoleReporter.java index 6541b05fb5..f6645e6cad 100644 --- a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/report/ConsoleReporter.java +++ b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/report/ConsoleReporter.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire.report; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,14 +16,15 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.surefire.report; import java.util.List; import org.apache.maven.plugin.surefire.log.api.ConsoleLogger; -import org.apache.maven.surefire.shared.utils.logging.MessageBuilder; import org.apache.maven.plugin.surefire.log.api.Level; -import org.apache.maven.surefire.extensions.StatelessTestsetInfoConsoleReportEventListener; import org.apache.maven.surefire.api.report.TestSetReportEntry; +import org.apache.maven.surefire.extensions.StatelessTestsetInfoConsoleReportEventListener; +import org.apache.maven.surefire.shared.utils.logging.MessageBuilder; import static org.apache.maven.plugin.surefire.log.api.Level.resolveLevel; import static org.apache.maven.plugin.surefire.report.TestSetStats.concatenateWithTestGroup; @@ -37,9 +36,7 @@ * @author Brett Porter * @author Kristian Rosenvold */ -public class ConsoleReporter - extends StatelessTestsetInfoConsoleReportEventListener -{ +public class ConsoleReporter extends StatelessTestsetInfoConsoleReportEventListener { public static final String BRIEF = "brief"; public static final String PLAIN = "plain"; private static final String TEST_SET_STARTING_PREFIX = "Running "; @@ -47,60 +44,48 @@ public class ConsoleReporter private final boolean usePhrasedClassNameInRunning; private final boolean usePhrasedClassNameInTestCaseSummary; - public ConsoleReporter( ConsoleLogger logger, - boolean usePhrasedClassNameInRunning, boolean usePhrasedClassNameInTestCaseSummary ) - { - super( logger ); + public ConsoleReporter( + ConsoleLogger logger, boolean usePhrasedClassNameInRunning, boolean usePhrasedClassNameInTestCaseSummary) { + super(logger); this.usePhrasedClassNameInRunning = usePhrasedClassNameInRunning; this.usePhrasedClassNameInTestCaseSummary = usePhrasedClassNameInTestCaseSummary; } @Override - public void testSetStarting( TestSetReportEntry report ) - { - MessageBuilder builder = buffer().a( TEST_SET_STARTING_PREFIX ); - String runningTestCase = concatenateWithTestGroup( builder, report, usePhrasedClassNameInRunning ); - getConsoleLogger() - .info( runningTestCase ); + public void testSetStarting(TestSetReportEntry report) { + MessageBuilder builder = buffer().a(TEST_SET_STARTING_PREFIX); + String runningTestCase = concatenateWithTestGroup(builder, report, usePhrasedClassNameInRunning); + getConsoleLogger().info(runningTestCase); } @Override - public void testSetCompleted( WrappedReportEntry report, TestSetStats testSetStats, List testResults ) - { + public void testSetCompleted(WrappedReportEntry report, TestSetStats testSetStats, List testResults) { boolean success = testSetStats.getCompletedCount() > 0; boolean failures = testSetStats.getFailures() > 0; boolean errors = testSetStats.getErrors() > 0; boolean skipped = testSetStats.getSkipped() > 0; boolean flakes = testSetStats.getSkipped() > 0; - Level level = resolveLevel( success, failures, errors, skipped, flakes ); + Level level = resolveLevel(success, failures, errors, skipped, flakes); - println( testSetStats.getColoredTestSetSummary( report, usePhrasedClassNameInTestCaseSummary ), level ); - for ( String testResult : testResults ) - { - println( testResult, level ); + println(testSetStats.getColoredTestSetSummary(report, usePhrasedClassNameInTestCaseSummary), level); + for (String testResult : testResults) { + println(testResult, level); } } @Override - public void reset() - { - } + public void reset() {} - private void println( String message, Level level ) - { - switch ( level ) - { + private void println(String message, Level level) { + switch (level) { case FAILURE: - getConsoleLogger() - .error( message ); + getConsoleLogger().error(message); break; case UNSTABLE: - getConsoleLogger() - .warning( message ); + getConsoleLogger().warning(message); break; default: - getConsoleLogger() - .info( message ); + getConsoleLogger().info(message); } } } diff --git a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/report/DefaultReporterFactory.java b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/report/DefaultReporterFactory.java index d45ae83cf3..762e1348cc 100644 --- a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/report/DefaultReporterFactory.java +++ b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/report/DefaultReporterFactory.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire.report; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,31 +16,32 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.surefire.report; + +import java.io.File; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; +import java.util.concurrent.ConcurrentLinkedQueue; import org.apache.maven.plugin.surefire.StartupReportConfiguration; import org.apache.maven.plugin.surefire.log.api.ConsoleLogger; import org.apache.maven.plugin.surefire.log.api.Level; import org.apache.maven.plugin.surefire.runorder.StatisticsReporter; +import org.apache.maven.surefire.api.report.ReporterFactory; +import org.apache.maven.surefire.api.report.StackTraceWriter; import org.apache.maven.surefire.api.report.TestOutputReportEntry; -import org.apache.maven.surefire.shared.utils.logging.MessageBuilder; +import org.apache.maven.surefire.api.report.TestReportListener; +import org.apache.maven.surefire.api.suite.RunResult; import org.apache.maven.surefire.extensions.ConsoleOutputReportEventListener; import org.apache.maven.surefire.extensions.StatelessReportEventListener; import org.apache.maven.surefire.extensions.StatelessTestsetInfoConsoleReportEventListener; import org.apache.maven.surefire.extensions.StatelessTestsetInfoFileReportEventListener; -import org.apache.maven.surefire.api.report.ReporterFactory; -import org.apache.maven.surefire.api.report.TestReportListener; import org.apache.maven.surefire.report.RunStatistics; -import org.apache.maven.surefire.api.report.StackTraceWriter; -import org.apache.maven.surefire.api.suite.RunResult; - -import java.io.File; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.TreeMap; -import java.util.concurrent.ConcurrentLinkedQueue; +import org.apache.maven.surefire.shared.utils.logging.MessageBuilder; import static org.apache.maven.plugin.surefire.log.api.Level.resolveLevel; import static org.apache.maven.plugin.surefire.report.ConsoleReporter.PLAIN; @@ -55,8 +54,8 @@ import static org.apache.maven.plugin.surefire.report.ReportEntryType.ERROR; import static org.apache.maven.plugin.surefire.report.ReportEntryType.FAILURE; import static org.apache.maven.plugin.surefire.report.ReportEntryType.SUCCESS; -import static org.apache.maven.surefire.shared.utils.logging.MessageUtils.buffer; import static org.apache.maven.surefire.api.util.internal.ObjectUtils.useNonNull; +import static org.apache.maven.surefire.shared.utils.logging.MessageUtils.buffer; /** * Provides reporting modules on the plugin side. @@ -65,9 +64,7 @@ * * @author Kristian Rosenvold */ -public class DefaultReporterFactory - implements ReporterFactory, ReportsMerger -{ +public class DefaultReporterFactory implements ReporterFactory, ReportsMerger { private final Collection listeners = new ConcurrentLinkedQueue<>(); private final StartupReportConfiguration reportConfiguration; private final ConsoleLogger consoleLogger; @@ -84,140 +81,119 @@ public class DefaultReporterFactory // from "." -> statistics about all the runs for error tests private Map> errorTests; - public DefaultReporterFactory( StartupReportConfiguration reportConfiguration, ConsoleLogger consoleLogger ) - { - this( reportConfiguration, consoleLogger, null ); + public DefaultReporterFactory(StartupReportConfiguration reportConfiguration, ConsoleLogger consoleLogger) { + this(reportConfiguration, consoleLogger, null); } - public DefaultReporterFactory( StartupReportConfiguration reportConfiguration, ConsoleLogger consoleLogger, - Integer forkNumber ) - { + public DefaultReporterFactory( + StartupReportConfiguration reportConfiguration, ConsoleLogger consoleLogger, Integer forkNumber) { this.reportConfiguration = reportConfiguration; this.consoleLogger = consoleLogger; this.forkNumber = forkNumber; } @Override - public TestReportListener createTestReportListener() - { - TestSetRunListener testSetRunListener = - new TestSetRunListener( createConsoleReporter(), - createFileReporter(), - createSimpleXMLReporter(), - createConsoleOutputReceiver(), - createStatisticsReporter(), - reportConfiguration.isTrimStackTrace(), - PLAIN.equals( reportConfiguration.getReportFormat() ), - reportConfiguration.isBriefOrPlainFormat(), - consoleLogger ); - addListener( testSetRunListener ); + public TestReportListener createTestReportListener() { + TestSetRunListener testSetRunListener = new TestSetRunListener( + createConsoleReporter(), + createFileReporter(), + createSimpleXMLReporter(), + createConsoleOutputReceiver(), + createStatisticsReporter(), + reportConfiguration.isTrimStackTrace(), + PLAIN.equals(reportConfiguration.getReportFormat()), + reportConfiguration.isBriefOrPlainFormat(), + consoleLogger); + addListener(testSetRunListener); return testSetRunListener; } @Override - public File getReportsDirectory() - { + public File getReportsDirectory() { return reportConfiguration.getReportsDirectory(); } - private StatelessTestsetInfoConsoleReportEventListener createConsoleReporter() - { + private StatelessTestsetInfoConsoleReportEventListener createConsoleReporter() { StatelessTestsetInfoConsoleReportEventListener consoleReporter = - reportConfiguration.instantiateConsoleReporter( consoleLogger ); - return useNonNull( consoleReporter, NullConsoleReporter.INSTANCE ); + reportConfiguration.instantiateConsoleReporter(consoleLogger); + return useNonNull(consoleReporter, NullConsoleReporter.INSTANCE); } - private StatelessTestsetInfoFileReportEventListener createFileReporter() - { + private StatelessTestsetInfoFileReportEventListener createFileReporter() { StatelessTestsetInfoFileReportEventListener fileReporter = - reportConfiguration.instantiateFileReporter( forkNumber ); - return useNonNull( fileReporter, NullFileReporter.INSTANCE ); + reportConfiguration.instantiateFileReporter(forkNumber); + return useNonNull(fileReporter, NullFileReporter.INSTANCE); } - private StatelessReportEventListener createSimpleXMLReporter() - { + private StatelessReportEventListener createSimpleXMLReporter() { StatelessReportEventListener xmlReporter = - reportConfiguration.instantiateStatelessXmlReporter( forkNumber ); - return useNonNull( xmlReporter, NullStatelessXmlReporter.INSTANCE ); + reportConfiguration.instantiateStatelessXmlReporter(forkNumber); + return useNonNull(xmlReporter, NullStatelessXmlReporter.INSTANCE); } - private ConsoleOutputReportEventListener createConsoleOutputReceiver() - { + private ConsoleOutputReportEventListener createConsoleOutputReceiver() { ConsoleOutputReportEventListener outputReporter = - reportConfiguration.instantiateConsoleOutputFileReporter( forkNumber ); - return useNonNull( outputReporter, NullConsoleOutputReceiver.INSTANCE ); + reportConfiguration.instantiateConsoleOutputFileReporter(forkNumber); + return useNonNull(outputReporter, NullConsoleOutputReceiver.INSTANCE); } - private StatisticsReporter createStatisticsReporter() - { + private StatisticsReporter createStatisticsReporter() { StatisticsReporter statisticsReporter = reportConfiguration.getStatisticsReporter(); - return useNonNull( statisticsReporter, NullStatisticsReporter.INSTANCE ); + return useNonNull(statisticsReporter, NullStatisticsReporter.INSTANCE); } @Override - public void mergeFromOtherFactories( Collection factories ) - { - for ( DefaultReporterFactory factory : factories ) - { - listeners.addAll( factory.listeners ); + public void mergeFromOtherFactories(Collection factories) { + for (DefaultReporterFactory factory : factories) { + listeners.addAll(factory.listeners); } } - final void addListener( TestSetRunListener listener ) - { - listeners.add( listener ); + final void addListener(TestSetRunListener listener) { + listeners.add(listener); } @Override - public RunResult close() - { + public RunResult close() { mergeTestHistoryResult(); runCompleted(); - for ( TestSetRunListener listener : listeners ) - { + for (TestSetRunListener listener : listeners) { listener.close(); } return globalStats.getRunResult(); } @Override - public void runStarting() - { - if ( reportConfiguration.isPrintSummary() ) - { - log( "" ); - log( "-------------------------------------------------------" ); - log( " T E S T S" ); - log( "-------------------------------------------------------" ); + public void runStarting() { + if (reportConfiguration.isPrintSummary()) { + log(""); + log("-------------------------------------------------------"); + log(" T E S T S"); + log("-------------------------------------------------------"); } } - private void runCompleted() - { - if ( reportConfiguration.isPrintSummary() ) - { - log( "" ); - log( "Results:" ); - log( "" ); + private void runCompleted() { + if (reportConfiguration.isPrintSummary()) { + log(""); + log("Results:"); + log(""); } - boolean printedFailures = printTestFailures( failure ); - boolean printedErrors = printTestFailures( error ); - boolean printedFlakes = printTestFailures( flake ); - if ( reportConfiguration.isPrintSummary() ) - { - if ( printedFailures | printedErrors | printedFlakes ) - { - log( "" ); + boolean printedFailures = printTestFailures(failure); + boolean printedErrors = printTestFailures(error); + boolean printedFlakes = printTestFailures(flake); + if (reportConfiguration.isPrintSummary()) { + if (printedFailures | printedErrors | printedFlakes) { + log(""); } boolean hasSuccessful = globalStats.getCompletedCount() > 0; boolean hasSkipped = globalStats.getSkipped() > 0; - log( globalStats.getSummary(), hasSuccessful, printedFailures, printedErrors, hasSkipped, printedFlakes ); - log( "" ); + log(globalStats.getSummary(), hasSuccessful, printedFailures, printedErrors, hasSkipped, printedFlakes); + log(""); } } - public RunStatistics getGlobalRunStatistics() - { + public RunStatistics getGlobalRunStatistics() { mergeTestHistoryResult(); return globalStats; } @@ -231,47 +207,31 @@ public RunStatistics getGlobalRunStatistics() * @return the type of test result */ // Use default visibility for testing - static TestResultType getTestResultType( List reportEntries, int rerunFailingTestsCount ) - { - if ( reportEntries == null || reportEntries.isEmpty() ) - { + static TestResultType getTestResultType(List reportEntries, int rerunFailingTestsCount) { + if (reportEntries == null || reportEntries.isEmpty()) { return unknown; } boolean seenSuccess = false, seenFailure = false, seenError = false; - for ( ReportEntryType resultType : reportEntries ) - { - if ( resultType == SUCCESS ) - { + for (ReportEntryType resultType : reportEntries) { + if (resultType == SUCCESS) { seenSuccess = true; - } - else if ( resultType == FAILURE ) - { + } else if (resultType == FAILURE) { seenFailure = true; - } - else if ( resultType == ERROR ) - { + } else if (resultType == ERROR) { seenError = true; } } - if ( seenFailure || seenError ) - { - if ( seenSuccess && rerunFailingTestsCount > 0 ) - { + if (seenFailure || seenError) { + if (seenSuccess && rerunFailingTestsCount > 0) { return flake; - } - else - { + } else { return seenError ? error : failure; } - } - else if ( seenSuccess ) - { + } else if (seenSuccess) { return success; - } - else - { + } else { return skipped; } } @@ -280,8 +240,7 @@ else if ( seenSuccess ) * Merge all the TestMethodStats in each TestRunListeners and put results into flakyTests, failedTests and * errorTests, indexed by test class and method name. Update globalStatistics based on the result of the merge. */ - private void mergeTestHistoryResult() - { + private void mergeTestHistoryResult() { globalStats = new RunStatistics(); flakyTests = new TreeMap<>(); failedTests = new TreeMap<>(); @@ -289,21 +248,16 @@ private void mergeTestHistoryResult() Map> mergedTestHistoryResult = new HashMap<>(); // Merge all the stats for tests from listeners - for ( TestSetRunListener listener : listeners ) - { - for ( TestMethodStats methodStats : listener.getTestMethodStats() ) - { + for (TestSetRunListener listener : listeners) { + for (TestMethodStats methodStats : listener.getTestMethodStats()) { List currentMethodStats = - mergedTestHistoryResult.get( methodStats.getTestClassMethodName() ); - if ( currentMethodStats == null ) - { + mergedTestHistoryResult.get(methodStats.getTestClassMethodName()); + if (currentMethodStats == null) { currentMethodStats = new ArrayList<>(); - currentMethodStats.add( methodStats ); - mergedTestHistoryResult.put( methodStats.getTestClassMethodName(), currentMethodStats ); - } - else - { - currentMethodStats.add( methodStats ); + currentMethodStats.add(methodStats); + mergedTestHistoryResult.put(methodStats.getTestClassMethodName(), currentMethodStats); + } else { + currentMethodStats.add(methodStats); } } } @@ -311,27 +265,22 @@ private void mergeTestHistoryResult() // Update globalStatistics by iterating through mergedTestHistoryResult int completedCount = 0, skipped = 0; - for ( Map.Entry> entry : mergedTestHistoryResult.entrySet() ) - { + for (Map.Entry> entry : mergedTestHistoryResult.entrySet()) { List testMethodStats = entry.getValue(); String testClassMethodName = entry.getKey(); completedCount++; List resultTypes = new ArrayList<>(); - for ( TestMethodStats methodStats : testMethodStats ) - { - resultTypes.add( methodStats.getResultType() ); + for (TestMethodStats methodStats : testMethodStats) { + resultTypes.add(methodStats.getResultType()); } - switch ( getTestResultType( resultTypes, reportConfiguration.getRerunFailingTestsCount() ) ) - { + switch (getTestResultType(resultTypes, reportConfiguration.getRerunFailingTestsCount())) { case success: // If there are multiple successful runs of the same test, count all of them int successCount = 0; - for ( ReportEntryType type : resultTypes ) - { - if ( type == SUCCESS ) - { + for (ReportEntryType type : resultTypes) { + if (type == SUCCESS) { successCount++; } } @@ -341,20 +290,20 @@ private void mergeTestHistoryResult() skipped++; break; case flake: - flakyTests.put( testClassMethodName, testMethodStats ); + flakyTests.put(testClassMethodName, testMethodStats); break; case failure: - failedTests.put( testClassMethodName, testMethodStats ); + failedTests.put(testClassMethodName, testMethodStats); break; case error: - errorTests.put( testClassMethodName, testMethodStats ); + errorTests.put(testClassMethodName, testMethodStats); break; default: - throw new IllegalStateException( "Get unknown test result type" ); + throw new IllegalStateException("Get unknown test result type"); } } - globalStats.set( completedCount, errorTests.size(), failedTests.size(), skipped, flakyTests.size() ); + globalStats.set(completedCount, errorTests.size(), failedTests.size(), skipped, flakyTests.size()); } /** @@ -365,12 +314,10 @@ private void mergeTestHistoryResult() * @return {@code true} if printed some lines */ // Use default visibility for testing - boolean printTestFailures( TestResultType type ) - { + boolean printTestFailures(TestResultType type) { final Map> testStats; final Level level; - switch ( type ) - { + switch (type) { case failure: testStats = failedTests; level = Level.FAILURE; @@ -388,115 +335,94 @@ boolean printTestFailures( TestResultType type ) } boolean printed = false; - if ( !testStats.isEmpty() ) - { - log( type.getLogPrefix(), level ); + if (!testStats.isEmpty()) { + log(type.getLogPrefix(), level); printed = true; } - for ( Map.Entry> entry : testStats.entrySet() ) - { + for (Map.Entry> entry : testStats.entrySet()) { List testMethodStats = entry.getValue(); - if ( testMethodStats.size() == 1 ) - { + if (testMethodStats.size() == 1) { // No rerun, follow the original output format - failure( " " + testMethodStats.get( 0 ).getStackTraceWriter().smartTrimmedStackTrace() ); - } - else - { - log( entry.getKey(), level ); - for ( int i = 0; i < testMethodStats.size(); i++ ) - { - StackTraceWriter failureStackTrace = testMethodStats.get( i ).getStackTraceWriter(); - if ( failureStackTrace == null ) - { - success( " Run " + ( i + 1 ) + ": PASS" ); - } - else - { - failure( " Run " + ( i + 1 ) + ": " + failureStackTrace.smartTrimmedStackTrace() ); + failure(" " + testMethodStats.get(0).getStackTraceWriter().smartTrimmedStackTrace()); + } else { + log(entry.getKey(), level); + for (int i = 0; i < testMethodStats.size(); i++) { + StackTraceWriter failureStackTrace = testMethodStats.get(i).getStackTraceWriter(); + if (failureStackTrace == null) { + success(" Run " + (i + 1) + ": PASS"); + } else { + failure(" Run " + (i + 1) + ": " + failureStackTrace.smartTrimmedStackTrace()); } } - log( "" ); + log(""); } } return printed; } // Describe the result of a given test - enum TestResultType - { - - error( "Errors: " ), - failure( "Failures: " ), - flake( "Flakes: " ), - success( "Success: " ), - skipped( "Skipped: " ), - unknown( "Unknown: " ); + enum TestResultType { + error("Errors: "), + failure("Failures: "), + flake("Flakes: "), + success("Success: "), + skipped("Skipped: "), + unknown("Unknown: "); private final String logPrefix; - TestResultType( String logPrefix ) - { + TestResultType(String logPrefix) { this.logPrefix = logPrefix; } - public String getLogPrefix() - { + public String getLogPrefix() { return logPrefix; } } - private void log( String s, boolean success, boolean failures, boolean errors, boolean skipped, boolean flakes ) - { - Level level = resolveLevel( success, failures, errors, skipped, flakes ); - log( s, level ); + private void log(String s, boolean success, boolean failures, boolean errors, boolean skipped, boolean flakes) { + Level level = resolveLevel(success, failures, errors, skipped, flakes); + log(s, level); } - private void log( String s, Level level ) - { - switch ( level ) - { + private void log(String s, Level level) { + switch (level) { case FAILURE: - failure( s ); + failure(s); break; case UNSTABLE: - warning( s ); + warning(s); break; case SUCCESS: - success( s ); + success(s); break; default: - info( s ); + info(s); } } - private void log( String s ) - { - consoleLogger.info( s ); + private void log(String s) { + consoleLogger.info(s); } - private void info( String s ) - { + private void info(String s) { MessageBuilder builder = buffer(); - consoleLogger.info( builder.a( s ).toString() ); + consoleLogger.info(builder.a(s).toString()); } - private void warning( String s ) - { + private void warning(String s) { MessageBuilder builder = buffer(); - consoleLogger.warning( builder.warning( s ).toString() ); + consoleLogger.warning(builder.warning(s).toString()); } - private void success( String s ) - { + private void success(String s) { MessageBuilder builder = buffer(); - consoleLogger.info( builder.success( s ).toString() ); + consoleLogger.info(builder.success(s).toString()); } - private void failure( String s ) - { + private void failure(String s) { MessageBuilder builder = buffer(); - consoleLogger.error( builder.failure( s ).toString() ); + consoleLogger.error(builder.failure(s).toString()); } } diff --git a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/report/DirectConsoleOutput.java b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/report/DirectConsoleOutput.java index a1748b691b..13b14eb82b 100644 --- a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/report/DirectConsoleOutput.java +++ b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/report/DirectConsoleOutput.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire.report; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,12 +16,13 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.surefire.report; + +import java.io.PrintStream; import org.apache.maven.surefire.api.report.TestOutputReportEntry; import org.apache.maven.surefire.api.report.TestSetReportEntry; -import java.io.PrintStream; - import static java.util.Objects.requireNonNull; /** @@ -34,45 +33,32 @@ * * @author Kristian Rosenvold */ -public class DirectConsoleOutput - implements TestcycleConsoleOutputReceiver -{ +public class DirectConsoleOutput implements TestcycleConsoleOutputReceiver { private final PrintStream out; private final PrintStream err; - public DirectConsoleOutput( PrintStream out, PrintStream err ) - { - this.out = requireNonNull( out ); - this.err = requireNonNull( err ); + public DirectConsoleOutput(PrintStream out, PrintStream err) { + this.out = requireNonNull(out); + this.err = requireNonNull(err); } @Override - public void writeTestOutput( TestOutputReportEntry reportEntry ) - { + public void writeTestOutput(TestOutputReportEntry reportEntry) { PrintStream stream = reportEntry.isStdOut() ? out : err; - if ( reportEntry.isNewLine() ) - { - stream.println( reportEntry.getLog() ); - } - else - { - stream.print( reportEntry.getLog() ); + if (reportEntry.isNewLine()) { + stream.println(reportEntry.getLog()); + } else { + stream.print(reportEntry.getLog()); } } @Override - public void testSetStarting( TestSetReportEntry reportEntry ) - { - } + public void testSetStarting(TestSetReportEntry reportEntry) {} @Override - public void testSetCompleted( TestSetReportEntry report ) - { - } + public void testSetCompleted(TestSetReportEntry report) {} @Override - public void close() - { - } + public void close() {} } diff --git a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/report/FileReporter.java b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/report/FileReporter.java index b3410f70b7..dfafeb5319 100644 --- a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/report/FileReporter.java +++ b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/report/FileReporter.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire.report; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,9 +16,7 @@ * specific language governing permissions and limitations * under the License. */ - -import org.apache.maven.surefire.extensions.StatelessTestsetInfoFileReportEventListener; -import org.apache.maven.surefire.api.report.ReporterException; +package org.apache.maven.plugin.surefire.report; import java.io.BufferedWriter; import java.io.File; @@ -31,6 +27,9 @@ import java.nio.charset.Charset; import java.util.List; +import org.apache.maven.surefire.api.report.ReporterException; +import org.apache.maven.surefire.extensions.StatelessTestsetInfoFileReportEventListener; + import static org.apache.maven.plugin.surefire.report.FileReporterUtils.stripIllegalFilenameChars; import static org.apache.maven.surefire.shared.utils.StringUtils.isNotBlank; @@ -40,72 +39,68 @@ * @author Brett Porter * @author Kristian Rosenvold */ -public class FileReporter - extends StatelessTestsetInfoFileReportEventListener -{ +public class FileReporter extends StatelessTestsetInfoFileReportEventListener { private final boolean usePhrasedFileName; private final boolean usePhrasedClassNameInRunning; private final boolean usePhrasedClassNameInTestCaseSummary; - public FileReporter( File reportsDirectory, String reportNameSuffix, Charset encoding, boolean usePhrasedFileName, - boolean usePhrasedClassNameInRunning, boolean usePhrasedClassNameInTestCaseSummary ) - { - super( reportsDirectory, reportNameSuffix, encoding ); + public FileReporter( + File reportsDirectory, + String reportNameSuffix, + Charset encoding, + boolean usePhrasedFileName, + boolean usePhrasedClassNameInRunning, + boolean usePhrasedClassNameInTestCaseSummary) { + super(reportsDirectory, reportNameSuffix, encoding); this.usePhrasedFileName = usePhrasedFileName; this.usePhrasedClassNameInRunning = usePhrasedClassNameInRunning; this.usePhrasedClassNameInTestCaseSummary = usePhrasedClassNameInTestCaseSummary; } - static File getReportFile( File reportsDirectory, String reportEntryName, String reportNameSuffix, - String fileExtension ) - { + static File getReportFile( + File reportsDirectory, String reportEntryName, String reportNameSuffix, String fileExtension) { String fileName = - reportEntryName + ( isNotBlank( reportNameSuffix ) ? "-" + reportNameSuffix : "" ) + fileExtension; - return new File( reportsDirectory, stripIllegalFilenameChars( fileName ) ); + reportEntryName + (isNotBlank(reportNameSuffix) ? "-" + reportNameSuffix : "") + fileExtension; + return new File(reportsDirectory, stripIllegalFilenameChars(fileName)); } @Override - public void testSetCompleted( WrappedReportEntry report, TestSetStats testSetStats, List testResults ) - { - File reportFile = getReportFile( getReportsDirectory(), - usePhrasedFileName ? report.getReportSourceName() : report.getSourceName(), - getReportNameSuffix(), - ".txt" ); + public void testSetCompleted(WrappedReportEntry report, TestSetStats testSetStats, List testResults) { + File reportFile = getReportFile( + getReportsDirectory(), + usePhrasedFileName ? report.getReportSourceName() : report.getSourceName(), + getReportNameSuffix(), + ".txt"); File reportDir = reportFile.getParentFile(); // noinspection ResultOfMethodCallIgnored reportDir.mkdirs(); - try ( BufferedWriter writer = createFileReporterWriter( reportFile, getEncoding() ) ) - { - writer.write( "-------------------------------------------------------------------------------" ); + try (BufferedWriter writer = createFileReporterWriter(reportFile, getEncoding())) { + writer.write("-------------------------------------------------------------------------------"); writer.newLine(); String tesSet = usePhrasedClassNameInRunning ? report.getReportSourceName() : report.getSourceName(); - writer.write( "Test set: " + tesSet ); + writer.write("Test set: " + tesSet); writer.newLine(); - writer.write( "-------------------------------------------------------------------------------" ); + writer.write("-------------------------------------------------------------------------------"); writer.newLine(); - writer.write( testSetStats.getTestSetSummary( report, usePhrasedClassNameInTestCaseSummary ) ); + writer.write(testSetStats.getTestSetSummary(report, usePhrasedClassNameInTestCaseSummary)); writer.newLine(); - for ( String testResult : testResults ) - { - writer.write( testResult ); + for (String testResult : testResults) { + writer.write(testResult); writer.newLine(); } - } - catch ( IOException e ) - { - throw new ReporterException( "Unable to create file for report: " + e.getLocalizedMessage(), e ); + } catch (IOException e) { + throw new ReporterException("Unable to create file for report: " + e.getLocalizedMessage(), e); } } - private static BufferedWriter createFileReporterWriter( File reportFile, Charset encoding ) - throws FileNotFoundException - { - return new BufferedWriter( new OutputStreamWriter( new FileOutputStream( reportFile ), encoding ), 64 * 1024 ); + private static BufferedWriter createFileReporterWriter(File reportFile, Charset encoding) + throws FileNotFoundException { + return new BufferedWriter(new OutputStreamWriter(new FileOutputStream(reportFile), encoding), 64 * 1024); } } diff --git a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/report/FileReporterUtils.java b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/report/FileReporterUtils.java index 5ef0610158..fb54edaeb5 100644 --- a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/report/FileReporterUtils.java +++ b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/report/FileReporterUtils.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire.report; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.surefire.report; import static org.apache.maven.surefire.shared.lang3.SystemUtils.IS_OS_WINDOWS; @@ -26,31 +25,25 @@ * * @author Andreas Gudian */ -public final class FileReporterUtils -{ - private FileReporterUtils() - { - throw new IllegalStateException( "non instantiable constructor" ); +public final class FileReporterUtils { + private FileReporterUtils() { + throw new IllegalStateException("non instantiable constructor"); } - public static String stripIllegalFilenameChars( String original ) - { - StringBuilder result = new StringBuilder( original ); + public static String stripIllegalFilenameChars(String original) { + StringBuilder result = new StringBuilder(original); String illegalChars = getOSSpecificIllegalChars(); - for ( int i = 0, len = result.length(); i < len; i++ ) - { - char charFromOriginal = result.charAt( i ); - boolean isIllegalChar = illegalChars.indexOf( charFromOriginal ) != -1; - if ( isIllegalChar ) - { - result.setCharAt( i, '_' ); + for (int i = 0, len = result.length(); i < len; i++) { + char charFromOriginal = result.charAt(i); + boolean isIllegalChar = illegalChars.indexOf(charFromOriginal) != -1; + if (isIllegalChar) { + result.setCharAt(i, '_'); } } return result.toString(); } - private static String getOSSpecificIllegalChars() - { + private static String getOSSpecificIllegalChars() { // forbidden and quoted characters // https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file // https://cygwin.com/cygwin-ug-net/using-specialnames.html diff --git a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/report/NullConsoleOutputReceiver.java b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/report/NullConsoleOutputReceiver.java index 165ffe0c1f..52fcf0fd79 100644 --- a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/report/NullConsoleOutputReceiver.java +++ b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/report/NullConsoleOutputReceiver.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire.report; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.surefire.report; import org.apache.maven.surefire.api.report.TestOutputReportEntry; import org.apache.maven.surefire.api.report.TestSetReportEntry; @@ -28,37 +27,21 @@ * @author Tibor Digana (tibor17) * @since 3.0.0-M4 */ -public class NullConsoleOutputReceiver - implements TestcycleConsoleOutputReceiver -{ +public class NullConsoleOutputReceiver implements TestcycleConsoleOutputReceiver { static final NullConsoleOutputReceiver INSTANCE = new NullConsoleOutputReceiver(); - private NullConsoleOutputReceiver() - { - } + private NullConsoleOutputReceiver() {} @Override - public void testSetStarting( TestSetReportEntry reportEntry ) - { - - } + public void testSetStarting(TestSetReportEntry reportEntry) {} @Override - public void testSetCompleted( TestSetReportEntry report ) - { - - } + public void testSetCompleted(TestSetReportEntry report) {} @Override - public void close() - { - - } + public void close() {} @Override - public void writeTestOutput( TestOutputReportEntry reportEntry ) - { - - } + public void writeTestOutput(TestOutputReportEntry reportEntry) {} } diff --git a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/report/NullConsoleReporter.java b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/report/NullConsoleReporter.java index 2c5ba59ad4..a8a5414da4 100644 --- a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/report/NullConsoleReporter.java +++ b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/report/NullConsoleReporter.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire.report; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.surefire.report; import java.util.List; @@ -30,29 +29,20 @@ * @author Benedikt Ritter * @since 2.20 */ -class NullConsoleReporter - extends ConsoleReporter -{ +class NullConsoleReporter extends ConsoleReporter { static final NullConsoleReporter INSTANCE = new NullConsoleReporter(); - private NullConsoleReporter() - { - super( new NullConsoleLogger(), false, false ); + private NullConsoleReporter() { + super(new NullConsoleLogger(), false, false); } @Override - public void testSetStarting( TestSetReportEntry report ) - { - } + public void testSetStarting(TestSetReportEntry report) {} @Override - public void testSetCompleted( WrappedReportEntry report, TestSetStats testSetStats, List testResults ) - { - } + public void testSetCompleted(WrappedReportEntry report, TestSetStats testSetStats, List testResults) {} @Override - public void reset() - { - } + public void reset() {} } diff --git a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/report/NullFileReporter.java b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/report/NullFileReporter.java index be217ebfe8..c7c0cb5592 100644 --- a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/report/NullFileReporter.java +++ b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/report/NullFileReporter.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire.report; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.surefire.report; import java.util.List; @@ -27,19 +26,14 @@ * @author Benedikt Ritter * @since 2.20 */ -class NullFileReporter - extends FileReporter -{ +class NullFileReporter extends FileReporter { static final NullFileReporter INSTANCE = new NullFileReporter(); - private NullFileReporter() - { - super( null, null, null, false, false, false ); + private NullFileReporter() { + super(null, null, null, false, false, false); } @Override - public void testSetCompleted( WrappedReportEntry report, TestSetStats testSetStats, List testResults ) - { - } + public void testSetCompleted(WrappedReportEntry report, TestSetStats testSetStats, List testResults) {} } diff --git a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/report/NullStatelessXmlReporter.java b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/report/NullStatelessXmlReporter.java index d43369dd8f..d4180d54f4 100644 --- a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/report/NullStatelessXmlReporter.java +++ b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/report/NullStatelessXmlReporter.java @@ -1,3 +1,21 @@ +/* + * 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.maven.plugin.surefire.report; /* @@ -25,24 +43,17 @@ * @author Benedikt Ritter * @since 2.20 */ -class NullStatelessXmlReporter - extends StatelessXmlReporter -{ +class NullStatelessXmlReporter extends StatelessXmlReporter { static final NullStatelessXmlReporter INSTANCE = new NullStatelessXmlReporter(); - private NullStatelessXmlReporter() - { - super( null, null, false, 0, null, null, null, false, false, false, false ); + private NullStatelessXmlReporter() { + super(null, null, false, 0, null, null, null, false, false, false, false); } @Override - public void testSetCompleted( WrappedReportEntry testSetReportEntry, TestSetStats testSetStats ) - { - } + public void testSetCompleted(WrappedReportEntry testSetReportEntry, TestSetStats testSetStats) {} @Override - public void cleanTestHistoryMap() - { - } + public void cleanTestHistoryMap() {} } diff --git a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/report/NullStatisticsReporter.java b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/report/NullStatisticsReporter.java index ea11d0da78..c9c1ee2867 100644 --- a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/report/NullStatisticsReporter.java +++ b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/report/NullStatisticsReporter.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire.report; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.surefire.report; import org.apache.maven.plugin.surefire.runorder.StatisticsReporter; import org.apache.maven.surefire.api.report.ReportEntry; @@ -28,39 +27,26 @@ * @author Benedikt Ritter * @since 2.20 */ -class NullStatisticsReporter - extends StatisticsReporter -{ +class NullStatisticsReporter extends StatisticsReporter { static final NullStatisticsReporter INSTANCE = new NullStatisticsReporter(); - private NullStatisticsReporter() - { - super( null, null, null ); + private NullStatisticsReporter() { + super(null, null, null); } @Override - public synchronized void testSetCompleted() - { - } + public synchronized void testSetCompleted() {} @Override - public void testSucceeded( ReportEntry report ) - { - } + public void testSucceeded(ReportEntry report) {} @Override - public void testSkipped( ReportEntry report ) - { - } + public void testSkipped(ReportEntry report) {} @Override - public void testError( ReportEntry report ) - { - } + public void testError(ReportEntry report) {} @Override - public void testFailed( ReportEntry report ) - { - } + public void testFailed(ReportEntry report) {} } diff --git a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/report/ReportEntryType.java b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/report/ReportEntryType.java index ffdb706532..69177f03f2 100644 --- a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/report/ReportEntryType.java +++ b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/report/ReportEntryType.java @@ -1,3 +1,21 @@ +/* + * 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.maven.plugin.surefire.report; /* @@ -23,13 +41,11 @@ * Type of an entry in the report * */ -public enum ReportEntryType -{ - - ERROR( "error", "flakyError", "rerunError" ), - FAILURE( "failure", "flakyFailure", "rerunFailure" ), - SKIPPED( "skipped", "", "" ), - SUCCESS( "", "", "" ); +public enum ReportEntryType { + ERROR("error", "flakyError", "rerunError"), + FAILURE("failure", "flakyFailure", "rerunFailure"), + SKIPPED("skipped", "", ""), + SUCCESS("", "", ""); private final String xmlTag; @@ -37,25 +53,21 @@ public enum ReportEntryType private final String rerunXmlTag; - ReportEntryType( String xmlTag, String flakyXmlTag, String rerunXmlTag ) - { + ReportEntryType(String xmlTag, String flakyXmlTag, String rerunXmlTag) { this.xmlTag = xmlTag; this.flakyXmlTag = flakyXmlTag; this.rerunXmlTag = rerunXmlTag; } - public String getXmlTag() - { + public String getXmlTag() { return xmlTag; } - public String getFlakyXmlTag() - { + public String getFlakyXmlTag() { return flakyXmlTag; } - public String getRerunXmlTag() - { + public String getRerunXmlTag() { return rerunXmlTag; } } diff --git a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/report/ReporterUtils.java b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/report/ReporterUtils.java index cf1704136c..a673a18d05 100644 --- a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/report/ReporterUtils.java +++ b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/report/ReporterUtils.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire.report; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.surefire.report; import java.text.NumberFormat; import java.util.Locale; @@ -28,21 +27,18 @@ * @author Tibor Digana (tibor17) * @since 2.19 */ -final class ReporterUtils -{ +final class ReporterUtils { private static final int MS_PER_SEC = 1000; - private ReporterUtils() - { - throw new IllegalStateException( "non instantiable constructor" ); + private ReporterUtils() { + throw new IllegalStateException("non instantiable constructor"); } - static String formatElapsedTime( double runTime ) - { - NumberFormat numberFormat = NumberFormat.getInstance( Locale.ENGLISH ); - numberFormat.setGroupingUsed( true ); - numberFormat.setMinimumFractionDigits( 0 ); - numberFormat.setMaximumFractionDigits( 3 ); - return numberFormat.format( runTime / MS_PER_SEC ); + static String formatElapsedTime(double runTime) { + NumberFormat numberFormat = NumberFormat.getInstance(Locale.ENGLISH); + numberFormat.setGroupingUsed(true); + numberFormat.setMinimumFractionDigits(0); + numberFormat.setMaximumFractionDigits(3); + return numberFormat.format(runTime / MS_PER_SEC); } } diff --git a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/report/ReportsMerger.java b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/report/ReportsMerger.java index 8722062c13..21e770022f 100644 --- a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/report/ReportsMerger.java +++ b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/report/ReportsMerger.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire.report; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,19 +16,22 @@ * specific language governing permissions and limitations * under the License. */ - -import org.apache.maven.surefire.api.suite.RunResult; +package org.apache.maven.plugin.surefire.report; import java.io.File; import java.util.Collection; +import org.apache.maven.surefire.api.suite.RunResult; + /** * This interface is used to merge reports in {@link org.apache.maven.plugin.surefire.booterclient.ForkStarter}. */ -public interface ReportsMerger -{ +public interface ReportsMerger { void runStarting(); - void mergeFromOtherFactories( Collection factories ); + + void mergeFromOtherFactories(Collection factories); + File getReportsDirectory(); + RunResult close(); } diff --git a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/report/StatelessXmlReporter.java b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/report/StatelessXmlReporter.java index 66cdf8c2b6..7a9a019d9d 100644 --- a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/report/StatelessXmlReporter.java +++ b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/report/StatelessXmlReporter.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire.report; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,12 +16,7 @@ * specific language governing permissions and limitations * under the License. */ - -import org.apache.maven.plugin.surefire.booterclient.output.InPluginProcessDumpSingleton; -import org.apache.maven.surefire.shared.utils.xml.PrettyPrintXMLWriter; -import org.apache.maven.surefire.shared.utils.xml.XMLWriter; -import org.apache.maven.surefire.extensions.StatelessReportEventListener; -import org.apache.maven.surefire.api.report.SafeThrowable; +package org.apache.maven.plugin.surefire.report; import java.io.BufferedOutputStream; import java.io.File; @@ -42,6 +35,12 @@ import java.util.StringTokenizer; import java.util.concurrent.ConcurrentLinkedDeque; +import org.apache.maven.plugin.surefire.booterclient.output.InPluginProcessDumpSingleton; +import org.apache.maven.surefire.api.report.SafeThrowable; +import org.apache.maven.surefire.extensions.StatelessReportEventListener; +import org.apache.maven.surefire.shared.utils.xml.PrettyPrintXMLWriter; +import org.apache.maven.surefire.shared.utils.xml.XMLWriter; + import static java.nio.charset.StandardCharsets.UTF_8; import static org.apache.maven.plugin.surefire.report.DefaultReporterFactory.TestResultType; import static org.apache.maven.plugin.surefire.report.FileReporterUtils.stripIllegalFilenameChars; @@ -49,7 +48,7 @@ import static org.apache.maven.plugin.surefire.report.ReportEntryType.SUCCESS; import static org.apache.maven.surefire.shared.utils.StringUtils.isBlank; -@SuppressWarnings( { "javadoc", "checkstyle:javadoctype" } ) +@SuppressWarnings({"javadoc", "checkstyle:javadoctype"}) // CHECKSTYLE_OFF: LineLength /* * XML format reporter writing to TEST-reportName[-suffix].xml file like written and read @@ -83,10 +82,8 @@ * @see Ant's format enhancement proposal * (not yet implemented by Ant 1.8.2) */ -//todo this is no more stateless due to existence of testClassMethodRunHistoryMap since of 2.19. -public class StatelessXmlReporter - implements StatelessReportEventListener -{ +// todo this is no more stateless due to existence of testClassMethodRunHistoryMap since of 2.19. +public class StatelessXmlReporter implements StatelessReportEventListener { private static final String XML_INDENT = " "; private static final String XML_NL = "\n"; @@ -115,12 +112,18 @@ public class StatelessXmlReporter private final boolean phrasedMethodName; - public StatelessXmlReporter( File reportsDirectory, String reportNameSuffix, boolean trimStackTrace, - int rerunFailingTestsCount, - Map> testClassMethodRunHistoryMap, - String xsdSchemaLocation, String xsdVersion, boolean phrasedFileName, - boolean phrasedSuiteName, boolean phrasedClassName, boolean phrasedMethodName ) - { + public StatelessXmlReporter( + File reportsDirectory, + String reportNameSuffix, + boolean trimStackTrace, + int rerunFailingTestsCount, + Map> testClassMethodRunHistoryMap, + String xsdSchemaLocation, + String xsdVersion, + boolean phrasedFileName, + boolean phrasedSuiteName, + boolean phrasedClassName, + boolean phrasedMethodName) { this.reportsDirectory = reportsDirectory; this.reportNameSuffix = reportNameSuffix; this.trimStackTrace = trimStackTrace; @@ -135,122 +138,106 @@ public StatelessXmlReporter( File reportsDirectory, String reportNameSuffix, boo } @Override - public void testSetCompleted( WrappedReportEntry testSetReportEntry, TestSetStats testSetStats ) - { + public void testSetCompleted(WrappedReportEntry testSetReportEntry, TestSetStats testSetStats) { Map>> classMethodStatistics = - arrangeMethodStatistics( testSetReportEntry, testSetStats ); + arrangeMethodStatistics(testSetReportEntry, testSetStats); // The Java Language Spec: // "Note that the close methods of resources are called in the opposite order of their creation." - try ( OutputStream outputStream = getOutputStream( testSetReportEntry ); - OutputStreamWriter fw = getWriter( outputStream ) ) - { - XMLWriter ppw = new PrettyPrintXMLWriter( new PrintWriter( fw ), XML_INDENT, XML_NL, UTF_8.name(), null ); + try (OutputStream outputStream = getOutputStream(testSetReportEntry); + OutputStreamWriter fw = getWriter(outputStream)) { + XMLWriter ppw = new PrettyPrintXMLWriter(new PrintWriter(fw), XML_INDENT, XML_NL, UTF_8.name(), null); - createTestSuiteElement( ppw, testSetReportEntry, testSetStats ); // TestSuite + createTestSuiteElement(ppw, testSetReportEntry, testSetStats); // TestSuite - showProperties( ppw, testSetReportEntry.getSystemProperties() ); + showProperties(ppw, testSetReportEntry.getSystemProperties()); - for ( Entry>> statistics : classMethodStatistics.entrySet() ) - { - for ( Entry> thisMethodRuns : statistics.getValue().entrySet() ) - { - serializeTestClass( outputStream, fw, ppw, thisMethodRuns.getValue() ); + for (Entry>> statistics : classMethodStatistics.entrySet()) { + for (Entry> thisMethodRuns : + statistics.getValue().entrySet()) { + serializeTestClass(outputStream, fw, ppw, thisMethodRuns.getValue()); } } ppw.endElement(); // TestSuite - } - catch ( IOException e ) - { + } catch (IOException e) { // It's not a test error. // This method must be sail-safe and errors are in a dump log. // The control flow must not be broken in TestSetRunListener#testSetCompleted. - InPluginProcessDumpSingleton.getSingleton() - .dumpException( e, e.getLocalizedMessage(), reportsDirectory ); + InPluginProcessDumpSingleton.getSingleton().dumpException(e, e.getLocalizedMessage(), reportsDirectory); } } private Map>> arrangeMethodStatistics( - WrappedReportEntry testSetReportEntry, TestSetStats testSetStats ) - { + WrappedReportEntry testSetReportEntry, TestSetStats testSetStats) { Map>> classMethodStatistics = new LinkedHashMap<>(); - for ( WrappedReportEntry methodEntry : aggregateCacheFromMultipleReruns( testSetReportEntry, testSetStats ) ) - { + for (WrappedReportEntry methodEntry : aggregateCacheFromMultipleReruns(testSetReportEntry, testSetStats)) { String testClassName = methodEntry.getSourceName(); - Map> stats = classMethodStatistics.get( testClassName ); - if ( stats == null ) - { + Map> stats = classMethodStatistics.get(testClassName); + if (stats == null) { stats = new LinkedHashMap<>(); - classMethodStatistics.put( testClassName, stats ); + classMethodStatistics.put(testClassName, stats); } String methodName = methodEntry.getName(); - List methodRuns = stats.get( methodName ); - if ( methodRuns == null ) - { + List methodRuns = stats.get(methodName); + if (methodRuns == null) { methodRuns = new ArrayList<>(); - stats.put( methodName, methodRuns ); + stats.put(methodName, methodRuns); } - methodRuns.add( methodEntry ); + methodRuns.add(methodEntry); } return classMethodStatistics; } - private Deque aggregateCacheFromMultipleReruns( WrappedReportEntry testSetReportEntry, - TestSetStats testSetStats ) - { + private Deque aggregateCacheFromMultipleReruns( + WrappedReportEntry testSetReportEntry, TestSetStats testSetStats) { String suiteClassName = testSetReportEntry.getSourceName(); - Deque methodRunHistory = getAddMethodRunHistoryMap( suiteClassName ); - methodRunHistory.addAll( testSetStats.getReportEntries() ); + Deque methodRunHistory = getAddMethodRunHistoryMap(suiteClassName); + methodRunHistory.addAll(testSetStats.getReportEntries()); return methodRunHistory; } - private void serializeTestClass( OutputStream outputStream, OutputStreamWriter fw, XMLWriter ppw, - List methodEntries ) - throws IOException - { - if ( rerunFailingTestsCount > 0 ) - { - serializeTestClassWithRerun( outputStream, fw, ppw, methodEntries ); - } - else - { + private void serializeTestClass( + OutputStream outputStream, OutputStreamWriter fw, XMLWriter ppw, List methodEntries) + throws IOException { + if (rerunFailingTestsCount > 0) { + serializeTestClassWithRerun(outputStream, fw, ppw, methodEntries); + } else { // rerunFailingTestsCount is smaller than 1, but for some reasons a test could be run // for more than once - serializeTestClassWithoutRerun( outputStream, fw, ppw, methodEntries ); + serializeTestClassWithoutRerun(outputStream, fw, ppw, methodEntries); } } - private void serializeTestClassWithoutRerun( OutputStream outputStream, OutputStreamWriter fw, XMLWriter ppw, - List methodEntries ) - throws IOException - { - for ( WrappedReportEntry methodEntry : methodEntries ) - { - startTestElement( ppw, methodEntry ); - if ( methodEntry.getReportEntryType() != SUCCESS ) - { - getTestProblems( fw, ppw, methodEntry, trimStackTrace, outputStream, - methodEntry.getReportEntryType().getXmlTag(), false ); + private void serializeTestClassWithoutRerun( + OutputStream outputStream, OutputStreamWriter fw, XMLWriter ppw, List methodEntries) + throws IOException { + for (WrappedReportEntry methodEntry : methodEntries) { + startTestElement(ppw, methodEntry); + if (methodEntry.getReportEntryType() != SUCCESS) { + getTestProblems( + fw, + ppw, + methodEntry, + trimStackTrace, + outputStream, + methodEntry.getReportEntryType().getXmlTag(), + false); } - createOutErrElements( fw, ppw, methodEntry, outputStream ); + createOutErrElements(fw, ppw, methodEntry, outputStream); ppw.endElement(); } } - private void serializeTestClassWithRerun( OutputStream outputStream, OutputStreamWriter fw, XMLWriter ppw, - List methodEntries ) - throws IOException - { - WrappedReportEntry firstMethodEntry = methodEntries.get( 0 ); - switch ( getTestResultType( methodEntries ) ) - { + private void serializeTestClassWithRerun( + OutputStream outputStream, OutputStreamWriter fw, XMLWriter ppw, List methodEntries) + throws IOException { + WrappedReportEntry firstMethodEntry = methodEntries.get(0); + switch (getTestResultType(methodEntries)) { case success: - for ( WrappedReportEntry methodEntry : methodEntries ) - { - if ( methodEntry.getReportEntryType() == SUCCESS ) - { - startTestElement( ppw, methodEntry ); + for (WrappedReportEntry methodEntry : methodEntries) { + if (methodEntry.getReportEntryType() == SUCCESS) { + startTestElement(ppw, methodEntry); ppw.endElement(); } } @@ -258,29 +245,35 @@ private void serializeTestClassWithRerun( OutputStream outputStream, OutputStrea case error: case failure: // When rerunFailingTestsCount is set to larger than 0 - startTestElement( ppw, firstMethodEntry ); + startTestElement(ppw, firstMethodEntry); boolean firstRun = true; - for ( WrappedReportEntry singleRunEntry : methodEntries ) - { - if ( firstRun ) - { + for (WrappedReportEntry singleRunEntry : methodEntries) { + if (firstRun) { firstRun = false; - getTestProblems( fw, ppw, singleRunEntry, trimStackTrace, outputStream, - singleRunEntry.getReportEntryType().getXmlTag(), false ); - createOutErrElements( fw, ppw, singleRunEntry, outputStream ); - } - else if ( singleRunEntry.getReportEntryType() == SKIPPED ) - { + getTestProblems( + fw, + ppw, + singleRunEntry, + trimStackTrace, + outputStream, + singleRunEntry.getReportEntryType().getXmlTag(), + false); + createOutErrElements(fw, ppw, singleRunEntry, outputStream); + } else if (singleRunEntry.getReportEntryType() == SKIPPED) { // The version 3.1.0 should produce a new XSD schema with version 3.1.0, see SUREFIRE-1986, // and the XSD schema should add a new element "rerunSkipped" // then ReportEntryType should update the enum to SKIPPED( "skipped", "", "rerunSkipped" ). // The teams should be notified - Jenkins reports. - addCommentElementTestCase( "a skipped test execution in re-run phase", fw, ppw, outputStream ); - } - else - { - getTestProblems( fw, ppw, singleRunEntry, trimStackTrace, outputStream, - singleRunEntry.getReportEntryType().getRerunXmlTag(), true ); + addCommentElementTestCase("a skipped test execution in re-run phase", fw, ppw, outputStream); + } else { + getTestProblems( + fw, + ppw, + singleRunEntry, + trimStackTrace, + outputStream, + singleRunEntry.getReportEntryType().getRerunXmlTag(), + true); } } ppw.endElement(); @@ -288,42 +281,49 @@ else if ( singleRunEntry.getReportEntryType() == SKIPPED ) case flake: WrappedReportEntry successful = null; // Get the run time of the first successful run - for ( WrappedReportEntry singleRunEntry : methodEntries ) - { - if ( singleRunEntry.getReportEntryType() == SUCCESS ) - { + for (WrappedReportEntry singleRunEntry : methodEntries) { + if (singleRunEntry.getReportEntryType() == SUCCESS) { successful = singleRunEntry; break; } } - WrappedReportEntry firstOrSuccessful = successful == null ? methodEntries.get( 0 ) : successful; - startTestElement( ppw, firstOrSuccessful ); - for ( WrappedReportEntry singleRunEntry : methodEntries ) - { - if ( singleRunEntry.getReportEntryType() != SUCCESS ) - { - getTestProblems( fw, ppw, singleRunEntry, trimStackTrace, outputStream, - singleRunEntry.getReportEntryType().getFlakyXmlTag(), true ); + WrappedReportEntry firstOrSuccessful = successful == null ? methodEntries.get(0) : successful; + startTestElement(ppw, firstOrSuccessful); + for (WrappedReportEntry singleRunEntry : methodEntries) { + if (singleRunEntry.getReportEntryType() != SUCCESS) { + getTestProblems( + fw, + ppw, + singleRunEntry, + trimStackTrace, + outputStream, + singleRunEntry.getReportEntryType().getFlakyXmlTag(), + true); } } ppw.endElement(); break; case skipped: - startTestElement( ppw, firstMethodEntry ); - getTestProblems( fw, ppw, firstMethodEntry, trimStackTrace, outputStream, - firstMethodEntry.getReportEntryType().getXmlTag(), false ); + startTestElement(ppw, firstMethodEntry); + getTestProblems( + fw, + ppw, + firstMethodEntry, + trimStackTrace, + outputStream, + firstMethodEntry.getReportEntryType().getXmlTag(), + false); ppw.endElement(); break; default: - throw new IllegalStateException( "Get unknown test result type" ); + throw new IllegalStateException("Get unknown test result type"); } } /** * Clean testClassMethodRunHistoryMap */ - public void cleanTestHistoryMap() - { + public void cleanTestHistoryMap() { testClassMethodRunHistoryMap.clear(); } @@ -333,186 +333,167 @@ public void cleanTestHistoryMap() * @param methodEntryList the list of runs for a given test * @return the TestResultType for the given test */ - private TestResultType getTestResultType( List methodEntryList ) - { + private TestResultType getTestResultType(List methodEntryList) { List testResultTypeList = new ArrayList<>(); - for ( WrappedReportEntry singleRunEntry : methodEntryList ) - { - testResultTypeList.add( singleRunEntry.getReportEntryType() ); + for (WrappedReportEntry singleRunEntry : methodEntryList) { + testResultTypeList.add(singleRunEntry.getReportEntryType()); } - return DefaultReporterFactory.getTestResultType( testResultTypeList, rerunFailingTestsCount ); + return DefaultReporterFactory.getTestResultType(testResultTypeList, rerunFailingTestsCount); } - private Deque getAddMethodRunHistoryMap( String testClassName ) - { - Deque methodRunHistory = testClassMethodRunHistoryMap.get( testClassName ); - if ( methodRunHistory == null ) - { + private Deque getAddMethodRunHistoryMap(String testClassName) { + Deque methodRunHistory = testClassMethodRunHistoryMap.get(testClassName); + if (methodRunHistory == null) { methodRunHistory = new ConcurrentLinkedDeque<>(); - testClassMethodRunHistoryMap.put( testClassName == null ? "null" : testClassName, methodRunHistory ); + testClassMethodRunHistoryMap.put(testClassName == null ? "null" : testClassName, methodRunHistory); } return methodRunHistory; } - private OutputStream getOutputStream( WrappedReportEntry testSetReportEntry ) - throws IOException - { - File reportFile = getReportFile( testSetReportEntry ); + private OutputStream getOutputStream(WrappedReportEntry testSetReportEntry) throws IOException { + File reportFile = getReportFile(testSetReportEntry); File reportDir = reportFile.getParentFile(); //noinspection ResultOfMethodCallIgnored reportFile.delete(); //noinspection ResultOfMethodCallIgnored reportDir.mkdirs(); - return new BufferedOutputStream( new FileOutputStream( reportFile ), 64 * 1024 ); + return new BufferedOutputStream(new FileOutputStream(reportFile), 64 * 1024); } - private static OutputStreamWriter getWriter( OutputStream fos ) - { - return new OutputStreamWriter( fos, UTF_8 ); + private static OutputStreamWriter getWriter(OutputStream fos) { + return new OutputStreamWriter(fos, UTF_8); } - private File getReportFile( WrappedReportEntry report ) - { - String reportName = "TEST-" + ( phrasedFileName ? report.getReportSourceName() : report.getSourceName() ); - String customizedReportName = isBlank( reportNameSuffix ) ? reportName : reportName + "-" + reportNameSuffix; - return new File( reportsDirectory, stripIllegalFilenameChars( customizedReportName + ".xml" ) ); + private File getReportFile(WrappedReportEntry report) { + String reportName = "TEST-" + (phrasedFileName ? report.getReportSourceName() : report.getSourceName()); + String customizedReportName = isBlank(reportNameSuffix) ? reportName : reportName + "-" + reportNameSuffix; + return new File(reportsDirectory, stripIllegalFilenameChars(customizedReportName + ".xml")); } - private void startTestElement( XMLWriter ppw, WrappedReportEntry report ) - throws IOException - { - ppw.startElement( "testcase" ); + private void startTestElement(XMLWriter ppw, WrappedReportEntry report) throws IOException { + ppw.startElement("testcase"); String name = phrasedMethodName ? report.getReportName() : report.getName(); - ppw.addAttribute( "name", name == null ? "" : extraEscapeAttribute( name ) ); + ppw.addAttribute("name", name == null ? "" : extraEscapeAttribute(name)); - if ( report.getGroup() != null ) - { - ppw.addAttribute( "group", report.getGroup() ); + if (report.getGroup() != null) { + ppw.addAttribute("group", report.getGroup()); } - String className = phrasedClassName ? report.getReportSourceName( reportNameSuffix ) - : report.getSourceName( reportNameSuffix ); - if ( className != null ) - { - ppw.addAttribute( "classname", extraEscapeAttribute( className ) ); + String className = phrasedClassName + ? report.getReportSourceName(reportNameSuffix) + : report.getSourceName(reportNameSuffix); + if (className != null) { + ppw.addAttribute("classname", extraEscapeAttribute(className)); } - ppw.addAttribute( "time", report.elapsedTimeAsString() ); + ppw.addAttribute("time", report.elapsedTimeAsString()); } - private void createTestSuiteElement( XMLWriter ppw, WrappedReportEntry report, TestSetStats testSetStats ) - throws IOException - { - ppw.startElement( "testsuite" ); + private void createTestSuiteElement(XMLWriter ppw, WrappedReportEntry report, TestSetStats testSetStats) + throws IOException { + ppw.startElement("testsuite"); - ppw.addAttribute( "xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance" ); - ppw.addAttribute( "xsi:noNamespaceSchemaLocation", xsdSchemaLocation ); - ppw.addAttribute( "version", xsdVersion ); + ppw.addAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance"); + ppw.addAttribute("xsi:noNamespaceSchemaLocation", xsdSchemaLocation); + ppw.addAttribute("version", xsdVersion); - String reportName = phrasedSuiteName ? report.getReportSourceName( reportNameSuffix ) - : report.getSourceName( reportNameSuffix ); - ppw.addAttribute( "name", reportName == null ? "" : extraEscapeAttribute( reportName ) ); + String reportName = phrasedSuiteName + ? report.getReportSourceName(reportNameSuffix) + : report.getSourceName(reportNameSuffix); + ppw.addAttribute("name", reportName == null ? "" : extraEscapeAttribute(reportName)); - if ( report.getGroup() != null ) - { - ppw.addAttribute( "group", report.getGroup() ); + if (report.getGroup() != null) { + ppw.addAttribute("group", report.getGroup()); } - ppw.addAttribute( "time", report.elapsedTimeAsString() ); + ppw.addAttribute("time", report.elapsedTimeAsString()); - ppw.addAttribute( "tests", String.valueOf( testSetStats.getCompletedCount() ) ); + ppw.addAttribute("tests", String.valueOf(testSetStats.getCompletedCount())); - ppw.addAttribute( "errors", String.valueOf( testSetStats.getErrors() ) ); + ppw.addAttribute("errors", String.valueOf(testSetStats.getErrors())); - ppw.addAttribute( "skipped", String.valueOf( testSetStats.getSkipped() ) ); + ppw.addAttribute("skipped", String.valueOf(testSetStats.getSkipped())); - ppw.addAttribute( "failures", String.valueOf( testSetStats.getFailures() ) ); + ppw.addAttribute("failures", String.valueOf(testSetStats.getFailures())); } - private static void getTestProblems( OutputStreamWriter outputStreamWriter, XMLWriter ppw, - WrappedReportEntry report, boolean trimStackTrace, OutputStream fw, - String testErrorType, boolean createOutErrElementsInside ) - throws IOException - { - ppw.startElement( testErrorType ); - - String stackTrace = report.getStackTrace( trimStackTrace ); - - if ( report.getMessage() != null && !report.getMessage().isEmpty() ) - { - ppw.addAttribute( "message", extraEscapeAttribute( report.getMessage() ) ); + private static void getTestProblems( + OutputStreamWriter outputStreamWriter, + XMLWriter ppw, + WrappedReportEntry report, + boolean trimStackTrace, + OutputStream fw, + String testErrorType, + boolean createOutErrElementsInside) + throws IOException { + ppw.startElement(testErrorType); + + String stackTrace = report.getStackTrace(trimStackTrace); + + if (report.getMessage() != null && !report.getMessage().isEmpty()) { + ppw.addAttribute("message", extraEscapeAttribute(report.getMessage())); } - if ( report.getStackTraceWriter() != null ) - { + if (report.getStackTraceWriter() != null) { //noinspection ThrowableResultOfMethodCallIgnored SafeThrowable t = report.getStackTraceWriter().getThrowable(); - if ( t != null ) - { - if ( t.getMessage() != null ) - { - int delimiter = stackTrace.indexOf( ":" ); - String type = delimiter == -1 ? stackTrace : stackTrace.substring( 0, delimiter ); - ppw.addAttribute( "type", type ); - } - else - { - ppw.addAttribute( "type", new StringTokenizer( stackTrace ).nextToken() ); + if (t != null) { + if (t.getMessage() != null) { + int delimiter = stackTrace.indexOf(":"); + String type = delimiter == -1 ? stackTrace : stackTrace.substring(0, delimiter); + ppw.addAttribute("type", type); + } else { + ppw.addAttribute("type", new StringTokenizer(stackTrace).nextToken()); } } } boolean hasNestedElements = createOutErrElementsInside & stackTrace != null; - if ( stackTrace != null ) - { - if ( hasNestedElements ) - { - ppw.startElement( "stackTrace" ); + if (stackTrace != null) { + if (hasNestedElements) { + ppw.startElement("stackTrace"); } - extraEscapeElementValue( stackTrace, outputStreamWriter, ppw, fw ); + extraEscapeElementValue(stackTrace, outputStreamWriter, ppw, fw); - if ( hasNestedElements ) - { + if (hasNestedElements) { ppw.endElement(); } } - if ( createOutErrElementsInside ) - { - createOutErrElements( outputStreamWriter, ppw, report, fw ); + if (createOutErrElementsInside) { + createOutErrElements(outputStreamWriter, ppw, report, fw); } ppw.endElement(); // entry type } // Create system-out and system-err elements - private static void createOutErrElements( OutputStreamWriter outputStreamWriter, XMLWriter ppw, - WrappedReportEntry report, OutputStream fw ) - throws IOException - { - EncodingOutputStream eos = new EncodingOutputStream( fw ); - addOutputStreamElement( outputStreamWriter, eos, ppw, report.getStdout(), "system-out" ); - addOutputStreamElement( outputStreamWriter, eos, ppw, report.getStdErr(), "system-err" ); + private static void createOutErrElements( + OutputStreamWriter outputStreamWriter, XMLWriter ppw, WrappedReportEntry report, OutputStream fw) + throws IOException { + EncodingOutputStream eos = new EncodingOutputStream(fw); + addOutputStreamElement(outputStreamWriter, eos, ppw, report.getStdout(), "system-out"); + addOutputStreamElement(outputStreamWriter, eos, ppw, report.getStdErr(), "system-err"); } - private static void addOutputStreamElement( OutputStreamWriter outputStreamWriter, - EncodingOutputStream eos, XMLWriter xmlWriter, - Utf8RecodingDeferredFileOutputStream utf8RecodingDeferredFileOutputStream, - String name ) - throws IOException - { - if ( utf8RecodingDeferredFileOutputStream != null && utf8RecodingDeferredFileOutputStream.getByteCount() > 0 ) - { - xmlWriter.startElement( name ); - xmlWriter.writeText( "" ); // Cheat sax to emit element + private static void addOutputStreamElement( + OutputStreamWriter outputStreamWriter, + EncodingOutputStream eos, + XMLWriter xmlWriter, + Utf8RecodingDeferredFileOutputStream utf8RecodingDeferredFileOutputStream, + String name) + throws IOException { + if (utf8RecodingDeferredFileOutputStream != null && utf8RecodingDeferredFileOutputStream.getByteCount() > 0) { + xmlWriter.startElement(name); + xmlWriter.writeText(""); // Cheat sax to emit element outputStreamWriter.flush(); - eos.getUnderlying().write( ByteConstantsHolder.CDATA_START_BYTES ); // emit cdata - utf8RecodingDeferredFileOutputStream.writeTo( eos ); + eos.getUnderlying().write(ByteConstantsHolder.CDATA_START_BYTES); // emit cdata + utf8RecodingDeferredFileOutputStream.writeTo(eos); utf8RecodingDeferredFileOutputStream.free(); - eos.getUnderlying().write( ByteConstantsHolder.CDATA_END_BYTES ); + eos.getUnderlying().write(ByteConstantsHolder.CDATA_END_BYTES); eos.flush(); xmlWriter.endElement(); } @@ -524,25 +505,21 @@ private static void addOutputStreamElement( OutputStreamWriter outputStreamWrite * * @param xmlWriter The test suite to report to */ - private static void showProperties( XMLWriter xmlWriter, Map systemProperties ) - throws IOException - { - xmlWriter.startElement( "properties" ); - for ( final Entry entry : systemProperties.entrySet() ) - { + private static void showProperties(XMLWriter xmlWriter, Map systemProperties) throws IOException { + xmlWriter.startElement("properties"); + for (final Entry entry : systemProperties.entrySet()) { final String key = entry.getKey(); String value = entry.getValue(); - if ( value == null ) - { + if (value == null) { value = "null"; } - xmlWriter.startElement( "property" ); + xmlWriter.startElement("property"); - xmlWriter.addAttribute( "name", key ); + xmlWriter.addAttribute("name", key); - xmlWriter.addAttribute( "value", extraEscapeAttribute( value ) ); + xmlWriter.addAttribute("value", extraEscapeAttribute(value)); xmlWriter.endElement(); } @@ -555,10 +532,9 @@ private static void showProperties( XMLWriter xmlWriter, Map sys * @param message The string * @return The escaped string or returns itself if all characters are legal */ - private static String extraEscapeAttribute( String message ) - { + private static String extraEscapeAttribute(String message) { // Someday convert to xml 1.1 which handles everything but 0 inside string - return containsEscapesIllegalXml10( message ) ? escapeXml( message, true ) : message; + return containsEscapesIllegalXml10(message) ? escapeXml(message, true) : message; } /** @@ -566,116 +542,93 @@ private static String extraEscapeAttribute( String message ) * * @param message The string */ - private static void extraEscapeElementValue( String message, OutputStreamWriter outputStreamWriter, - XMLWriter xmlWriter, OutputStream fw ) - throws IOException - { + private static void extraEscapeElementValue( + String message, OutputStreamWriter outputStreamWriter, XMLWriter xmlWriter, OutputStream fw) + throws IOException { // Someday convert to xml 1.1 which handles everything but 0 inside string - if ( containsEscapesIllegalXml10( message ) ) - { - xmlWriter.writeText( escapeXml( message, false ) ); - } - else - { - EncodingOutputStream eos = new EncodingOutputStream( fw ); - xmlWriter.writeText( "" ); // Cheat sax to emit element + if (containsEscapesIllegalXml10(message)) { + xmlWriter.writeText(escapeXml(message, false)); + } else { + EncodingOutputStream eos = new EncodingOutputStream(fw); + xmlWriter.writeText(""); // Cheat sax to emit element outputStreamWriter.flush(); - eos.getUnderlying().write( ByteConstantsHolder.CDATA_START_BYTES ); - eos.write( message.getBytes( UTF_8 ) ); - eos.getUnderlying().write( ByteConstantsHolder.CDATA_END_BYTES ); + eos.getUnderlying().write(ByteConstantsHolder.CDATA_START_BYTES); + eos.write(message.getBytes(UTF_8)); + eos.getUnderlying().write(ByteConstantsHolder.CDATA_END_BYTES); eos.flush(); } } // todo: SUREFIRE-1986 - private static void addCommentElementTestCase( String comment, OutputStreamWriter outputStreamWriter, - XMLWriter xmlWriter, OutputStream fw ) - throws IOException - { - xmlWriter.writeText( "" ); // Cheat sax to emit element + private static void addCommentElementTestCase( + String comment, OutputStreamWriter outputStreamWriter, XMLWriter xmlWriter, OutputStream fw) + throws IOException { + xmlWriter.writeText(""); // Cheat sax to emit element outputStreamWriter.flush(); - fw.write( XML_NL.getBytes( UTF_8 ) ); - fw.write( XML_INDENT.getBytes( UTF_8 ) ); - fw.write( XML_INDENT.getBytes( UTF_8 ) ); - fw.write( ByteConstantsHolder.COMMENT_START ); - fw.write( comment.getBytes( UTF_8 ) ); - fw.write( ByteConstantsHolder.COMMENT_END ); - fw.write( XML_NL.getBytes( UTF_8 ) ); - fw.write( XML_INDENT.getBytes( UTF_8 ) ); + fw.write(XML_NL.getBytes(UTF_8)); + fw.write(XML_INDENT.getBytes(UTF_8)); + fw.write(XML_INDENT.getBytes(UTF_8)); + fw.write(ByteConstantsHolder.COMMENT_START); + fw.write(comment.getBytes(UTF_8)); + fw.write(ByteConstantsHolder.COMMENT_END); + fw.write(XML_NL.getBytes(UTF_8)); + fw.write(XML_INDENT.getBytes(UTF_8)); fw.flush(); } - private static final class EncodingOutputStream - extends FilterOutputStream - { + private static final class EncodingOutputStream extends FilterOutputStream { private int c1; private int c2; - EncodingOutputStream( OutputStream out ) - { - super( out ); + EncodingOutputStream(OutputStream out) { + super(out); } - OutputStream getUnderlying() - { + OutputStream getUnderlying() { return out; } - private boolean isCdataEndBlock( int c ) - { + private boolean isCdataEndBlock(int c) { return c1 == ']' && c2 == ']' && c == '>'; } @Override - public void write( int b ) - throws IOException - { - if ( isCdataEndBlock( b ) ) - { - out.write( ByteConstantsHolder.CDATA_ESCAPE_STRING_BYTES ); - } - else if ( isIllegalEscape( b ) ) - { + public void write(int b) throws IOException { + if (isCdataEndBlock(b)) { + out.write(ByteConstantsHolder.CDATA_ESCAPE_STRING_BYTES); + } else if (isIllegalEscape(b)) { // uh-oh! This character is illegal in XML 1.0! // http://www.w3.org/TR/1998/REC-xml-19980210#charsets // we're going to deliberately doubly-XML escape it... // there's nothing better we can do! :-( // SUREFIRE-456 - out.write( ByteConstantsHolder.AMP_BYTES ); - out.write( String.valueOf( b ).getBytes( UTF_8 ) ); - out.write( ';' ); // & Will be encoded to amp inside xml encodingSHO - } - else - { - out.write( b ); + out.write(ByteConstantsHolder.AMP_BYTES); + out.write(String.valueOf(b).getBytes(UTF_8)); + out.write(';'); // & Will be encoded to amp inside xml encodingSHO + } else { + out.write(b); } c1 = c2; c2 = b; } } - private static boolean containsEscapesIllegalXml10( String message ) - { + private static boolean containsEscapesIllegalXml10(String message) { int size = message.length(); - for ( int i = 0; i < size; i++ ) - { - if ( isIllegalEscape( message.charAt( i ) ) ) - { + for (int i = 0; i < size; i++) { + if (isIllegalEscape(message.charAt(i))) { return true; } - } return false; } - private static boolean isIllegalEscape( char c ) - { - return isIllegalEscape( (int) c ); + private static boolean isIllegalEscape(char c) { + return isIllegalEscape((int) c); } - private static boolean isIllegalEscape( int c ) - { + private static boolean isIllegalEscape(int c) { return c >= 0 && c < 32 && c != '\n' && c != '\r' && c != '\t'; } @@ -686,42 +639,37 @@ private static boolean isIllegalEscape( int c ) * @param attribute true if the escaped value is inside an attribute * @return The escaped string */ - private static String escapeXml( String text, boolean attribute ) - { - StringBuilder sb = new StringBuilder( text.length() * 2 ); - for ( int i = 0; i < text.length(); i++ ) - { - char c = text.charAt( i ); - if ( isIllegalEscape( c ) ) - { + private static String escapeXml(String text, boolean attribute) { + StringBuilder sb = new StringBuilder(text.length() * 2); + for (int i = 0; i < text.length(); i++) { + char c = text.charAt(i); + if (isIllegalEscape(c)) { // uh-oh! This character is illegal in XML 1.0! // http://www.w3.org/TR/1998/REC-xml-19980210#charsets // we're going to deliberately doubly-XML escape it... // there's nothing better we can do! :-( // SUREFIRE-456 - sb.append( attribute ? "&#" : "&#" ).append( (int) c ).append( - ';' ); // & Will be encoded to amp inside xml encodingSHO - } - else - { - sb.append( c ); + sb.append(attribute ? "&#" : "&#") + .append((int) c) + .append(';'); // & Will be encoded to amp inside xml encodingSHO + } else { + sb.append(c); } } return sb.toString(); } - private static final class ByteConstantsHolder - { - private static final byte[] CDATA_START_BYTES = "".getBytes( UTF_8 ); + private static final byte[] CDATA_END_BYTES = "]]>".getBytes(UTF_8); - private static final byte[] CDATA_ESCAPE_STRING_BYTES = "]]>".getBytes( UTF_8 ); + private static final byte[] CDATA_ESCAPE_STRING_BYTES = "]]>".getBytes(UTF_8); - private static final byte[] AMP_BYTES = "&#".getBytes( UTF_8 ); + private static final byte[] AMP_BYTES = "&#".getBytes(UTF_8); - private static final byte[] COMMENT_START = " ".getBytes( UTF_8 ); + private static final byte[] COMMENT_END = " --> ".getBytes(UTF_8); } } diff --git a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/report/TestMethodStats.java b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/report/TestMethodStats.java index 96bca2688c..d3abb53a79 100644 --- a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/report/TestMethodStats.java +++ b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/report/TestMethodStats.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire.report; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.surefire.report; import org.apache.maven.surefire.api.report.StackTraceWriter; @@ -28,33 +27,28 @@ * @author Qingzhou Luo * */ -public class TestMethodStats -{ +public class TestMethodStats { private final String testClassMethodName; private final ReportEntryType resultType; private final StackTraceWriter stackTraceWriter; - public TestMethodStats( String testClassMethodName, ReportEntryType resultType, StackTraceWriter stackTraceWriter ) - { + public TestMethodStats(String testClassMethodName, ReportEntryType resultType, StackTraceWriter stackTraceWriter) { this.testClassMethodName = testClassMethodName; this.resultType = resultType; this.stackTraceWriter = stackTraceWriter; } - public String getTestClassMethodName() - { + public String getTestClassMethodName() { return testClassMethodName; } - public ReportEntryType getResultType() - { + public ReportEntryType getResultType() { return resultType; } - public StackTraceWriter getStackTraceWriter() - { + public StackTraceWriter getStackTraceWriter() { return stackTraceWriter; } } diff --git a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/report/TestSetRunListener.java b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/report/TestSetRunListener.java index d795bf828a..5e90fb0559 100644 --- a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/report/TestSetRunListener.java +++ b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/report/TestSetRunListener.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire.report; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.surefire.report; import java.io.IOException; import java.util.Collections; @@ -46,9 +45,7 @@ * * @author Kristian Rosenvold */ -public class TestSetRunListener - implements TestReportListener -{ +public class TestSetRunListener implements TestReportListener { private final Queue testMethodStats = new ConcurrentLinkedQueue<>(); private final TestSetStats detailsForThis; @@ -67,161 +64,136 @@ public class TestSetRunListener private final Object lock; - private Utf8RecodingDeferredFileOutputStream testStdOut = initDeferred( "stdout" ); - - private Utf8RecodingDeferredFileOutputStream testStdErr = initDeferred( "stderr" ); - - @SuppressWarnings( "checkstyle:parameternumber" ) - public TestSetRunListener( StatelessTestsetInfoConsoleReportEventListener - consoleReporter, - StatelessTestsetInfoFileReportEventListener - fileReporter, - StatelessReportEventListener simpleXMLReporter, - ConsoleOutputReportEventListener testOutputReceiver, - StatisticsReporter statisticsReporter, boolean trimStackTrace, - boolean isPlainFormat, boolean briefOrPlainFormat, Object lock ) - { + private Utf8RecodingDeferredFileOutputStream testStdOut = initDeferred("stdout"); + + private Utf8RecodingDeferredFileOutputStream testStdErr = initDeferred("stderr"); + + @SuppressWarnings("checkstyle:parameternumber") + public TestSetRunListener( + StatelessTestsetInfoConsoleReportEventListener consoleReporter, + StatelessTestsetInfoFileReportEventListener fileReporter, + StatelessReportEventListener simpleXMLReporter, + ConsoleOutputReportEventListener testOutputReceiver, + StatisticsReporter statisticsReporter, + boolean trimStackTrace, + boolean isPlainFormat, + boolean briefOrPlainFormat, + Object lock) { this.consoleReporter = consoleReporter; this.fileReporter = fileReporter; this.statisticsReporter = statisticsReporter; this.simpleXMLReporter = simpleXMLReporter; this.testOutputReceiver = testOutputReceiver; this.briefOrPlainFormat = briefOrPlainFormat; - detailsForThis = new TestSetStats( trimStackTrace, isPlainFormat ); + detailsForThis = new TestSetStats(trimStackTrace, isPlainFormat); this.lock = lock; } @Override - public boolean isDebugEnabled() - { + public boolean isDebugEnabled() { return consoleReporter.getConsoleLogger().isDebugEnabled(); } @Override - public void debug( String message ) - { - synchronized ( lock ) - { - consoleReporter.getConsoleLogger().debug( trimTrailingNewLine( message ) ); + public void debug(String message) { + synchronized (lock) { + consoleReporter.getConsoleLogger().debug(trimTrailingNewLine(message)); } } @Override - public boolean isInfoEnabled() - { + public boolean isInfoEnabled() { return consoleReporter.getConsoleLogger().isInfoEnabled(); } @Override - public void info( String message ) - { - synchronized ( lock ) - { - consoleReporter.getConsoleLogger().info( trimTrailingNewLine( message ) ); + public void info(String message) { + synchronized (lock) { + consoleReporter.getConsoleLogger().info(trimTrailingNewLine(message)); } } @Override - public boolean isWarnEnabled() - { + public boolean isWarnEnabled() { return consoleReporter.getConsoleLogger().isWarnEnabled(); } @Override - public void warning( String message ) - { - synchronized ( lock ) - { - consoleReporter.getConsoleLogger().warning( trimTrailingNewLine( message ) ); + public void warning(String message) { + synchronized (lock) { + consoleReporter.getConsoleLogger().warning(trimTrailingNewLine(message)); } } @Override - public boolean isErrorEnabled() - { + public boolean isErrorEnabled() { return consoleReporter.getConsoleLogger().isErrorEnabled(); } @Override - public void error( String message ) - { - synchronized ( lock ) - { - consoleReporter.getConsoleLogger().error( trimTrailingNewLine( message ) ); + public void error(String message) { + synchronized (lock) { + consoleReporter.getConsoleLogger().error(trimTrailingNewLine(message)); } } @Override - public void error( String message, Throwable t ) - { - synchronized ( lock ) - { - consoleReporter.getConsoleLogger().error( trimTrailingNewLine( message ), t ); + public void error(String message, Throwable t) { + synchronized (lock) { + consoleReporter.getConsoleLogger().error(trimTrailingNewLine(message), t); } } @Override - public void error( Throwable t ) - { - synchronized ( lock ) - { - consoleReporter.getConsoleLogger().error( t ); + public void error(Throwable t) { + synchronized (lock) { + consoleReporter.getConsoleLogger().error(t); } } @Override - public void writeTestOutput( TestOutputReportEntry reportEntry ) - { - try - { - synchronized ( lock ) - { + public void writeTestOutput(TestOutputReportEntry reportEntry) { + try { + synchronized (lock) { Utf8RecodingDeferredFileOutputStream stream = reportEntry.isStdOut() ? testStdOut : testStdErr; - stream.write( reportEntry.getLog(), reportEntry.isNewLine() ); - testOutputReceiver.writeTestOutput( reportEntry ); + stream.write(reportEntry.getLog(), reportEntry.isNewLine()); + testOutputReceiver.writeTestOutput(reportEntry); } - } - catch ( IOException e ) - { - throw new RuntimeException( e ); + } catch (IOException e) { + throw new RuntimeException(e); } } @Override - public void testSetStarting( TestSetReportEntry report ) - { + public void testSetStarting(TestSetReportEntry report) { detailsForThis.testSetStart(); - consoleReporter.testSetStarting( report ); - testOutputReceiver.testSetStarting( report ); + consoleReporter.testSetStarting(report); + testOutputReceiver.testSetStarting(report); } - private void clearCapture() - { - if ( testStdOut != null ) - { + private void clearCapture() { + if (testStdOut != null) { testStdOut.commit(); } - if ( testStdErr != null ) - { + if (testStdErr != null) { testStdErr.commit(); } - testStdOut = initDeferred( "stdout" ); - testStdErr = initDeferred( "stderr" ); + testStdOut = initDeferred("stdout"); + testStdErr = initDeferred("stderr"); } @Override - public void testSetCompleted( TestSetReportEntry report ) - { - final WrappedReportEntry wrap = wrapTestSet( report ); + public void testSetCompleted(TestSetReportEntry report) { + final WrappedReportEntry wrap = wrapTestSet(report); final List testResults = briefOrPlainFormat ? detailsForThis.getTestResults() : Collections.emptyList(); - fileReporter.testSetCompleted( wrap, detailsForThis, testResults ); - simpleXMLReporter.testSetCompleted( wrap, detailsForThis ); + fileReporter.testSetCompleted(wrap, detailsForThis, testResults); + simpleXMLReporter.testSetCompleted(wrap, detailsForThis); statisticsReporter.testSetCompleted(); - consoleReporter.testSetCompleted( wrap, detailsForThis, testResults ); - testOutputReceiver.testSetCompleted( wrap ); + consoleReporter.testSetCompleted(wrap, detailsForThis, testResults); + testOutputReceiver.testSetCompleted(wrap); consoleReporter.reset(); wrap.getStdout().free(); @@ -237,35 +209,31 @@ public void testSetCompleted( TestSetReportEntry report ) // ---------------------------------------------------------------------- @Override - public void testStarting( ReportEntry report ) - { + public void testStarting(ReportEntry report) { detailsForThis.testStart(); } @Override - public void testSucceeded( ReportEntry reportEntry ) - { - WrappedReportEntry wrapped = wrap( reportEntry, SUCCESS ); - detailsForThis.testSucceeded( wrapped ); - statisticsReporter.testSucceeded( reportEntry ); + public void testSucceeded(ReportEntry reportEntry) { + WrappedReportEntry wrapped = wrap(reportEntry, SUCCESS); + detailsForThis.testSucceeded(wrapped); + statisticsReporter.testSucceeded(reportEntry); clearCapture(); } @Override - public void testError( ReportEntry reportEntry ) - { - WrappedReportEntry wrapped = wrap( reportEntry, ERROR ); - detailsForThis.testError( wrapped ); - statisticsReporter.testError( reportEntry ); + public void testError(ReportEntry reportEntry) { + WrappedReportEntry wrapped = wrap(reportEntry, ERROR); + detailsForThis.testError(wrapped); + statisticsReporter.testError(reportEntry); clearCapture(); } @Override - public void testFailed( ReportEntry reportEntry ) - { - WrappedReportEntry wrapped = wrap( reportEntry, FAILURE ); - detailsForThis.testFailure( wrapped ); - statisticsReporter.testFailed( reportEntry ); + public void testFailed(ReportEntry reportEntry) { + WrappedReportEntry wrapped = wrap(reportEntry, FAILURE); + detailsForThis.testFailure(wrapped); + statisticsReporter.testFailed(reportEntry); clearCapture(); } @@ -274,79 +242,71 @@ public void testFailed( ReportEntry reportEntry ) // ---------------------------------------------------------------------- @Override - public void testSkipped( ReportEntry reportEntry ) - { - WrappedReportEntry wrapped = wrap( reportEntry, SKIPPED ); - detailsForThis.testSkipped( wrapped ); - statisticsReporter.testSkipped( reportEntry ); + public void testSkipped(ReportEntry reportEntry) { + WrappedReportEntry wrapped = wrap(reportEntry, SKIPPED); + detailsForThis.testSkipped(wrapped); + statisticsReporter.testSkipped(reportEntry); clearCapture(); } @Override - public void testExecutionSkippedByUser() - { + public void testExecutionSkippedByUser() { clearCapture(); } @Override - public void testAssumptionFailure( ReportEntry report ) - { - testSkipped( report ); + public void testAssumptionFailure(ReportEntry report) { + testSkipped(report); } - private WrappedReportEntry wrap( ReportEntry other, ReportEntryType reportEntryType ) - { + private WrappedReportEntry wrap(ReportEntry other, ReportEntryType reportEntryType) { int estimatedElapsed = 0; - if ( reportEntryType != SKIPPED ) - { + if (reportEntryType != SKIPPED) { Integer etime = other.getElapsed(); estimatedElapsed = etime == null ? detailsForThis.getElapsedSinceLastStart() : etime; } - return new WrappedReportEntry( other, reportEntryType, estimatedElapsed, testStdOut, testStdErr ); + return new WrappedReportEntry(other, reportEntryType, estimatedElapsed, testStdOut, testStdErr); } - private WrappedReportEntry wrapTestSet( TestSetReportEntry other ) - { - return new WrappedReportEntry( other, null, other.getElapsed() != null - ? other.getElapsed() - : detailsForThis.getElapsedSinceTestSetStart(), testStdOut, testStdErr, other.getSystemProperties() ); + private WrappedReportEntry wrapTestSet(TestSetReportEntry other) { + return new WrappedReportEntry( + other, + null, + other.getElapsed() != null ? other.getElapsed() : detailsForThis.getElapsedSinceTestSetStart(), + testStdOut, + testStdErr, + other.getSystemProperties()); } - public void close() - { + public void close() { testOutputReceiver.close(); } - private void addTestMethodStats() - { - for ( WrappedReportEntry reportEntry : detailsForThis.getReportEntries() ) - { - TestMethodStats methodStats = - new TestMethodStats( reportEntry.getClassMethodName(), reportEntry.getReportEntryType(), - reportEntry.getStackTraceWriter() ); - testMethodStats.add( methodStats ); + private void addTestMethodStats() { + for (WrappedReportEntry reportEntry : detailsForThis.getReportEntries()) { + TestMethodStats methodStats = new TestMethodStats( + reportEntry.getClassMethodName(), + reportEntry.getReportEntryType(), + reportEntry.getStackTraceWriter()); + testMethodStats.add(methodStats); } } - public Queue getTestMethodStats() - { + public Queue getTestMethodStats() { return testMethodStats; } - private static String trimTrailingNewLine( final String message ) - { - final int e = message == null ? 0 : lineBoundSymbolWidth( message ); - return message != null && e != 0 ? message.substring( 0, message.length() - e ) : message; + private static String trimTrailingNewLine(final String message) { + final int e = message == null ? 0 : lineBoundSymbolWidth(message); + return message != null && e != 0 ? message.substring(0, message.length() - e) : message; } - private static int lineBoundSymbolWidth( String message ) - { - return message.endsWith( "\r\n" ) ? 2 : ( message.endsWith( "\n" ) || message.endsWith( "\r" ) ? 1 : 0 ); + private static int lineBoundSymbolWidth(String message) { + return message.endsWith("\r\n") ? 2 : (message.endsWith("\n") || message.endsWith("\r") ? 1 : 0); } - private static Utf8RecodingDeferredFileOutputStream initDeferred( String channel ) - { - return new Utf8RecodingDeferredFileOutputStream( channel ); + private static Utf8RecodingDeferredFileOutputStream initDeferred(String channel) { + return new Utf8RecodingDeferredFileOutputStream(channel); } } diff --git a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/report/TestSetStats.java b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/report/TestSetStats.java index 57c18241da..6e79000dc7 100644 --- a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/report/TestSetStats.java +++ b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/report/TestSetStats.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire.report; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,9 +16,7 @@ * specific language governing permissions and limitations * under the License. */ - -import org.apache.maven.surefire.shared.utils.logging.MessageBuilder; -import org.apache.maven.surefire.api.report.ReportEntry; +package org.apache.maven.plugin.surefire.report; import java.util.ArrayList; import java.util.Collection; @@ -28,14 +24,16 @@ import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; -import static org.apache.maven.surefire.shared.utils.logging.MessageUtils.buffer; +import org.apache.maven.surefire.api.report.ReportEntry; +import org.apache.maven.surefire.shared.utils.logging.MessageBuilder; + import static org.apache.maven.surefire.api.report.CategorizedReportEntry.GROUP_PREFIX; +import static org.apache.maven.surefire.shared.utils.logging.MessageUtils.buffer; /** * Maintains per-thread test result state. Not thread safe. */ -public class TestSetStats -{ +public class TestSetStats { private static final String TESTS = "Tests "; private static final String RUN = "run: "; private static final String TESTS_RUN = "Tests run: "; @@ -66,78 +64,65 @@ public class TestSetStats private long lastStartAt; - public TestSetStats( boolean trimStackTrace, boolean plainFormat ) - { + public TestSetStats(boolean trimStackTrace, boolean plainFormat) { this.trimStackTrace = trimStackTrace; this.plainFormat = plainFormat; } - public int getElapsedSinceTestSetStart() - { - return testSetStartAt > 0 ? (int) ( System.currentTimeMillis() - testSetStartAt ) : 0; + public int getElapsedSinceTestSetStart() { + return testSetStartAt > 0 ? (int) (System.currentTimeMillis() - testSetStartAt) : 0; } - public int getElapsedSinceLastStart() - { - return lastStartAt > 0 ? (int) ( System.currentTimeMillis() - lastStartAt ) : 0; + public int getElapsedSinceLastStart() { + return lastStartAt > 0 ? (int) (System.currentTimeMillis() - lastStartAt) : 0; } - public void testSetStart() - { + public void testSetStart() { testSetStartAt = System.currentTimeMillis(); lastStartAt = testSetStartAt; } - public void testStart() - { + public void testStart() { testStartAt = System.currentTimeMillis(); lastStartAt = testStartAt; } - private void finishTest( WrappedReportEntry reportEntry ) - { - reportEntries.add( reportEntry ); + private void finishTest(WrappedReportEntry reportEntry) { + reportEntries.add(reportEntry); incrementCompletedCount(); // SUREFIRE-398 skipped tests call endTest without calling testStarting // if startTime = 0, set it to endTime, so the diff will be 0 - if ( testStartAt == 0 ) - { + if (testStartAt == 0) { testStartAt = System.currentTimeMillis(); } } - public void testSucceeded( WrappedReportEntry reportEntry ) - { - finishTest( reportEntry ); + public void testSucceeded(WrappedReportEntry reportEntry) { + finishTest(reportEntry); } - public void testError( WrappedReportEntry reportEntry ) - { + public void testError(WrappedReportEntry reportEntry) { errors += 1; - finishTest( reportEntry ); + finishTest(reportEntry); } - public void testFailure( WrappedReportEntry reportEntry ) - { + public void testFailure(WrappedReportEntry reportEntry) { failures += 1; - finishTest( reportEntry ); + finishTest(reportEntry); } - public void testSkipped( WrappedReportEntry reportEntry ) - { + public void testSkipped(WrappedReportEntry reportEntry) { skipped += 1; - finishTest( reportEntry ); + finishTest(reportEntry); } - public void reset() - { + public void reset() { completedCount = 0; errors = 0; failures = 0; skipped = 0; - for ( WrappedReportEntry entry : reportEntries ) - { + for (WrappedReportEntry entry : reportEntries) { entry.getStdout().free(); entry.getStdErr().free(); } @@ -145,45 +130,42 @@ public void reset() reportEntries.clear(); } - public int getCompletedCount() - { + public int getCompletedCount() { return completedCount; } - public int getErrors() - { + public int getErrors() { return errors; } - public int getFailures() - { + public int getFailures() { return failures; } - public int getSkipped() - { + public int getSkipped() { return skipped; } - private void incrementCompletedCount() - { + private void incrementCompletedCount() { completedCount += 1; } - public String getTestSetSummary( WrappedReportEntry reportEntry, boolean phrasedClassName ) - { - String summary = TESTS_RUN + completedCount - + COMMA - + FAILURES + failures - + COMMA - + ERRORS + errors - + COMMA - + SKIPPED + skipped - + COMMA - + reportEntry.getElapsedTimeVerbose(); - - if ( failures > 0 || errors > 0 ) - { + public String getTestSetSummary(WrappedReportEntry reportEntry, boolean phrasedClassName) { + String summary = TESTS_RUN + + completedCount + + COMMA + + FAILURES + + failures + + COMMA + + ERRORS + + errors + + COMMA + + SKIPPED + + skipped + + COMMA + + reportEntry.getElapsedTimeVerbose(); + + if (failures > 0 || errors > 0) { summary += FAILURE_MARKER; } @@ -193,97 +175,68 @@ public String getTestSetSummary( WrappedReportEntry reportEntry, boolean phrased return summary; } - public String getColoredTestSetSummary( WrappedReportEntry reportEntry, boolean phrasedClassName ) - { + public String getColoredTestSetSummary(WrappedReportEntry reportEntry, boolean phrasedClassName) { final boolean isSuccessful = failures == 0 && errors == 0 && skipped == 0; final boolean isFailure = failures > 0; final boolean isError = errors > 0; final boolean isFailureOrError = isFailure | isError; final boolean isSkipped = skipped > 0; - final MessageBuilder builder = buffer(); - if ( isSuccessful ) - { - if ( completedCount == 0 ) - { - builder.strong( TESTS_RUN ).strong( completedCount ); - } - else - { - builder.success( TESTS_RUN ).success( completedCount ); + final MessageBuilder builder = buffer(); + if (isSuccessful) { + if (completedCount == 0) { + builder.strong(TESTS_RUN).strong(completedCount); + } else { + builder.success(TESTS_RUN).success(completedCount); } - } - else - { - if ( isFailureOrError ) - { - builder.failure( TESTS ).strong( RUN ).strong( completedCount ); + } else { + if (isFailureOrError) { + builder.failure(TESTS).strong(RUN).strong(completedCount); + } else { + builder.warning(TESTS).strong(RUN).strong(completedCount); } - else - { - builder.warning( TESTS ).strong( RUN ).strong( completedCount ); - } - } - builder.a( COMMA ); - if ( isFailure ) - { - builder.failure( FAILURES ).failure( failures ); } - else - { - builder.a( FAILURES ).a( failures ); + builder.a(COMMA); + if (isFailure) { + builder.failure(FAILURES).failure(failures); + } else { + builder.a(FAILURES).a(failures); } - builder.a( COMMA ); - if ( isError ) - { - builder.failure( ERRORS ).failure( errors ); + builder.a(COMMA); + if (isError) { + builder.failure(ERRORS).failure(errors); + } else { + builder.a(ERRORS).a(errors); } - else - { - builder.a( ERRORS ).a( errors ); + builder.a(COMMA); + if (isSkipped) { + builder.warning(SKIPPED).warning(skipped); + } else { + builder.a(SKIPPED).a(skipped); } - builder.a( COMMA ); - if ( isSkipped ) - { - builder.warning( SKIPPED ).warning( skipped ); + builder.a(COMMA).a(reportEntry.getElapsedTimeVerbose()); + if (isFailureOrError) { + builder.failure(FAILURE_MARKER); } - else - { - builder.a( SKIPPED ).a( skipped ); - } - builder.a( COMMA ) - .a( reportEntry.getElapsedTimeVerbose() ); - if ( isFailureOrError ) - { - builder.failure( FAILURE_MARKER ); - } - builder.a( IN_MARKER ); - return concatenateWithTestGroup( builder, reportEntry, phrasedClassName ); + builder.a(IN_MARKER); + return concatenateWithTestGroup(builder, reportEntry, phrasedClassName); } - public List getTestResults() - { + public List getTestResults() { List result = new ArrayList<>(); - for ( WrappedReportEntry testResult : reportEntries ) - { - if ( testResult.isErrorOrFailure() ) - { - result.add( testResult.getOutput( trimStackTrace ) ); - } - else if ( plainFormat && testResult.isSkipped() ) - { - result.add( testResult.getSourceName() + " skipped" ); - } - else if ( plainFormat && testResult.isSucceeded() ) - { - result.add( testResult.getElapsedTimeSummary() ); + for (WrappedReportEntry testResult : reportEntries) { + if (testResult.isErrorOrFailure()) { + result.add(testResult.getOutput(trimStackTrace)); + } else if (plainFormat && testResult.isSkipped()) { + result.add(testResult.getSourceName() + " skipped"); + } else if (plainFormat && testResult.isSucceeded()) { + result.add(testResult.getElapsedTimeSummary()); } } // This should be Map with an enum and the enums will be displayed with colors on console. return result; } - public Collection getReportEntries() - { + public Collection getReportEntries() { return reportEntries; } @@ -295,23 +248,16 @@ public Collection getReportEntries() * @param report report whose test set is starting * @return the message */ - static String concatenateWithTestGroup( MessageBuilder builder, ReportEntry report, boolean phrasedClassName ) - { - if ( phrasedClassName && report.getReportNameWithGroup() != null ) - { - return builder.strong( report.getReportNameWithGroup() ) - .toString(); - } - else - { + static String concatenateWithTestGroup(MessageBuilder builder, ReportEntry report, boolean phrasedClassName) { + if (phrasedClassName && report.getReportNameWithGroup() != null) { + return builder.strong(report.getReportNameWithGroup()).toString(); + } else { String testClass = report.getNameWithGroup(); - int indexOfGroup = testClass.indexOf( GROUP_PREFIX ); - int delimiter = testClass.lastIndexOf( '.', indexOfGroup == -1 ? testClass.length() : indexOfGroup ); - String pkg = testClass.substring( 0, 1 + delimiter ); - String cls = testClass.substring( 1 + delimiter ); - return builder.a( pkg ) - .strong( cls ) - .toString(); + int indexOfGroup = testClass.indexOf(GROUP_PREFIX); + int delimiter = testClass.lastIndexOf('.', indexOfGroup == -1 ? testClass.length() : indexOfGroup); + String pkg = testClass.substring(0, 1 + delimiter); + String cls = testClass.substring(1 + delimiter); + return builder.a(pkg).strong(cls).toString(); } } } diff --git a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/report/TestcycleConsoleOutputReceiver.java b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/report/TestcycleConsoleOutputReceiver.java index dd4a10ffbd..6303f3d48f 100644 --- a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/report/TestcycleConsoleOutputReceiver.java +++ b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/report/TestcycleConsoleOutputReceiver.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire.report; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,21 +16,21 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.surefire.report; import org.apache.maven.surefire.api.report.TestOutputReceiver; import org.apache.maven.surefire.api.report.TestOutputReportEntry; -import org.apache.maven.surefire.extensions.ConsoleOutputReportEventListener; import org.apache.maven.surefire.api.report.TestSetReportEntry; +import org.apache.maven.surefire.extensions.ConsoleOutputReportEventListener; /** * @author Kristian Rosenvold */ public interface TestcycleConsoleOutputReceiver - extends TestOutputReceiver, ConsoleOutputReportEventListener -{ - void testSetStarting( TestSetReportEntry reportEntry ); + extends TestOutputReceiver, ConsoleOutputReportEventListener { + void testSetStarting(TestSetReportEntry reportEntry); - void testSetCompleted( TestSetReportEntry report ); + void testSetCompleted(TestSetReportEntry report); void close(); } diff --git a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/report/Utf8RecodingDeferredFileOutputStream.java b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/report/Utf8RecodingDeferredFileOutputStream.java index ebdd0af3b3..ddbb2fb52a 100644 --- a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/report/Utf8RecodingDeferredFileOutputStream.java +++ b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/report/Utf8RecodingDeferredFileOutputStream.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire.report; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.surefire.report; import java.io.IOException; import java.io.OutputStream; @@ -28,14 +27,14 @@ import java.nio.ByteBuffer; import java.nio.file.Path; +import org.apache.maven.surefire.api.util.SureFireFileManager; + import static java.nio.charset.StandardCharsets.UTF_8; import static java.nio.file.Files.notExists; import static java.nio.file.Files.size; import static java.util.Objects.requireNonNull; import static org.apache.maven.surefire.api.util.internal.StringUtils.NL; -import org.apache.maven.surefire.api.util.SureFireFileManager; - /** * A deferred file output stream decorator that encodes the string from the VM to UTF-8. *
@@ -47,9 +46,8 @@ * * @author Andreas Gudian */ -final class Utf8RecodingDeferredFileOutputStream -{ - private static final byte[] NL_BYTES = NL.getBytes( UTF_8 ); +final class Utf8RecodingDeferredFileOutputStream { + private static final byte[] NL_BYTES = NL.getBytes(UTF_8); public static final int CACHE_SIZE = 64 * 1024; private final String channel; @@ -60,169 +58,132 @@ final class Utf8RecodingDeferredFileOutputStream private ByteBuffer cache; private boolean isDirty; - Utf8RecodingDeferredFileOutputStream( String channel ) - { - this.channel = requireNonNull( channel ); + Utf8RecodingDeferredFileOutputStream(String channel) { + this.channel = requireNonNull(channel); } - public synchronized void write( String output, boolean newLine ) - throws IOException - { - if ( closed ) - { + public synchronized void write(String output, boolean newLine) throws IOException { + if (closed) { return; } - if ( storage == null ) - { + if (storage == null) { - file = SureFireFileManager.createTempFile( channel, "deferred" ).toPath(); - storage = new RandomAccessFile( file.toFile(), "rw" ); + file = SureFireFileManager.createTempFile(channel, "deferred").toPath(); + storage = new RandomAccessFile(file.toFile(), "rw"); } - if ( output == null ) - { + if (output == null) { output = "null"; } - if ( cache == null ) - { - cache = ByteBuffer.allocate( CACHE_SIZE ); + if (cache == null) { + cache = ByteBuffer.allocate(CACHE_SIZE); } isDirty = true; - byte[] decodedString = output.getBytes( UTF_8 ); + byte[] decodedString = output.getBytes(UTF_8); int newLineLength = newLine ? NL_BYTES.length : 0; - if ( cache.remaining() >= decodedString.length + newLineLength ) - { - cache.put( decodedString ); - if ( newLine ) - { - cache.put( NL_BYTES ); + if (cache.remaining() >= decodedString.length + newLineLength) { + cache.put(decodedString); + if (newLine) { + cache.put(NL_BYTES); } - } - else - { - ( (Buffer) cache ).flip(); + } else { + ((Buffer) cache).flip(); int minLength = cache.remaining() + decodedString.length + NL_BYTES.length; - byte[] buffer = getLargeCache( minLength ); + byte[] buffer = getLargeCache(minLength); int bufferLength = 0; - System.arraycopy( cache.array(), cache.arrayOffset() + ( (Buffer) cache ).position(), - buffer, bufferLength, cache.remaining() ); + System.arraycopy( + cache.array(), + cache.arrayOffset() + ((Buffer) cache).position(), + buffer, + bufferLength, + cache.remaining()); bufferLength += cache.remaining(); - ( (Buffer) cache ).clear(); + ((Buffer) cache).clear(); - System.arraycopy( decodedString, 0, buffer, bufferLength, decodedString.length ); + System.arraycopy(decodedString, 0, buffer, bufferLength, decodedString.length); bufferLength += decodedString.length; - if ( newLine ) - { - System.arraycopy( NL_BYTES, 0, buffer, bufferLength, NL_BYTES.length ); + if (newLine) { + System.arraycopy(NL_BYTES, 0, buffer, bufferLength, NL_BYTES.length); bufferLength += NL_BYTES.length; } - storage.write( buffer, 0, bufferLength ); + storage.write(buffer, 0, bufferLength); } } - public synchronized long getByteCount() - { - try - { + public synchronized long getByteCount() { + try { sync(); - if ( storage != null && !closed ) - { + if (storage != null && !closed) { storage.getFD().sync(); } - return file == null ? 0 : size( file ); - } - catch ( IOException e ) - { + return file == null ? 0 : size(file); + } catch (IOException e) { return 0; } } - @SuppressWarnings( "checkstyle:innerassignment" ) - public synchronized void writeTo( OutputStream out ) - throws IOException - { - if ( file != null && notExists( file ) ) - { + @SuppressWarnings("checkstyle:innerassignment") + public synchronized void writeTo(OutputStream out) throws IOException { + if (file != null && notExists(file)) { storage = null; } - if ( ( storage == null && file != null ) || ( storage != null && !storage.getChannel().isOpen() ) ) - { - storage = new RandomAccessFile( file.toFile(), "rw" ); + if ((storage == null && file != null) + || (storage != null && !storage.getChannel().isOpen())) { + storage = new RandomAccessFile(file.toFile(), "rw"); } - if ( storage != null ) - { + if (storage != null) { sync(); final long currentFilePosition = storage.getFilePointer(); - storage.seek( 0L ); - try - { + storage.seek(0L); + try { byte[] buffer = new byte[CACHE_SIZE]; - for ( int readCount; ( readCount = storage.read( buffer ) ) != -1; ) - { - out.write( buffer, 0, readCount ); + for (int readCount; (readCount = storage.read(buffer)) != -1; ) { + out.write(buffer, 0, readCount); } - } - finally - { - storage.seek( currentFilePosition ); + } finally { + storage.seek(currentFilePosition); } } } - public synchronized void commit() - { - if ( storage == null ) - { + public synchronized void commit() { + if (storage == null) { return; } - try - { + try { sync(); storage.close(); - } - catch ( IOException e ) - { - throw new UncheckedIOException( e ); - } - finally - { + } catch (IOException e) { + throw new UncheckedIOException(e); + } finally { storage = null; cache = null; largeCache = null; } } - public synchronized void free() - { - if ( !closed ) - { + public synchronized void free() { + if (!closed) { closed = true; - if ( file != null ) - { - try - { + if (file != null) { + try { commit(); - //todo delete( file ); uncomment L485 assertThat( file ).doesNotExist() in StatelessXmlReporterTest - } - catch ( /*todo uncomment IOException |*/ UncheckedIOException e ) - { + // todo delete( file ); uncomment L485 assertThat( file ).doesNotExist() in StatelessXmlReporterTest + } catch (/*todo uncomment IOException |*/ UncheckedIOException e) { /*todo uncomment file.toFile() - .deleteOnExit();*/ - } - finally - { + .deleteOnExit();*/ + } finally { // todo should be removed after uncommented delete( file ) - file.toFile() - .deleteOnExit(); + file.toFile().deleteOnExit(); } storage = null; @@ -232,36 +193,31 @@ public synchronized void free() } } - private void sync() throws IOException - { - if ( !isDirty ) - { + private void sync() throws IOException { + if (!isDirty) { return; } isDirty = false; - if ( storage != null && cache != null ) - { - ( (Buffer) cache ).flip(); + if (storage != null && cache != null) { + ((Buffer) cache).flip(); byte[] array = cache.array(); - int offset = cache.arrayOffset() + ( (Buffer) cache ).position(); + int offset = cache.arrayOffset() + ((Buffer) cache).position(); int length = cache.remaining(); - ( (Buffer) cache ).clear(); - storage.write( array, offset, length ); + ((Buffer) cache).clear(); + storage.write(array, offset, length); // the data that you wrote with the mode "rw" may still only be kept in memory and may be read back // storage.getFD().sync(); } } - @SuppressWarnings( "checkstyle:innerassignment" ) - private byte[] getLargeCache( int minLength ) - { + @SuppressWarnings("checkstyle:innerassignment") + private byte[] getLargeCache(int minLength) { byte[] buffer; - if ( largeCache == null || ( buffer = largeCache.get() ) == null || buffer.length < minLength ) - { + if (largeCache == null || (buffer = largeCache.get()) == null || buffer.length < minLength) { buffer = new byte[minLength]; - largeCache = new SoftReference<>( buffer ); + largeCache = new SoftReference<>(buffer); } return buffer; } diff --git a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/report/WrappedReportEntry.java b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/report/WrappedReportEntry.java index 75e845e59b..97b3734c21 100644 --- a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/report/WrappedReportEntry.java +++ b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/report/WrappedReportEntry.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire.report; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,16 +16,18 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.surefire.report; + +import javax.annotation.Nonnull; + +import java.util.Collections; +import java.util.Map; import org.apache.maven.surefire.api.report.ReportEntry; import org.apache.maven.surefire.api.report.RunMode; import org.apache.maven.surefire.api.report.StackTraceWriter; import org.apache.maven.surefire.api.report.TestSetReportEntry; -import javax.annotation.Nonnull; -import java.util.Collections; -import java.util.Map; - import static java.util.Collections.unmodifiableMap; import static org.apache.maven.plugin.surefire.report.ReporterUtils.formatElapsedTime; import static org.apache.maven.surefire.api.util.internal.StringUtils.NL; @@ -36,9 +36,7 @@ /** * @author Kristian Rosenvold */ -public class WrappedReportEntry - implements TestSetReportEntry -{ +public class WrappedReportEntry implements TestSetReportEntry { private final ReportEntry original; private final ReportEntryType reportEntryType; @@ -51,182 +49,159 @@ public class WrappedReportEntry private final Map systemProperties; - public WrappedReportEntry( ReportEntry original, ReportEntryType reportEntryType, Integer estimatedElapsed, - Utf8RecodingDeferredFileOutputStream stdout, - Utf8RecodingDeferredFileOutputStream stdErr, - Map systemProperties ) - { + public WrappedReportEntry( + ReportEntry original, + ReportEntryType reportEntryType, + Integer estimatedElapsed, + Utf8RecodingDeferredFileOutputStream stdout, + Utf8RecodingDeferredFileOutputStream stdErr, + Map systemProperties) { this.original = original; this.reportEntryType = reportEntryType; this.elapsed = estimatedElapsed; this.stdout = stdout; this.stdErr = stdErr; - this.systemProperties = unmodifiableMap( systemProperties ); + this.systemProperties = unmodifiableMap(systemProperties); } - public WrappedReportEntry( ReportEntry original, ReportEntryType reportEntryType, Integer estimatedElapsed, - Utf8RecodingDeferredFileOutputStream stdout, - Utf8RecodingDeferredFileOutputStream stdErr ) - { - this( original, reportEntryType, estimatedElapsed, stdout, stdErr, Collections.emptyMap() ); + public WrappedReportEntry( + ReportEntry original, + ReportEntryType reportEntryType, + Integer estimatedElapsed, + Utf8RecodingDeferredFileOutputStream stdout, + Utf8RecodingDeferredFileOutputStream stdErr) { + this(original, reportEntryType, estimatedElapsed, stdout, stdErr, Collections.emptyMap()); } @Override - public Integer getElapsed() - { + public Integer getElapsed() { return elapsed; } @Override - public int getElapsed( int fallback ) - { + public int getElapsed(int fallback) { return elapsed == null ? fallback : elapsed; } - public ReportEntryType getReportEntryType() - { + public ReportEntryType getReportEntryType() { return reportEntryType; } - public Utf8RecodingDeferredFileOutputStream getStdout() - { + public Utf8RecodingDeferredFileOutputStream getStdout() { return stdout; } - public Utf8RecodingDeferredFileOutputStream getStdErr() - { + public Utf8RecodingDeferredFileOutputStream getStdErr() { return stdErr; } @Override - public String getSourceName() - { + public String getSourceName() { return original.getSourceName(); } @Override - public String getSourceText() - { + public String getSourceText() { return original.getSourceText(); } @Override - public String getName() - { + public String getName() { return original.getName(); } @Override - public String getNameText() - { + public String getNameText() { return original.getNameText(); } - public String getClassMethodName() - { + public String getClassMethodName() { return original.getSourceName() + "." + original.getName(); } @Override - public String getGroup() - { + public String getGroup() { return original.getGroup(); } @Override - public StackTraceWriter getStackTraceWriter() - { + public StackTraceWriter getStackTraceWriter() { return original.getStackTraceWriter(); } @Override - public String getMessage() - { + public String getMessage() { return original.getMessage(); } - public String getStackTrace( boolean trimStackTrace ) - { + public String getStackTrace(boolean trimStackTrace) { StackTraceWriter w = original.getStackTraceWriter(); - return w == null ? null : ( trimStackTrace ? w.writeTrimmedTraceToString() : w.writeTraceToString() ); + return w == null ? null : (trimStackTrace ? w.writeTrimmedTraceToString() : w.writeTraceToString()); } - public String elapsedTimeAsString() - { - return formatElapsedTime( getElapsed() ); + public String elapsedTimeAsString() { + return formatElapsedTime(getElapsed()); } - String getReportSourceName() - { + String getReportSourceName() { String sourceName = getSourceName(); String sourceText = getSourceText(); - return isBlank( sourceText ) ? sourceName : sourceText; + return isBlank(sourceText) ? sourceName : sourceText; } - String getReportSourceName( String suffix ) - { - return isBlank( suffix ) ? getReportSourceName() : getReportSourceName() + "(" + suffix + ")"; + String getReportSourceName(String suffix) { + return isBlank(suffix) ? getReportSourceName() : getReportSourceName() + "(" + suffix + ")"; } - String getSourceName( String suffix ) - { - return isBlank( suffix ) ? getSourceName() : getSourceName() + "(" + suffix + ")"; + String getSourceName(String suffix) { + return isBlank(suffix) ? getSourceName() : getSourceName() + "(" + suffix + ")"; } - String getReportName() - { + String getReportName() { String name = getName(); String nameText = getNameText(); - return isBlank( nameText ) ? name : nameText; + return isBlank(nameText) ? name : nameText; } - public String getOutput( boolean trimStackTrace ) - { - String outputLine = getElapsedTimeSummary() + " <<< " + getReportEntryType().name() + "!"; - String trimmedStackTrace = getStackTrace( trimStackTrace ); + public String getOutput(boolean trimStackTrace) { + String outputLine = + getElapsedTimeSummary() + " <<< " + getReportEntryType().name() + "!"; + String trimmedStackTrace = getStackTrace(trimStackTrace); return trimmedStackTrace == null ? outputLine : outputLine + NL + trimmedStackTrace; } - public String getElapsedTimeVerbose() - { + public String getElapsedTimeVerbose() { return "Time elapsed: " + elapsedTimeAsString() + " s"; } - public String getElapsedTimeSummary() - { + public String getElapsedTimeSummary() { String description = getName() == null ? getSourceName() : getClassMethodName(); return description + " " + getElapsedTimeVerbose(); } - public boolean isErrorOrFailure() - { + public boolean isErrorOrFailure() { ReportEntryType thisType = getReportEntryType(); return ReportEntryType.FAILURE == thisType || ReportEntryType.ERROR == thisType; } - public boolean isSkipped() - { + public boolean isSkipped() { return ReportEntryType.SKIPPED == getReportEntryType(); } - public boolean isSucceeded() - { + public boolean isSucceeded() { return ReportEntryType.SUCCESS == getReportEntryType(); } @Override - public String getNameWithGroup() - { + public String getNameWithGroup() { return original.getNameWithGroup(); } @Override - public String getReportNameWithGroup() - { + public String getReportNameWithGroup() { String reportNameWithGroup = original.getReportNameWithGroup(); - if ( isBlank ( reportNameWithGroup ) ) - { + if (isBlank(reportNameWithGroup)) { return getNameWithGroup(); } @@ -235,20 +210,17 @@ public String getReportNameWithGroup() @Nonnull @Override - public RunMode getRunMode() - { + public RunMode getRunMode() { return original.getRunMode(); } @Override - public Long getTestRunId() - { + public Long getTestRunId() { return original.getTestRunId(); } @Override - public Map getSystemProperties() - { + public Map getSystemProperties() { return systemProperties; } } diff --git a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/runorder/StatisticsReporter.java b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/runorder/StatisticsReporter.java index 1b7006e9ff..2480622bf7 100644 --- a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/runorder/StatisticsReporter.java +++ b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/runorder/StatisticsReporter.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire.runorder; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,67 +16,57 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.surefire.runorder; import java.io.File; import java.io.IOException; -import org.apache.maven.surefire.api.runorder.RunEntryStatisticsMap; import org.apache.maven.surefire.api.report.ReportEntry; +import org.apache.maven.surefire.api.runorder.RunEntryStatisticsMap; import static org.apache.maven.surefire.api.runorder.RunEntryStatisticsMap.fromFile; /** * @author Kristian Rosenvold */ -public class StatisticsReporter -{ +public class StatisticsReporter { private final RunEntryStatisticsMap existing; private final RunEntryStatisticsMap newResults; private final File dataFile; - public StatisticsReporter( File dataFile ) - { - this( dataFile, fromFile( dataFile ), new RunEntryStatisticsMap() ); + public StatisticsReporter(File dataFile) { + this(dataFile, fromFile(dataFile), new RunEntryStatisticsMap()); } - protected StatisticsReporter( File dataFile, RunEntryStatisticsMap existing, RunEntryStatisticsMap newResults ) - { + protected StatisticsReporter(File dataFile, RunEntryStatisticsMap existing, RunEntryStatisticsMap newResults) { this.dataFile = dataFile; this.existing = existing; this.newResults = newResults; } - public synchronized void testSetCompleted() - { - try - { - newResults.serialize( dataFile ); - } - catch ( IOException e ) - { - throw new RuntimeException( e ); + public synchronized void testSetCompleted() { + try { + newResults.serialize(dataFile); + } catch (IOException e) { + throw new RuntimeException(e); } } - public void testSucceeded( ReportEntry report ) - { - newResults.add( existing.createNextGeneration( report ) ); + public void testSucceeded(ReportEntry report) { + newResults.add(existing.createNextGeneration(report)); } - public void testSkipped( ReportEntry report ) - { - newResults.add( existing.createNextGeneration( report ) ); + public void testSkipped(ReportEntry report) { + newResults.add(existing.createNextGeneration(report)); } - public void testError( ReportEntry report ) - { - newResults.add( existing.createNextGenerationFailure( report ) ); + public void testError(ReportEntry report) { + newResults.add(existing.createNextGenerationFailure(report)); } - public void testFailed( ReportEntry report ) - { - newResults.add( existing.createNextGenerationFailure( report ) ); + public void testFailed(ReportEntry report) { + newResults.add(existing.createNextGenerationFailure(report)); } } diff --git a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/util/DependencyScanner.java b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/util/DependencyScanner.java index 15aa0b2f60..156f280ed3 100644 --- a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/util/DependencyScanner.java +++ b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/util/DependencyScanner.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire.util; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,13 +16,7 @@ * specific language governing permissions and limitations * under the License. */ - -import org.apache.maven.artifact.Artifact; -import org.apache.maven.plugin.MojoExecutionException; -import org.apache.maven.shared.artifact.filter.PatternIncludesArtifactFilter; -import org.apache.maven.surefire.api.testset.TestFilter; -import org.apache.maven.surefire.api.testset.TestListResolver; -import org.apache.maven.surefire.api.util.DefaultScanResult; +package org.apache.maven.plugin.surefire.util; import java.io.File; import java.io.IOException; @@ -37,6 +29,13 @@ import java.util.jar.JarEntry; import java.util.jar.JarFile; +import org.apache.maven.artifact.Artifact; +import org.apache.maven.plugin.MojoExecutionException; +import org.apache.maven.shared.artifact.filter.PatternIncludesArtifactFilter; +import org.apache.maven.surefire.api.testset.TestFilter; +import org.apache.maven.surefire.api.testset.TestListResolver; +import org.apache.maven.surefire.api.util.DefaultScanResult; + import static org.apache.maven.plugin.surefire.util.ScannerUtil.convertJarFileResourceToJavaClassName; import static org.apache.maven.plugin.surefire.util.ScannerUtil.isJavaClassFile; @@ -45,51 +44,38 @@ * * @author Aslak Knutsen */ -public class DependencyScanner -{ +public class DependencyScanner { private final List dependenciesToScan; private final TestListResolver filter; - public DependencyScanner( List dependenciesToScan, TestListResolver filter ) - { + public DependencyScanner(List dependenciesToScan, TestListResolver filter) { this.dependenciesToScan = dependenciesToScan; this.filter = filter; } - public DefaultScanResult scan() - throws MojoExecutionException - { + public DefaultScanResult scan() throws MojoExecutionException { Set classes = new LinkedHashSet<>(); - for ( File artifact : dependenciesToScan ) - { - if ( artifact != null && artifact.isFile() && artifact.getName().endsWith( ".jar" ) ) - { - try - { - scanArtifact( artifact, filter, classes ); - } - catch ( IOException e ) - { - throw new MojoExecutionException( "Could not scan dependency " + artifact.toString(), e ); + for (File artifact : dependenciesToScan) { + if (artifact != null && artifact.isFile() && artifact.getName().endsWith(".jar")) { + try { + scanArtifact(artifact, filter, classes); + } catch (IOException e) { + throw new MojoExecutionException("Could not scan dependency " + artifact.toString(), e); } } } - return new DefaultScanResult( new ArrayList<>( classes ) ); + return new DefaultScanResult(new ArrayList<>(classes)); } - private static void scanArtifact( File artifact, TestFilter filter, Set classes ) - throws IOException - { - try ( JarFile jar = new JarFile( artifact ) ) - { - for ( Enumeration entries = jar.entries(); entries.hasMoreElements(); ) - { + private static void scanArtifact(File artifact, TestFilter filter, Set classes) + throws IOException { + try (JarFile jar = new JarFile(artifact)) { + for (Enumeration entries = jar.entries(); entries.hasMoreElements(); ) { JarEntry entry = entries.nextElement(); String path = entry.getName(); - if ( !entry.isDirectory() && isJavaClassFile( path ) && filter.shouldRun( path, null ) ) - { - classes.add( convertJarFileResourceToJavaClassName( path ) ); + if (!entry.isDirectory() && isJavaClassFile(path) && filter.shouldRun(path, null)) { + classes.add(convertJarFileResourceToJavaClassName(path)); } } } @@ -103,21 +89,17 @@ private static void scanArtifact( File artifact, TestFilter filt * @return list of items from artifacts that match any of the filters in groupArtifactIds, * empty if none match */ - public static List filter( List artifacts, List artifactPatterns ) - { - if ( artifactPatterns == null || artifacts == null || artifacts.isEmpty() ) - { + public static List filter(List artifacts, List artifactPatterns) { + if (artifactPatterns == null || artifacts == null || artifacts.isEmpty()) { return Collections.emptyList(); } - PatternIncludesArtifactFilter artifactFilter = new PatternIncludesArtifactFilter( artifactPatterns ); + PatternIncludesArtifactFilter artifactFilter = new PatternIncludesArtifactFilter(artifactPatterns); List matches = new ArrayList<>(); - for ( Artifact artifact : artifacts ) - { - if ( artifactFilter.include( artifact ) ) - { - matches.add( artifact ); + for (Artifact artifact : artifacts) { + if (artifactFilter.include(artifact)) { + matches.add(artifact); } } return matches; diff --git a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/util/DirectoryScanner.java b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/util/DirectoryScanner.java index d96675b9b2..addb4fd92b 100644 --- a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/util/DirectoryScanner.java +++ b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/util/DirectoryScanner.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire.util; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.surefire.util; import java.io.File; import java.util.ArrayList; @@ -32,23 +31,20 @@ * @author Karl M. Davis * @author Kristian Rosenvold */ -public class DirectoryScanner -{ +public class DirectoryScanner { private final File basedir; private final TestListResolver filter; - public DirectoryScanner( File basedir, TestListResolver filter ) - { + public DirectoryScanner(File basedir, TestListResolver filter) { this.basedir = basedir; this.filter = filter; } - public DefaultScanResult scan() - { - FileScanner scanner = new FileScanner( basedir, "class" ); + public DefaultScanResult scan() { + FileScanner scanner = new FileScanner(basedir, "class"); List result = new ArrayList<>(); - scanner.scanTo( result, filter ); - return new DefaultScanResult( result ); + scanner.scanTo(result, filter); + return new DefaultScanResult(result); } } diff --git a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/util/FileScanner.java b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/util/FileScanner.java index 69a6945a99..48d72f2303 100644 --- a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/util/FileScanner.java +++ b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/util/FileScanner.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire.util; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,111 +16,94 @@ * specific language governing permissions and limitations * under the License. */ - -import org.apache.maven.surefire.api.testset.TestFilter; +package org.apache.maven.plugin.surefire.util; import java.io.File; import java.util.Collection; +import org.apache.maven.surefire.api.testset.TestFilter; + import static org.apache.maven.surefire.shared.utils.StringUtils.isBlank; -final class FileScanner -{ +final class FileScanner { private final File basedir; private final String ext; - FileScanner( File basedir, String ext ) - { + FileScanner(File basedir, String ext) { this.basedir = basedir; ext = ext.trim(); - if ( isBlank( ext ) ) - { - throw new IllegalArgumentException( "No file extension" ); + if (isBlank(ext)) { + throw new IllegalArgumentException("No file extension"); } - this.ext = ext.startsWith( "." ) ? ext : "." + ext; + this.ext = ext.startsWith(".") ? ext : "." + ext; } - void scanTo( Collection scannedJavaClassNames, TestFilter filter ) - { - scan( scannedJavaClassNames, filter, basedir ); + void scanTo(Collection scannedJavaClassNames, TestFilter filter) { + scan(scannedJavaClassNames, filter, basedir); } - private void scan( Collection scannedJavaClassNames, - TestFilter filter, File basedir, String... subDirectories ) - { + private void scan( + Collection scannedJavaClassNames, + TestFilter filter, + File basedir, + String... subDirectories) { File[] filesAndDirs = basedir.listFiles(); - if ( filesAndDirs != null ) - { - final String pAckage = toJavaPackage( subDirectories ); - final String path = toPath( subDirectories ); + if (filesAndDirs != null) { + final String pAckage = toJavaPackage(subDirectories); + final String path = toPath(subDirectories); final String ext = this.ext; final boolean hasExtension = ext != null; final int extLength = hasExtension ? ext.length() : 0; - for ( File fileOrDir : filesAndDirs ) - { + for (File fileOrDir : filesAndDirs) { String name = fileOrDir.getName(); - if ( !name.isEmpty() ) - { - if ( fileOrDir.isFile() ) - { + if (!name.isEmpty()) { + if (fileOrDir.isFile()) { final int clsLength = name.length() - extLength; - if ( clsLength > 0 - && ( !hasExtension || name.regionMatches( true, clsLength, ext, 0, extLength ) ) ) - { - String simpleClassName = hasExtension ? name.substring( 0, clsLength ) : name; - if ( filter.shouldRun( toFile( path, simpleClassName ), null ) ) - { + if (clsLength > 0 + && (!hasExtension || name.regionMatches(true, clsLength, ext, 0, extLength))) { + String simpleClassName = hasExtension ? name.substring(0, clsLength) : name; + if (filter.shouldRun(toFile(path, simpleClassName), null)) { String fullyQualifiedClassName = - pAckage.isEmpty() ? simpleClassName : pAckage + '.' + simpleClassName; - scannedJavaClassNames.add( fullyQualifiedClassName ); + pAckage.isEmpty() ? simpleClassName : pAckage + '.' + simpleClassName; + scannedJavaClassNames.add(fullyQualifiedClassName); } } - } - else if ( fileOrDir.isDirectory() ) - { + } else if (fileOrDir.isDirectory()) { String[] paths = new String[subDirectories.length + 1]; - System.arraycopy( subDirectories, 0, paths, 0, subDirectories.length ); + System.arraycopy(subDirectories, 0, paths, 0, subDirectories.length); paths[subDirectories.length] = name; - scan( scannedJavaClassNames, filter, fileOrDir, paths ); + scan(scannedJavaClassNames, filter, fileOrDir, paths); } } } } } - private static String toJavaPackage( String... subDirectories ) - { + private static String toJavaPackage(String... subDirectories) { StringBuilder pkg = new StringBuilder(); - for ( int i = 0; i < subDirectories.length; i++ ) - { - if ( i > 0 && i < subDirectories.length ) - { - pkg.append( '.' ); + for (int i = 0; i < subDirectories.length; i++) { + if (i > 0 && i < subDirectories.length) { + pkg.append('.'); } - pkg.append( subDirectories[i] ); + pkg.append(subDirectories[i]); } return pkg.toString(); } - private static String toPath( String... subDirectories ) - { + private static String toPath(String... subDirectories) { StringBuilder pkg = new StringBuilder(); - for ( int i = 0; i < subDirectories.length; i++ ) - { - if ( i > 0 && i < subDirectories.length ) - { - pkg.append( '/' ); + for (int i = 0; i < subDirectories.length; i++) { + if (i > 0 && i < subDirectories.length) { + pkg.append('/'); } - pkg.append( subDirectories[i] ); + pkg.append(subDirectories[i]); } return pkg.toString(); } - private String toFile( String path, String fileNameWithoutExtension ) - { - String pathWithoutExtension = - path.isEmpty() ? fileNameWithoutExtension : path + '/' + fileNameWithoutExtension; + private String toFile(String path, String fileNameWithoutExtension) { + String pathWithoutExtension = path.isEmpty() ? fileNameWithoutExtension : path + '/' + fileNameWithoutExtension; return pathWithoutExtension + ext; } } diff --git a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/util/Relocator.java b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/util/Relocator.java index fe071691b4..9c1438a51e 100644 --- a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/util/Relocator.java +++ b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/util/Relocator.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire.util; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,7 +16,7 @@ * specific language governing permissions and limitations * under the License. */ - +package org.apache.maven.plugin.surefire.util; import javax.annotation.Nonnull; @@ -27,30 +25,23 @@ * * @author Kristian Rosenvold */ -public final class Relocator -{ +public final class Relocator { private static final String RELOCATION_BASE = "org.apache.maven."; private static final String PACKAGE_DELIMITER = "shadefire"; - private Relocator() - { - throw new IllegalStateException( "no instantiable constructor" ); + private Relocator() { + throw new IllegalStateException("no instantiable constructor"); } @Nonnull - public static String relocate( @Nonnull String className ) - { - if ( className.contains( PACKAGE_DELIMITER ) ) - { + public static String relocate(@Nonnull String className) { + if (className.contains(PACKAGE_DELIMITER)) { return className; - } - else - { - if ( !className.startsWith( RELOCATION_BASE ) ) - { - throw new IllegalArgumentException( "'" + className + "' should start with '" + RELOCATION_BASE + "'" ); + } else { + if (!className.startsWith(RELOCATION_BASE)) { + throw new IllegalArgumentException("'" + className + "' should start with '" + RELOCATION_BASE + "'"); } - String rest = className.substring( RELOCATION_BASE.length() ); + String rest = className.substring(RELOCATION_BASE.length()); final String s = RELOCATION_BASE + PACKAGE_DELIMITER + "."; return s + rest; } diff --git a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/util/ScannerUtil.java b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/util/ScannerUtil.java index afd9cf23e0..7541db72ce 100644 --- a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/util/ScannerUtil.java +++ b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/util/ScannerUtil.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire.util; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,37 +16,36 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.surefire.util; -import org.apache.maven.surefire.shared.lang3.StringUtils; import javax.annotation.Nonnull; -final class ScannerUtil -{ +import org.apache.maven.surefire.shared.lang3.StringUtils; + +final class ScannerUtil { - private ScannerUtil() - { - throw new IllegalStateException( "not instantiable constructor" ); + private ScannerUtil() { + throw new IllegalStateException("not instantiable constructor"); } @Deprecated - private static final String FS = System.getProperty( "file.separator" ); + private static final String FS = System.getProperty("file.separator"); @Deprecated - private static final boolean IS_NON_UNIX_FS = ( !FS.equals( "/" ) ); + private static final boolean IS_NON_UNIX_FS = (!FS.equals("/")); - @Nonnull public static String convertJarFileResourceToJavaClassName( @Nonnull String test ) - { - return StringUtils.removeEnd( test, ".class" ).replace( "/", "." ); + @Nonnull + public static String convertJarFileResourceToJavaClassName(@Nonnull String test) { + return StringUtils.removeEnd(test, ".class").replace("/", "."); } - public static boolean isJavaClassFile( String file ) - { - return file.endsWith( ".class" ); + public static boolean isJavaClassFile(String file) { + return file.endsWith(".class"); } @Deprecated - @Nonnull public static String convertSlashToSystemFileSeparator( @Nonnull String path ) - { - return ( IS_NON_UNIX_FS ? path.replace( "/", FS ) : path ); + @Nonnull + public static String convertSlashToSystemFileSeparator(@Nonnull String path) { + return (IS_NON_UNIX_FS ? path.replace("/", FS) : path); } } diff --git a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/util/SpecificFileFilter.java b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/util/SpecificFileFilter.java index 00ea5990a8..8246180dcc 100644 --- a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/util/SpecificFileFilter.java +++ b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/util/SpecificFileFilter.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire.util; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,12 +16,13 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.surefire.util; + +import javax.annotation.Nullable; import java.util.HashSet; import java.util.Set; -import javax.annotation.Nullable; - import org.apache.maven.surefire.shared.utils.io.SelectorUtils; import static org.apache.maven.plugin.surefire.util.ScannerUtil.convertSlashToSystemFileSeparator; @@ -33,34 +32,26 @@ * */ @Deprecated -public class SpecificFileFilter -{ +public class SpecificFileFilter { private Set names; - public SpecificFileFilter( @Nullable String[] classNames ) - { - if ( classNames != null && classNames.length > 0 ) - { + public SpecificFileFilter(@Nullable String[] classNames) { + if (classNames != null && classNames.length > 0) { this.names = new HashSet<>(); - for ( String name : classNames ) - { - names.add( convertSlashToSystemFileSeparator( name ) ); + for (String name : classNames) { + names.add(convertSlashToSystemFileSeparator(name)); } } } - public boolean accept( @Nullable String resourceName ) - { + public boolean accept(@Nullable String resourceName) { // If the tests enumeration is empty, allow anything. - if ( names != null && !names.isEmpty() ) - { - for ( String pattern : names ) - { + if (names != null && !names.isEmpty()) { + for (String pattern : names) { // This is the same utility used under the covers in the plexus DirectoryScanner, and // therefore in the surefire DefaultDirectoryScanner implementation. - if ( SelectorUtils.matchPath( pattern, resourceName, true ) ) - { + if (SelectorUtils.matchPath(pattern, resourceName, true)) { return true; } } @@ -68,5 +59,4 @@ public boolean accept( @Nullable String resourceName ) } return true; } - } diff --git a/maven-surefire-common/src/main/java/org/apache/maven/surefire/providerapi/ConfigurableProviderInfo.java b/maven-surefire-common/src/main/java/org/apache/maven/surefire/providerapi/ConfigurableProviderInfo.java index 00d4fb23cf..d7c00d3bef 100644 --- a/maven-surefire-common/src/main/java/org/apache/maven/surefire/providerapi/ConfigurableProviderInfo.java +++ b/maven-surefire-common/src/main/java/org/apache/maven/surefire/providerapi/ConfigurableProviderInfo.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.providerapi; /* @@ -22,8 +40,6 @@ /** * @author Kristian Rosenvold */ -public interface ConfigurableProviderInfo - extends ProviderInfo -{ - ProviderInfo instantiate( String providerName ); +public interface ConfigurableProviderInfo extends ProviderInfo { + ProviderInfo instantiate(String providerName); } diff --git a/maven-surefire-common/src/main/java/org/apache/maven/surefire/providerapi/ProviderDetector.java b/maven-surefire-common/src/main/java/org/apache/maven/surefire/providerapi/ProviderDetector.java index cc9b91dd07..c40f72a3c8 100644 --- a/maven-surefire-common/src/main/java/org/apache/maven/surefire/providerapi/ProviderDetector.java +++ b/maven-surefire-common/src/main/java/org/apache/maven/surefire/providerapi/ProviderDetector.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.providerapi; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.providerapi; import javax.annotation.Nonnull; @@ -40,9 +39,8 @@ /** * @author Kristian Rosenvold */ -@Component( role = ProviderDetector.class ) -public final class ProviderDetector -{ +@Component(role = ProviderDetector.class) +public final class ProviderDetector { @Requirement private Logger logger; @@ -50,59 +48,46 @@ public final class ProviderDetector private ServiceLoader serviceLoader; @Nonnull - public List resolve( ConfigurableProviderInfo dynamicProvider, ProviderInfo... wellKnownProviders ) - { + public List resolve(ConfigurableProviderInfo dynamicProvider, ProviderInfo... wellKnownProviders) { Set manuallyConfiguredProviders = getManuallyConfiguredProviders(); List providersToRun = manuallyConfiguredProviders.stream() - .map( name -> - findByName( name, wellKnownProviders ) - .orElseGet( () -> dynamicProvider.instantiate( name ) ) ) - .collect( toList() ); + .map(name -> findByName(name, wellKnownProviders).orElseGet(() -> dynamicProvider.instantiate(name))) + .collect(toList()); - providersToRun.forEach( p -> logger.info( "Using configured provider " + p.getProviderName() ) ); + providersToRun.forEach(p -> logger.info("Using configured provider " + p.getProviderName())); - if ( providersToRun.isEmpty() ) - { - return autoDetectOneWellKnownProvider( wellKnownProviders ) - .map( Collections::singletonList ) - .orElse( emptyList() ); - } - else - { - return Collections.unmodifiableList( providersToRun ); + if (providersToRun.isEmpty()) { + return autoDetectOneWellKnownProvider(wellKnownProviders) + .map(Collections::singletonList) + .orElse(emptyList()); + } else { + return Collections.unmodifiableList(providersToRun); } } - private Optional autoDetectOneWellKnownProvider( ProviderInfo... wellKnownProviders ) - { - Optional providerInfo = stream( wellKnownProviders ) - .filter( ProviderInfo::isApplicable ) - .findFirst(); + private Optional autoDetectOneWellKnownProvider(ProviderInfo... wellKnownProviders) { + Optional providerInfo = + stream(wellKnownProviders).filter(ProviderInfo::isApplicable).findFirst(); - providerInfo.ifPresent( p -> logger.info( "Using auto detected provider " + p.getProviderName() ) ); + providerInfo.ifPresent(p -> logger.info("Using auto detected provider " + p.getProviderName())); return providerInfo; } - private Set getManuallyConfiguredProviders() - { - try - { + private Set getManuallyConfiguredProviders() { + try { ClassLoader cl = currentThread().getContextClassLoader(); - return serviceLoader.lookup( SurefireProvider.class, cl ); - } - catch ( IOException e ) - { - throw new RuntimeException( e ); + return serviceLoader.lookup(SurefireProvider.class, cl); + } catch (IOException e) { + throw new RuntimeException(e); } } @Nonnull - private Optional findByName( String providerClassName, ProviderInfo... wellKnownProviders ) - { - return stream( wellKnownProviders ) - .filter( p -> p.getProviderName().equals( providerClassName ) ) - .findFirst(); + private Optional findByName(String providerClassName, ProviderInfo... wellKnownProviders) { + return stream(wellKnownProviders) + .filter(p -> p.getProviderName().equals(providerClassName)) + .findFirst(); } } diff --git a/maven-surefire-common/src/main/java/org/apache/maven/surefire/providerapi/ProviderInfo.java b/maven-surefire-common/src/main/java/org/apache/maven/surefire/providerapi/ProviderInfo.java index dfa1d63808..52c68fdefd 100644 --- a/maven-surefire-common/src/main/java/org/apache/maven/surefire/providerapi/ProviderInfo.java +++ b/maven-surefire-common/src/main/java/org/apache/maven/surefire/providerapi/ProviderInfo.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.providerapi; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,10 +16,12 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.providerapi; + +import javax.annotation.Nonnull; import java.util.List; import java.util.Set; -import javax.annotation.Nonnull; import org.apache.maven.artifact.Artifact; import org.apache.maven.plugin.MojoExecutionException; @@ -29,8 +29,7 @@ /** * @author Kristian Rosenvold */ -public interface ProviderInfo -{ +public interface ProviderInfo { @Nonnull String getProviderName(); @@ -42,5 +41,5 @@ public interface ProviderInfo void addProviderProperties() throws MojoExecutionException; @Nonnull - List getJpmsArguments( @Nonnull ProviderRequirements forkRequirements ); + List getJpmsArguments(@Nonnull ProviderRequirements forkRequirements); } diff --git a/maven-surefire-common/src/main/java/org/apache/maven/surefire/providerapi/ProviderRequirements.java b/maven-surefire-common/src/main/java/org/apache/maven/surefire/providerapi/ProviderRequirements.java index e1d722915f..88399915f5 100644 --- a/maven-surefire-common/src/main/java/org/apache/maven/surefire/providerapi/ProviderRequirements.java +++ b/maven-surefire-common/src/main/java/org/apache/maven/surefire/providerapi/ProviderRequirements.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.providerapi; /* @@ -24,31 +42,26 @@ * * @see ProviderInfo#getJpmsArguments(ProviderRequirements) */ -public final class ProviderRequirements -{ +public final class ProviderRequirements { private final boolean modularPath; private final boolean mainModuleDescriptor; private final boolean testModuleDescriptor; - public ProviderRequirements( boolean modularPath, boolean mainModuleDescriptor, boolean testModuleDescriptor ) - { + public ProviderRequirements(boolean modularPath, boolean mainModuleDescriptor, boolean testModuleDescriptor) { this.modularPath = modularPath; this.mainModuleDescriptor = mainModuleDescriptor; this.testModuleDescriptor = testModuleDescriptor; } - public boolean isModularPath() - { + public boolean isModularPath() { return modularPath; } - public boolean hasMainModuleDescriptor() - { + public boolean hasMainModuleDescriptor() { return mainModuleDescriptor; } - public boolean hasTestModuleDescriptor() - { + public boolean hasTestModuleDescriptor() { return testModuleDescriptor; } } diff --git a/maven-surefire-common/src/main/java/org/apache/maven/surefire/providerapi/ServiceLoader.java b/maven-surefire-common/src/main/java/org/apache/maven/surefire/providerapi/ServiceLoader.java index e904eef095..41c9109f05 100644 --- a/maven-surefire-common/src/main/java/org/apache/maven/surefire/providerapi/ServiceLoader.java +++ b/maven-surefire-common/src/main/java/org/apache/maven/surefire/providerapi/ServiceLoader.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.providerapi; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.providerapi; import javax.annotation.Nonnull; @@ -45,42 +44,33 @@ * * @since 2.20 */ -@Component( role = ServiceLoader.class ) -public class ServiceLoader -{ +@Component(role = ServiceLoader.class) +public class ServiceLoader { @Nonnull - @SuppressWarnings( "unchecked" ) - public Set load( Class clazz, ClassLoader classLoader ) - { - try - { + @SuppressWarnings("unchecked") + public Set load(Class clazz, ClassLoader classLoader) { + try { Set implementations = new HashSet<>(); - for ( String fullyQualifiedClassName : lookup( clazz, classLoader ) ) - { - Class implClass = classLoader.loadClass( fullyQualifiedClassName ); - implementations.add( (T) getConstructor( implClass ).newInstance() ); + for (String fullyQualifiedClassName : lookup(clazz, classLoader)) { + Class implClass = classLoader.loadClass(fullyQualifiedClassName); + implementations.add((T) getConstructor(implClass).newInstance()); } return implementations; - } - catch ( IOException | ReflectiveOperationException e ) - { - throw new IllegalStateException( e.getLocalizedMessage(), e ); + } catch (IOException | ReflectiveOperationException e) { + throw new IllegalStateException(e.getLocalizedMessage(), e); } } @Nonnull - public Set lookup( Class clazz, ClassLoader classLoader ) - throws IOException - { + public Set lookup(Class clazz, ClassLoader classLoader) throws IOException { final String resourceName = "META-INF/services/" + clazz.getName(); - if ( classLoader == null ) - { + if (classLoader == null) { return emptySet(); } - final Enumeration urls = classLoader.getResources( resourceName ); - return lookupSpiImplementations( urls ); + final Enumeration urls = classLoader.getResources(resourceName); + return lookupSpiImplementations(urls); } /** @@ -92,51 +82,39 @@ public Set lookup( Class clazz, ClassLoader classLoader ) * @throws IOException When reading the streams fails */ @Nonnull - @SuppressWarnings( "checkstyle:innerassignment" ) - private static Set lookupSpiImplementations( final Enumeration urlEnumeration ) - throws IOException - { + @SuppressWarnings("checkstyle:innerassignment") + private static Set lookupSpiImplementations(final Enumeration urlEnumeration) throws IOException { final Set names = new HashSet<>(); nextUrl: - while ( urlEnumeration.hasMoreElements() ) - { + while (urlEnumeration.hasMoreElements()) { final URL url = urlEnumeration.nextElement(); - try ( BufferedReader reader = getReader( url ) ) - { - for ( String line; ( line = reader.readLine() ) != null; ) - { - int ci = line.indexOf( '#' ); - if ( ci >= 0 ) - { - line = line.substring( 0, ci ); + try (BufferedReader reader = getReader(url)) { + for (String line; (line = reader.readLine()) != null; ) { + int ci = line.indexOf('#'); + if (ci >= 0) { + line = line.substring(0, ci); } line = line.trim(); int n = line.length(); - if ( n == 0 ) - { + if (n == 0) { continue; // next line } - if ( line.indexOf( ' ' ) >= 0 || line.indexOf( '\t' ) >= 0 ) - { + if (line.indexOf(' ') >= 0 || line.indexOf('\t') >= 0) { continue nextUrl; // next url } - char cp = line.charAt( 0 ); // should use codePointAt but this was JDK1.3 - if ( !isJavaIdentifierStart( cp ) ) - { + char cp = line.charAt(0); // should use codePointAt but this was JDK1.3 + if (!isJavaIdentifierStart(cp)) { continue nextUrl; // next url } - for ( int i = 1; i < n; i++ ) - { - cp = line.charAt( i ); // should use codePointAt but this was JDK1.3 - if ( !isJavaIdentifierPart( cp ) && cp != '.' ) - { + for (int i = 1; i < n; i++) { + cp = line.charAt(i); // should use codePointAt but this was JDK1.3 + if (!isJavaIdentifierPart(cp) && cp != '.') { continue nextUrl; // next url } } - if ( !names.contains( line ) ) - { - names.add( line ); + if (!names.contains(line)) { + names.add(line); } } } @@ -146,11 +124,9 @@ private static Set lookupSpiImplementations( final Enumeration urlE } @Nonnull - private static BufferedReader getReader( @Nonnull URL url ) - throws IOException - { + private static BufferedReader getReader(@Nonnull URL url) throws IOException { final InputStream inputStream = url.openStream(); - final InputStreamReader inputStreamReader = new InputStreamReader( inputStream ); - return new BufferedReader( inputStreamReader ); + final InputStreamReader inputStreamReader = new InputStreamReader(inputStream); + return new BufferedReader(inputStreamReader); } } diff --git a/maven-surefire-common/src/main/java/org/apache/maven/surefire/report/RunStatistics.java b/maven-surefire-common/src/main/java/org/apache/maven/surefire/report/RunStatistics.java index 8ae941a97c..00abbf2482 100644 --- a/maven-surefire-common/src/main/java/org/apache/maven/surefire/report/RunStatistics.java +++ b/maven-surefire-common/src/main/java/org/apache/maven/surefire/report/RunStatistics.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.report; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,14 +16,14 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.report; import org.apache.maven.surefire.api.suite.RunResult; /** * @author Kristian Rosenvold */ -public final class RunStatistics -{ +public final class RunStatistics { private int completedCount; private int errors; @@ -36,33 +34,27 @@ public final class RunStatistics private int flakes; - public synchronized int getCompletedCount() - { + public synchronized int getCompletedCount() { return completedCount; } - public synchronized int getSkipped() - { + public synchronized int getSkipped() { return skipped; } - public synchronized int getFailures() - { + public synchronized int getFailures() { return failures; } - public synchronized int getErrors() - { + public synchronized int getErrors() { return errors; } - public synchronized int getFlakes() - { + public synchronized int getFlakes() { return flakes; } - public synchronized void set( int completedCount, int errors, int failures, int skipped, int flakes ) - { + public synchronized void set(int completedCount, int errors, int failures, int skipped, int flakes) { this.completedCount = completedCount; this.errors = errors; this.failures = failures; @@ -70,18 +62,14 @@ public synchronized void set( int completedCount, int errors, int failures, int this.flakes = flakes; } - public synchronized RunResult getRunResult() - { - return new RunResult( completedCount, errors, failures, skipped, flakes ); + public synchronized RunResult getRunResult() { + return new RunResult(completedCount, errors, failures, skipped, flakes); } - public synchronized String getSummary() - { - String summary = - "Tests run: " + completedCount + ", Failures: " + failures + ", Errors: " + errors + ", Skipped: " - + skipped; - if ( flakes > 0 ) - { + public synchronized String getSummary() { + String summary = "Tests run: " + completedCount + ", Failures: " + failures + ", Errors: " + errors + + ", Skipped: " + skipped; + if (flakes > 0) { summary += ", Flakes: " + flakes; } return summary; diff --git a/maven-surefire-common/src/main/java/org/apache/maven/surefire/stream/CommandEncoder.java b/maven-surefire-common/src/main/java/org/apache/maven/surefire/stream/CommandEncoder.java index 5da115165b..ef5b2a4b72 100644 --- a/maven-surefire-common/src/main/java/org/apache/maven/surefire/stream/CommandEncoder.java +++ b/maven-surefire-common/src/main/java/org/apache/maven/surefire/stream/CommandEncoder.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.stream; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,17 +16,19 @@ * specific language governing permissions and limitations * under the License. */ - -import org.apache.maven.surefire.api.booter.MasterProcessCommand; -import org.apache.maven.surefire.api.stream.AbstractStreamEncoder; +package org.apache.maven.surefire.stream; import javax.annotation.Nonnull; + import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.WritableByteChannel; import java.nio.charset.Charset; import java.nio.charset.CharsetEncoder; +import org.apache.maven.surefire.api.booter.MasterProcessCommand; +import org.apache.maven.surefire.api.stream.AbstractStreamEncoder; + import static org.apache.maven.surefire.api.booter.Constants.DEFAULT_STREAM_ENCODING; import static org.apache.maven.surefire.api.booter.Constants.DEFAULT_STREAM_ENCODING_BYTES; import static org.apache.maven.surefire.api.booter.Constants.MAGIC_NUMBER_FOR_COMMANDS_BYTES; @@ -42,104 +42,90 @@ /** * */ -public class CommandEncoder extends AbstractStreamEncoder implements AutoCloseable -{ +public class CommandEncoder extends AbstractStreamEncoder implements AutoCloseable { private final WritableByteChannel out; - public CommandEncoder( WritableByteChannel out ) - { - super( out ); + public CommandEncoder(WritableByteChannel out) { + super(out); this.out = out; } - public void sendRunClass( String testClassName ) throws IOException - { + public void sendRunClass(String testClassName) throws IOException { CharsetEncoder encoder = newCharsetEncoder(); - int bufferMaxLength = estimateBufferLength( RUN_CLASS.getOpcodeLength(), null, encoder, 0, 0, testClassName ); - ByteBuffer result = ByteBuffer.allocate( bufferMaxLength ); - encode( encoder, result, RUN_CLASS, testClassName ); - write( result, true ); + int bufferMaxLength = estimateBufferLength(RUN_CLASS.getOpcodeLength(), null, encoder, 0, 0, testClassName); + ByteBuffer result = ByteBuffer.allocate(bufferMaxLength); + encode(encoder, result, RUN_CLASS, testClassName); + write(result, true); } - public void sendTestSetFinished() throws IOException - { - int bufferMaxLength = estimateBufferLength( TEST_SET_FINISHED.getOpcodeLength(), null, null, 0, 0 ); - ByteBuffer result = ByteBuffer.allocate( bufferMaxLength ); - encodeHeader( result, TEST_SET_FINISHED ); - write( result, true ); + public void sendTestSetFinished() throws IOException { + int bufferMaxLength = estimateBufferLength(TEST_SET_FINISHED.getOpcodeLength(), null, null, 0, 0); + ByteBuffer result = ByteBuffer.allocate(bufferMaxLength); + encodeHeader(result, TEST_SET_FINISHED); + write(result, true); } - public void sendSkipSinceNextTest() throws IOException - { - int bufferMaxLength = estimateBufferLength( SKIP_SINCE_NEXT_TEST.getOpcodeLength(), null, null, 0, 0 ); - ByteBuffer result = ByteBuffer.allocate( bufferMaxLength ); - encodeHeader( result, SKIP_SINCE_NEXT_TEST ); - write( result, true ); + public void sendSkipSinceNextTest() throws IOException { + int bufferMaxLength = estimateBufferLength(SKIP_SINCE_NEXT_TEST.getOpcodeLength(), null, null, 0, 0); + ByteBuffer result = ByteBuffer.allocate(bufferMaxLength); + encodeHeader(result, SKIP_SINCE_NEXT_TEST); + write(result, true); } - public void sendShutdown( String shutdownData ) throws IOException - { + public void sendShutdown(String shutdownData) throws IOException { CharsetEncoder encoder = newCharsetEncoder(); - int bufferMaxLength = estimateBufferLength( SHUTDOWN.getOpcodeLength(), null, encoder, 0, 0, shutdownData ); - ByteBuffer result = ByteBuffer.allocate( bufferMaxLength ); - encode( encoder, result, SHUTDOWN, shutdownData ); - write( result, true ); + int bufferMaxLength = estimateBufferLength(SHUTDOWN.getOpcodeLength(), null, encoder, 0, 0, shutdownData); + ByteBuffer result = ByteBuffer.allocate(bufferMaxLength); + encode(encoder, result, SHUTDOWN, shutdownData); + write(result, true); } - public void sendNoop() throws IOException - { - int bufferMaxLength = estimateBufferLength( NOOP.getOpcodeLength(), null, null, 0, 0 ); - ByteBuffer result = ByteBuffer.allocate( bufferMaxLength ); - encodeHeader( result, NOOP ); - write( result, true ); + public void sendNoop() throws IOException { + int bufferMaxLength = estimateBufferLength(NOOP.getOpcodeLength(), null, null, 0, 0); + ByteBuffer result = ByteBuffer.allocate(bufferMaxLength); + encodeHeader(result, NOOP); + write(result, true); } - public void sendByeAck() throws IOException - { - int bufferMaxLength = estimateBufferLength( BYE_ACK.getOpcodeLength(), null, null, 0, 0 ); - ByteBuffer result = ByteBuffer.allocate( bufferMaxLength ); - encodeHeader( result, BYE_ACK ); - write( result, true ); + public void sendByeAck() throws IOException { + int bufferMaxLength = estimateBufferLength(BYE_ACK.getOpcodeLength(), null, null, 0, 0); + ByteBuffer result = ByteBuffer.allocate(bufferMaxLength); + encodeHeader(result, BYE_ACK); + write(result, true); } @Nonnull @Override - protected final byte[] getEncodedMagicNumber() - { + protected final byte[] getEncodedMagicNumber() { return MAGIC_NUMBER_FOR_COMMANDS_BYTES; } @Nonnull @Override - protected final byte[] enumToByteArray( MasterProcessCommand masterProcessCommand ) - { + protected final byte[] enumToByteArray(MasterProcessCommand masterProcessCommand) { return masterProcessCommand.getOpcodeBinary(); } @Nonnull @Override - protected final byte[] getEncodedCharsetName() - { + protected final byte[] getEncodedCharsetName() { return DEFAULT_STREAM_ENCODING_BYTES; } @Nonnull @Override - protected final Charset getCharset() - { + protected final Charset getCharset() { return DEFAULT_STREAM_ENCODING; } @Nonnull @Override - protected final CharsetEncoder newCharsetEncoder() - { + protected final CharsetEncoder newCharsetEncoder() { return getCharset().newEncoder(); } @Override - public void close() throws IOException - { + public void close() throws IOException { out.close(); } } diff --git a/maven-surefire-common/src/main/java/org/apache/maven/surefire/stream/EventDecoder.java b/maven-surefire-common/src/main/java/org/apache/maven/surefire/stream/EventDecoder.java index ea11889846..0bfc1e26b7 100644 --- a/maven-surefire-common/src/main/java/org/apache/maven/surefire/stream/EventDecoder.java +++ b/maven-surefire-common/src/main/java/org/apache/maven/surefire/stream/EventDecoder.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.stream; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,21 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.stream; + +import javax.annotation.Nonnull; + +import java.io.BufferedOutputStream; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.nio.channels.ReadableByteChannel; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.FutureTask; import org.apache.maven.plugin.surefire.booterclient.output.DeserializedStacktraceWriter; import org.apache.maven.surefire.api.booter.ForkedProcessEventType; @@ -50,19 +63,6 @@ import org.apache.maven.surefire.api.stream.AbstractStreamDecoder; import org.apache.maven.surefire.api.stream.SegmentType; -import javax.annotation.Nonnull; -import java.io.BufferedOutputStream; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.nio.channels.ReadableByteChannel; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.FutureTask; - import static java.util.Collections.emptyMap; import static org.apache.maven.surefire.api.booter.Constants.MAGIC_NUMBER_FOR_EVENTS_BYTES; import static org.apache.maven.surefire.api.report.CategorizedReportEntry.reportEntry; @@ -77,47 +77,25 @@ /** * */ -public class EventDecoder extends AbstractStreamDecoder -{ +public class EventDecoder extends AbstractStreamDecoder { private static final int DEBUG_SINK_BUFFER_SIZE = 64 * 1024; // due to have fast and thread-safe Map private static final Map EVENT_TYPES = segmentsToEvents(); private static final Map RUN_MODES = segmentsToRunModes(); - private static final SegmentType[] EVENT_WITHOUT_DATA = new SegmentType[] { - END_OF_FRAME - }; + private static final SegmentType[] EVENT_WITHOUT_DATA = new SegmentType[] {END_OF_FRAME}; - private static final SegmentType[] EVENT_WITH_ERROR_TRACE = new SegmentType[] { - STRING_ENCODING, - DATA_STRING, - DATA_STRING, - DATA_STRING, - END_OF_FRAME - }; + private static final SegmentType[] EVENT_WITH_ERROR_TRACE = + new SegmentType[] {STRING_ENCODING, DATA_STRING, DATA_STRING, DATA_STRING, END_OF_FRAME}; - private static final SegmentType[] EVENT_WITH_ONE_STRING = new SegmentType[] { - STRING_ENCODING, - DATA_STRING, - END_OF_FRAME - }; + private static final SegmentType[] EVENT_WITH_ONE_STRING = + new SegmentType[] {STRING_ENCODING, DATA_STRING, END_OF_FRAME}; - private static final SegmentType[] EVENT_WITH_RUNMODE_TID_AND_ONE_STRING = new SegmentType[] { - RUN_MODE, - TEST_RUN_ID, - STRING_ENCODING, - DATA_STRING, - END_OF_FRAME - }; + private static final SegmentType[] EVENT_WITH_RUNMODE_TID_AND_ONE_STRING = + new SegmentType[] {RUN_MODE, TEST_RUN_ID, STRING_ENCODING, DATA_STRING, END_OF_FRAME}; - private static final SegmentType[] EVENT_WITH_RUNMODE_TID_AND_TWO_STRINGS = new SegmentType[] { - RUN_MODE, - TEST_RUN_ID, - STRING_ENCODING, - DATA_STRING, - DATA_STRING, - END_OF_FRAME - }; + private static final SegmentType[] EVENT_WITH_RUNMODE_TID_AND_TWO_STRINGS = + new SegmentType[] {RUN_MODE, TEST_RUN_ID, STRING_ENCODING, DATA_STRING, DATA_STRING, END_OF_FRAME}; private static final SegmentType[] EVENT_TEST_CONTROL = new SegmentType[] { RUN_MODE, @@ -140,101 +118,81 @@ public class EventDecoder extends AbstractStreamDecoder args ) - { - RunMode runMode = (RunMode) args.get( 0 ); - long testRunId = (long) args.get( 1 ); + private static TestSetReportEntry toReportEntry(List args) { + RunMode runMode = (RunMode) args.get(0); + long testRunId = (long) args.get(1); // ReportEntry: - String source = (String) args.get( 2 ); - String sourceText = (String) args.get( 3 ); - String name = (String) args.get( 4 ); - String nameText = (String) args.get( 5 ); - String group = (String) args.get( 6 ); - String message = (String) args.get( 7 ); - Integer timeElapsed = (Integer) args.get( 8 ); + String source = (String) args.get(2); + String sourceText = (String) args.get(3); + String name = (String) args.get(4); + String nameText = (String) args.get(5); + String group = (String) args.get(6); + String message = (String) args.get(7); + Integer timeElapsed = (Integer) args.get(8); // StackTraceWriter: - String traceMessage = (String) args.get( 9 ); - String smartTrimmedStackTrace = (String) args.get( 10 ); - String stackTrace = (String) args.get( 11 ); - return newReportEntry( runMode, testRunId, source, sourceText, name, nameText, group, message, timeElapsed, - traceMessage, smartTrimmedStackTrace, stackTrace ); + String traceMessage = (String) args.get(9); + String smartTrimmedStackTrace = (String) args.get(10); + String stackTrace = (String) args.get(11); + return newReportEntry( + runMode, + testRunId, + source, + sourceText, + name, + nameText, + group, + message, + timeElapsed, + traceMessage, + smartTrimmedStackTrace, + stackTrace); } - private static StackTraceWriter toStackTraceWriter( List args ) - { - String traceMessage = (String) args.get( 0 ); - String smartTrimmedStackTrace = (String) args.get( 1 ); - String stackTrace = (String) args.get( 2 ); - return toTrace( traceMessage, smartTrimmedStackTrace, stackTrace ); + private static StackTraceWriter toStackTraceWriter(List args) { + String traceMessage = (String) args.get(0); + String smartTrimmedStackTrace = (String) args.get(1); + String stackTrace = (String) args.get(2); + return toTrace(traceMessage, smartTrimmedStackTrace, stackTrace); } - private static StackTraceWriter toTrace( String traceMessage, String smartTrimmedStackTrace, String stackTrace ) - { + private static StackTraceWriter toTrace(String traceMessage, String smartTrimmedStackTrace, String stackTrace) { boolean exists = traceMessage != null || stackTrace != null || smartTrimmedStackTrace != null; - return exists ? new DeserializedStacktraceWriter( traceMessage, smartTrimmedStackTrace, stackTrace ) : null; + return exists ? new DeserializedStacktraceWriter(traceMessage, smartTrimmedStackTrace, stackTrace) : null; } static TestSetReportEntry newReportEntry( // ReportEntry: - RunMode runMode, long testRunId, String source, String sourceText, - String name, String nameText, String group, String message, - Integer timeElapsed, - // StackTraceWriter: - String traceMessage, - String smartTrimmedStackTrace, String stackTrace ) - throws NumberFormatException - { - StackTraceWriter stackTraceWriter = toTrace( traceMessage, smartTrimmedStackTrace, stackTrace ); - return reportEntry( runMode, testRunId, source, sourceText, name, nameText, group, stackTraceWriter, - timeElapsed, message, emptyMap() ); + RunMode runMode, + long testRunId, + String source, + String sourceText, + String name, + String nameText, + String group, + String message, + Integer timeElapsed, + // StackTraceWriter: + String traceMessage, + String smartTrimmedStackTrace, + String stackTrace) + throws NumberFormatException { + StackTraceWriter stackTraceWriter = toTrace(traceMessage, smartTrimmedStackTrace, stackTrace); + return reportEntry( + runMode, + testRunId, + source, + sourceText, + name, + nameText, + group, + stackTraceWriter, + timeElapsed, + message, + emptyMap()); } - private static Map segmentsToEvents() - { + private static Map segmentsToEvents() { Map events = new HashMap<>(); - for ( ForkedProcessEventType event : ForkedProcessEventType.values() ) - { + for (ForkedProcessEventType event : ForkedProcessEventType.values()) { byte[] array = event.getOpcodeBinary(); - events.put( new Segment( array, 0, array.length ), event ); + events.put(new Segment(array, 0, array.length), event); } return events; } - private static Map segmentsToRunModes() - { + private static Map segmentsToRunModes() { Map runModes = new HashMap<>(); - for ( RunMode runMode : RunMode.values() ) - { + for (RunMode runMode : RunMode.values()) { byte[] array = runMode.getRunmodeBinary(); - runModes.put( new Segment( array, 0, array.length ), runMode ); + runModes.put(new Segment(array, 0, array.length), runMode); } return runModes; } @Override - protected void debugStream( byte[] array, int position, int remaining ) - { - if ( debugSink == null ) - { + protected void debugStream(byte[] array, int position, int remaining) { + if (debugSink == null) { return; } - try - { - debugSink.write( array, position, remaining ); - } - catch ( IOException e ) - { + try { + debugSink.write(array, position, remaining); + } catch (IOException e) { // logger file was deleted // System.out is already used by the stream in this decoder } } - private OutputStream newDebugSink( ForkNodeArguments arguments ) - { + private OutputStream newDebugSink(ForkNodeArguments arguments) { final File sink = arguments.getEventStreamBinaryFile(); - if ( sink == null ) - { + if (sink == null) { return null; } - try - { - OutputStream fos = new FileOutputStream( sink, true ); - final OutputStream os = new BufferedOutputStream( fos, DEBUG_SINK_BUFFER_SIZE ); - addShutDownHook( new Thread( new FutureTask<>( () -> - { + try { + OutputStream fos = new FileOutputStream(sink, true); + final OutputStream os = new BufferedOutputStream(fos, DEBUG_SINK_BUFFER_SIZE); + addShutDownHook(new Thread(new FutureTask<>(() -> { os.close(); return null; - } ) ) ); + }))); return os; - } - catch ( FileNotFoundException e ) - { + } catch (FileNotFoundException e) { return null; } } @Override - public void close() throws IOException - { + public void close() throws IOException { // do NOT close the channel, it's std/out. - if ( debugSink != null ) - { + if (debugSink != null) { debugSink.close(); } } diff --git a/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/AbstractSurefireMojoJava7PlusTest.java b/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/AbstractSurefireMojoJava7PlusTest.java index 6f91ccf75c..7f3834b335 100644 --- a/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/AbstractSurefireMojoJava7PlusTest.java +++ b/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/AbstractSurefireMojoJava7PlusTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,27 +16,35 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.surefire; + +import java.io.File; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.DefaultArtifact; import org.apache.maven.artifact.handler.ArtifactHandler; import org.apache.maven.artifact.versioning.VersionRange; import org.apache.maven.plugin.surefire.log.PluginConsoleLogger; +import org.apache.maven.surefire.api.suite.RunResult; +import org.apache.maven.surefire.api.util.DefaultScanResult; import org.apache.maven.surefire.booter.ClassLoaderConfiguration; import org.apache.maven.surefire.booter.Classpath; import org.apache.maven.surefire.booter.ModularClasspathConfiguration; import org.apache.maven.surefire.booter.StartupConfiguration; import org.apache.maven.surefire.extensions.ForkNodeFactory; -import org.apache.maven.surefire.api.suite.RunResult; -import org.apache.maven.surefire.api.util.DefaultScanResult; import org.apache.maven.surefire.providerapi.ProviderInfo; import org.apache.maven.surefire.providerapi.ProviderRequirements; import org.codehaus.plexus.languages.java.jpms.JavaModuleDescriptor; import org.codehaus.plexus.languages.java.jpms.LocationManager; +import org.codehaus.plexus.languages.java.jpms.ModuleNameSource; import org.codehaus.plexus.languages.java.jpms.ResolvePathResult; import org.codehaus.plexus.languages.java.jpms.ResolvePathsRequest; import org.codehaus.plexus.languages.java.jpms.ResolvePathsResult; -import org.codehaus.plexus.languages.java.jpms.ModuleNameSource; import org.codehaus.plexus.logging.Logger; import org.junit.Test; import org.junit.runner.RunWith; @@ -48,13 +54,6 @@ import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; -import java.io.File; -import java.util.HashMap; -import java.util.List; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Set; - import static java.util.Arrays.asList; import static java.util.Collections.singleton; import static java.util.Collections.singletonMap; @@ -68,8 +67,8 @@ import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -import static org.powermock.api.mockito.PowerMockito.doReturn; import static org.powermock.api.mockito.PowerMockito.doNothing; +import static org.powermock.api.mockito.PowerMockito.doReturn; import static org.powermock.api.mockito.PowerMockito.mock; import static org.powermock.api.mockito.PowerMockito.mockStatic; import static org.powermock.api.mockito.PowerMockito.spy; @@ -79,11 +78,10 @@ /** * Test for {@link AbstractSurefireMojo}. */ -@RunWith( PowerMockRunner.class ) -@PrepareForTest( { AbstractSurefireMojo.class, ResolvePathsRequest.class } ) -@PowerMockIgnore( { "org.jacoco.agent.rt.*", "com.vladium.emma.rt.*" } ) -public class AbstractSurefireMojoJava7PlusTest -{ +@RunWith(PowerMockRunner.class) +@PrepareForTest({AbstractSurefireMojo.class, ResolvePathsRequest.class}) +@PowerMockIgnore({"org.jacoco.agent.rt.*", "com.vladium.emma.rt.*"}) +public class AbstractSurefireMojoJava7PlusTest { @Mock private ArtifactHandler handler; @@ -94,153 +92,167 @@ public class AbstractSurefireMojoJava7PlusTest private JavaModuleDescriptor descriptor; @Test - @SuppressWarnings( "checkstyle:linelength" ) - public void shouldHaveStartupConfigForModularClasspath() - throws Exception - { - AbstractSurefireMojo mojo = spy( new Mojo() ); - doReturn( locationManager ) - .when( mojo, "getLocationManager" ); + @SuppressWarnings("checkstyle:linelength") + public void shouldHaveStartupConfigForModularClasspath() throws Exception { + AbstractSurefireMojo mojo = spy(new Mojo()); + doReturn(locationManager).when(mojo, "getLocationManager"); - when( handler.isAddedToClasspath() ).thenReturn( true ); + when(handler.isAddedToClasspath()).thenReturn(true); - VersionRange v1 = createFromVersion( "1" ); - Artifact modular = new DefaultArtifact( "x", "modular", v1, "compile", "jar", "", handler ); - modular.setFile( mockFile( "modular.jar" ) ); + VersionRange v1 = createFromVersion("1"); + Artifact modular = new DefaultArtifact("x", "modular", v1, "compile", "jar", "", handler); + modular.setFile(mockFile("modular.jar")); - VersionRange v2 = createFromVersion( "1" ); - Artifact nonModular = new DefaultArtifact( "x", "non-modular", v2, "test", "jar", "", handler ); - nonModular.setFile( mockFile( "non-modular.jar" ) ); + VersionRange v2 = createFromVersion("1"); + Artifact nonModular = new DefaultArtifact("x", "non-modular", v2, "test", "jar", "", handler); + nonModular.setFile(mockFile("non-modular.jar")); - VersionRange v3 = createFromVersion( "4.12" ); - Artifact junit = new DefaultArtifact( "junit", "junit", v3, "test", "jar", "", handler ); - junit.setFile( mockFile( "junit.jar" ) ); + VersionRange v3 = createFromVersion("4.12"); + Artifact junit = new DefaultArtifact("junit", "junit", v3, "test", "jar", "", handler); + junit.setFile(mockFile("junit.jar")); - VersionRange v4 = createFromVersion( "1.3.0" ); - Artifact hamcrest = new DefaultArtifact( "org.hamcrest", "hamcrest-core", v4, "test", "jar", "", handler ); - hamcrest.setFile( mockFile( "hamcrest.jar" ) ); + VersionRange v4 = createFromVersion("1.3.0"); + Artifact hamcrest = new DefaultArtifact("org.hamcrest", "hamcrest-core", v4, "test", "jar", "", handler); + hamcrest.setFile(mockFile("hamcrest.jar")); - File classesDir = mockFile( "classes" ); - File testClassesDir = mockFile( "test-classes" ); + File classesDir = mockFile("classes"); + File testClassesDir = mockFile("test-classes"); TestClassPath testClasspath = - new TestClassPath( asList( modular, nonModular, junit, hamcrest ), classesDir, testClassesDir, - null ); - - doReturn( testClasspath ).when( mojo, "generateTestClasspath" ); - doReturn( 1 ).when( mojo, "getEffectiveForkCount" ); - doReturn( true ).when( mojo, "effectiveIsEnableAssertions" ); - when( mojo.isChildDelegation() ).thenReturn( false ); - when( mojo.getTestClassesDirectory() ).thenReturn( testClassesDir ); - - DefaultScanResult scanResult = mock( DefaultScanResult.class ); - when( scanResult.getClasses() ).thenReturn( asList( "org.apache.A", "org.apache.B" ) ); - - ClassLoaderConfiguration classLoaderConfiguration = new ClassLoaderConfiguration( false, true ); - - VersionRange v5 = createFromVersion( "1" ); - Artifact providerArtifact = new DefaultArtifact( "org.apache.maven.surefire", "surefire-provider", - v5, "runtime", "jar", "", handler ); - providerArtifact.setFile( mockFile( "surefire-provider.jar" ) ); - Set providerClasspath = singleton( providerArtifact ); - - ResolvePathResult moduleInfo = mock( ResolvePathResult.class ); - when( moduleInfo.getModuleDescriptor() ).thenReturn( descriptor ); - - @SuppressWarnings( "unchecked" ) - ResolvePathsRequest req = mock( ResolvePathsRequest.class ); - mockStatic( ResolvePathsRequest.class ); - when( ResolvePathsRequest.ofStrings( eq( testClasspath.toClasspath().getClassPath() ) ) ).thenReturn( req ); - when( req.setJdkHome( anyString() ) ).thenReturn( req ); - when( req.setIncludeStatic( true ) ).thenReturn( req ); - when( req.setIncludeAllProviders( anyBoolean() ) ).thenReturn( req ); - when( req.setModuleDescriptor( eq( descriptor ) ) ).thenReturn( req ); - - when( descriptor.name() ).thenReturn( "abc" ); - - @SuppressWarnings( "unchecked" ) - ResolvePathsResult res = mock( ResolvePathsResult.class ); - when( res.getMainModuleDescriptor() ).thenReturn( descriptor ); - when( res.getClasspathElements() ).thenReturn( asList( "non-modular.jar", "junit.jar", "hamcrest.jar" ) ); + new TestClassPath(asList(modular, nonModular, junit, hamcrest), classesDir, testClassesDir, null); + + doReturn(testClasspath).when(mojo, "generateTestClasspath"); + doReturn(1).when(mojo, "getEffectiveForkCount"); + doReturn(true).when(mojo, "effectiveIsEnableAssertions"); + when(mojo.isChildDelegation()).thenReturn(false); + when(mojo.getTestClassesDirectory()).thenReturn(testClassesDir); + + DefaultScanResult scanResult = mock(DefaultScanResult.class); + when(scanResult.getClasses()).thenReturn(asList("org.apache.A", "org.apache.B")); + + ClassLoaderConfiguration classLoaderConfiguration = new ClassLoaderConfiguration(false, true); + + VersionRange v5 = createFromVersion("1"); + Artifact providerArtifact = new DefaultArtifact( + "org.apache.maven.surefire", "surefire-provider", v5, "runtime", "jar", "", handler); + providerArtifact.setFile(mockFile("surefire-provider.jar")); + Set providerClasspath = singleton(providerArtifact); + + ResolvePathResult moduleInfo = mock(ResolvePathResult.class); + when(moduleInfo.getModuleDescriptor()).thenReturn(descriptor); + + @SuppressWarnings("unchecked") + ResolvePathsRequest req = mock(ResolvePathsRequest.class); + mockStatic(ResolvePathsRequest.class); + when(ResolvePathsRequest.ofStrings(eq(testClasspath.toClasspath().getClassPath()))) + .thenReturn(req); + when(req.setJdkHome(anyString())).thenReturn(req); + when(req.setIncludeStatic(true)).thenReturn(req); + when(req.setIncludeAllProviders(anyBoolean())).thenReturn(req); + when(req.setModuleDescriptor(eq(descriptor))).thenReturn(req); + + when(descriptor.name()).thenReturn("abc"); + + @SuppressWarnings("unchecked") + ResolvePathsResult res = mock(ResolvePathsResult.class); + when(res.getMainModuleDescriptor()).thenReturn(descriptor); + when(res.getClasspathElements()).thenReturn(asList("non-modular.jar", "junit.jar", "hamcrest.jar")); Map mod = new LinkedHashMap<>(); - mod.put( "modular.jar", null ); - mod.put( "classes", null ); - when( res.getModulepathElements() ).thenReturn( mod ); - when( res.getPathExceptions() ).thenReturn( singletonMap( "java 1.8", new Exception( "low version" ) ) ); - when( locationManager.resolvePaths( eq( req ) ) ).thenReturn( res ); - - Logger logger = mock( Logger.class ); - when( logger.isDebugEnabled() ).thenReturn( true ); - doNothing().when( logger ).debug( anyString() ); - when( mojo.getConsoleLogger() ).thenReturn( new PluginConsoleLogger( logger ) ); - - Artifact common = new DefaultArtifact( "org.apache.maven.surefire", "maven-surefire-common", v5, "runtime", - "jar", "", handler ); - common.setFile( mockFile( "maven-surefire-common.jar" ) ); - - Artifact ext = new DefaultArtifact( "org.apache.maven.surefire", "surefire-extensions-api", v5, "runtime", - "jar", "", handler ); - ext.setFile( mockFile( "surefire-extensions-api.jar" ) ); - - Artifact api = new DefaultArtifact( "org.apache.maven.surefire", "surefire-api", v5, "runtime", - "jar", "", handler ); - api.setFile( mockFile( "surefire-api.jar" ) ); - - Artifact loggerApi = new DefaultArtifact( "org.apache.maven.surefire", "surefire-logger-api", v5, "runtime", - "jar", "", handler ); - loggerApi.setFile( mockFile( "surefire-logger-api.jar" ) ); - - Artifact spi = new DefaultArtifact( "org.apache.maven.surefire", "surefire-extensions-spi", - createFromVersion( "1" ), "runtime", "jar", "", handler ); - spi.setFile( mockFile( "surefire-extensions-spi.jar" ) ); - - Artifact booter = new DefaultArtifact( "org.apache.maven.surefire", "surefire-booter", - createFromVersion( "1" ), "runtime", "jar", "", handler ); - booter.setFile( mockFile( "surefire-booter.jar" ) ); - - Artifact utils = new DefaultArtifact( "org.apache.maven.surefire", "surefire-shared-utils", - createFromVersion( "1" ), "runtime", "jar", "", handler ); - utils.setFile( mockFile( "surefire-shared-utils.jar" ) ); + mod.put("modular.jar", null); + mod.put("classes", null); + when(res.getModulepathElements()).thenReturn(mod); + when(res.getPathExceptions()).thenReturn(singletonMap("java 1.8", new Exception("low version"))); + when(locationManager.resolvePaths(eq(req))).thenReturn(res); + + Logger logger = mock(Logger.class); + when(logger.isDebugEnabled()).thenReturn(true); + doNothing().when(logger).debug(anyString()); + when(mojo.getConsoleLogger()).thenReturn(new PluginConsoleLogger(logger)); + + Artifact common = new DefaultArtifact( + "org.apache.maven.surefire", "maven-surefire-common", v5, "runtime", "jar", "", handler); + common.setFile(mockFile("maven-surefire-common.jar")); + + Artifact ext = new DefaultArtifact( + "org.apache.maven.surefire", "surefire-extensions-api", v5, "runtime", "jar", "", handler); + ext.setFile(mockFile("surefire-extensions-api.jar")); + + Artifact api = + new DefaultArtifact("org.apache.maven.surefire", "surefire-api", v5, "runtime", "jar", "", handler); + api.setFile(mockFile("surefire-api.jar")); + + Artifact loggerApi = new DefaultArtifact( + "org.apache.maven.surefire", "surefire-logger-api", v5, "runtime", "jar", "", handler); + loggerApi.setFile(mockFile("surefire-logger-api.jar")); + + Artifact spi = new DefaultArtifact( + "org.apache.maven.surefire", + "surefire-extensions-spi", + createFromVersion("1"), + "runtime", + "jar", + "", + handler); + spi.setFile(mockFile("surefire-extensions-spi.jar")); + + Artifact booter = new DefaultArtifact( + "org.apache.maven.surefire", "surefire-booter", createFromVersion("1"), "runtime", "jar", "", handler); + booter.setFile(mockFile("surefire-booter.jar")); + + Artifact utils = new DefaultArtifact( + "org.apache.maven.surefire", + "surefire-shared-utils", + createFromVersion("1"), + "runtime", + "jar", + "", + handler); + utils.setFile(mockFile("surefire-shared-utils.jar")); Map artifacts = new HashMap<>(); - artifacts.put( "org.apache.maven.surefire:maven-surefire-common", common ); - artifacts.put( "org.apache.maven.surefire:surefire-extensions-api", ext ); - artifacts.put( "org.apache.maven.surefire:surefire-api", api ); - artifacts.put( "org.apache.maven.surefire:surefire-logger-api", loggerApi ); - artifacts.put( "org.apache.maven.surefire:surefire-extensions-spi", spi ); - artifacts.put( "org.apache.maven.surefire:surefire-booter", booter ); - artifacts.put( "org.apache.maven.surefire:surefire-shared-utils", utils ); - when( mojo.getPluginArtifactMap() ).thenReturn( artifacts ); - - ProviderInfo providerInfo = mock( ProviderInfo.class ); - when( providerInfo.getProviderName() ).thenReturn( "org.asf.Provider" ); - when( providerInfo.getProviderClasspath() ).thenReturn( providerClasspath ); - - StartupConfiguration conf = invokeMethod( mojo, "newStartupConfigWithModularPath", - classLoaderConfiguration, providerInfo, - new ResolvePathResultWrapper( moduleInfo, true ), scanResult, "", testClasspath ); - - verify( mojo, times( 1 ) ).effectiveIsEnableAssertions(); - verify( mojo, times( 1 ) ).isChildDelegation(); - verify( mojo, times( 1 ) ).getTestClassesDirectory(); - verify( scanResult, times( 1 ) ).getClasses(); - verifyStatic( ResolvePathsRequest.class, times( 1 ) ); - ResolvePathsRequest.ofStrings( eq( testClasspath.toClasspath().getClassPath() ) ); - verify( req, times( 1 ) ).setModuleDescriptor( eq( descriptor ) ); - verify( res, times( 1 ) ).getClasspathElements(); - verify( res, times( 1 ) ).getModulepathElements(); - verify( locationManager, times( 1 ) ).resolvePaths( eq( req ) ); - ArgumentCaptor argument1 = ArgumentCaptor.forClass( String.class ); - ArgumentCaptor argument2 = ArgumentCaptor.forClass( Exception.class ); - verify( logger, times( 1 ) ).warn( argument1.capture(), argument2.capture() ); - assertThat( argument1.getValue() ) - .isEqualTo( "Exception for 'java 1.8'." ); - assertThat( argument2.getValue().getMessage() ) - .isEqualTo( "low version" ); - ArgumentCaptor argument = ArgumentCaptor.forClass( String.class ); - verify( logger, times( 9 ) ).debug( argument.capture() ); - assertThat( argument.getAllValues() ) - .containsExactly( "main module descriptor name: abc", + artifacts.put("org.apache.maven.surefire:maven-surefire-common", common); + artifacts.put("org.apache.maven.surefire:surefire-extensions-api", ext); + artifacts.put("org.apache.maven.surefire:surefire-api", api); + artifacts.put("org.apache.maven.surefire:surefire-logger-api", loggerApi); + artifacts.put("org.apache.maven.surefire:surefire-extensions-spi", spi); + artifacts.put("org.apache.maven.surefire:surefire-booter", booter); + artifacts.put("org.apache.maven.surefire:surefire-shared-utils", utils); + when(mojo.getPluginArtifactMap()).thenReturn(artifacts); + + ProviderInfo providerInfo = mock(ProviderInfo.class); + when(providerInfo.getProviderName()).thenReturn("org.asf.Provider"); + when(providerInfo.getProviderClasspath()).thenReturn(providerClasspath); + + StartupConfiguration conf = invokeMethod( + mojo, + "newStartupConfigWithModularPath", + classLoaderConfiguration, + providerInfo, + new ResolvePathResultWrapper(moduleInfo, true), + scanResult, + "", + testClasspath); + + verify(mojo, times(1)).effectiveIsEnableAssertions(); + verify(mojo, times(1)).isChildDelegation(); + verify(mojo, times(1)).getTestClassesDirectory(); + verify(scanResult, times(1)).getClasses(); + verifyStatic(ResolvePathsRequest.class, times(1)); + ResolvePathsRequest.ofStrings(eq(testClasspath.toClasspath().getClassPath())); + verify(req, times(1)).setModuleDescriptor(eq(descriptor)); + verify(res, times(1)).getClasspathElements(); + verify(res, times(1)).getModulepathElements(); + verify(locationManager, times(1)).resolvePaths(eq(req)); + ArgumentCaptor argument1 = ArgumentCaptor.forClass(String.class); + ArgumentCaptor argument2 = ArgumentCaptor.forClass(Exception.class); + verify(logger, times(1)).warn(argument1.capture(), argument2.capture()); + assertThat(argument1.getValue()).isEqualTo("Exception for 'java 1.8'."); + assertThat(argument2.getValue().getMessage()).isEqualTo("low version"); + ArgumentCaptor argument = ArgumentCaptor.forClass(String.class); + verify(logger, times(9)).debug(argument.capture()); + assertThat(argument.getAllValues()) + .containsExactly( + "main module descriptor name: abc", "test classpath: non-modular.jar junit.jar hamcrest.jar", "test modulepath: modular.jar classes", "provider classpath: surefire-provider.jar", @@ -248,735 +260,595 @@ public void shouldHaveStartupConfigForModularClasspath() "test(compact) modulepath: modular.jar classes", "provider(compact) classpath: surefire-provider.jar", "in-process classpath: surefire-provider.jar maven-surefire-common.jar surefire-booter.jar surefire-extensions-api.jar surefire-api.jar surefire-extensions-spi.jar surefire-logger-api.jar surefire-shared-utils.jar", - "in-process(compact) classpath: surefire-provider.jar maven-surefire-common.jar surefire-booter.jar surefire-extensions-api.jar surefire-api.jar surefire-extensions-spi.jar surefire-logger-api.jar surefire-shared-utils.jar" - ); - - assertThat( conf ).isNotNull(); - assertThat( conf.isShadefire() ).isFalse(); - assertThat( conf.isProviderMainClass() ).isFalse(); - assertThat( conf.isManifestOnlyJarRequestedAndUsable() ).isFalse(); - assertThat( conf.getClassLoaderConfiguration() ).isSameAs( classLoaderConfiguration ); - assertThat( conf.getProviderClassName() ).isEqualTo( "org.asf.Provider" ); - assertThat( conf.getActualClassName() ).isEqualTo( "org.asf.Provider" ); - assertThat( conf.getClasspathConfiguration() ).isNotNull(); - assertThat( ( Object ) conf.getClasspathConfiguration().getTestClasspath() ) - .isEqualTo( new Classpath( res.getClasspathElements() ) ); - assertThat( ( Object ) conf.getClasspathConfiguration().getProviderClasspath() ) - .isEqualTo( new Classpath( singleton( "surefire-provider.jar" ) ) ); - assertThat( conf.getClasspathConfiguration() ).isInstanceOf( ModularClasspathConfiguration.class ); - ModularClasspathConfiguration mcc = ( ModularClasspathConfiguration ) conf.getClasspathConfiguration(); - assertThat( mcc.getModularClasspath().getModuleNameFromDescriptor() ).isEqualTo( "abc" ); - assertThat( mcc.getModularClasspath().getPackages() ).containsOnly( "org.apache" ); - assertThat( mcc.getModularClasspath().getPatchFile().getAbsolutePath() ) - .isEqualTo( "test-classes" ); - assertThat( mcc.getModularClasspath().getModulePath() ) - .containsExactly( "modular.jar", "classes" ); + "in-process(compact) classpath: surefire-provider.jar maven-surefire-common.jar surefire-booter.jar surefire-extensions-api.jar surefire-api.jar surefire-extensions-spi.jar surefire-logger-api.jar surefire-shared-utils.jar"); + + assertThat(conf).isNotNull(); + assertThat(conf.isShadefire()).isFalse(); + assertThat(conf.isProviderMainClass()).isFalse(); + assertThat(conf.isManifestOnlyJarRequestedAndUsable()).isFalse(); + assertThat(conf.getClassLoaderConfiguration()).isSameAs(classLoaderConfiguration); + assertThat(conf.getProviderClassName()).isEqualTo("org.asf.Provider"); + assertThat(conf.getActualClassName()).isEqualTo("org.asf.Provider"); + assertThat(conf.getClasspathConfiguration()).isNotNull(); + assertThat((Object) conf.getClasspathConfiguration().getTestClasspath()) + .isEqualTo(new Classpath(res.getClasspathElements())); + assertThat((Object) conf.getClasspathConfiguration().getProviderClasspath()) + .isEqualTo(new Classpath(singleton("surefire-provider.jar"))); + assertThat(conf.getClasspathConfiguration()).isInstanceOf(ModularClasspathConfiguration.class); + ModularClasspathConfiguration mcc = (ModularClasspathConfiguration) conf.getClasspathConfiguration(); + assertThat(mcc.getModularClasspath().getModuleNameFromDescriptor()).isEqualTo("abc"); + assertThat(mcc.getModularClasspath().getPackages()).containsOnly("org.apache"); + assertThat(mcc.getModularClasspath().getPatchFile().getAbsolutePath()).isEqualTo("test-classes"); + assertThat(mcc.getModularClasspath().getModulePath()).containsExactly("modular.jar", "classes"); } @Test - @SuppressWarnings( "checkstyle:linelength" ) - public void shouldHaveStartupConfigForModularClasspathAndTestDescriptor() - throws Exception - { - AbstractSurefireMojo mojo = spy( new Mojo() ); - doReturn( locationManager ) - .when( mojo, "getLocationManager" ); + @SuppressWarnings("checkstyle:linelength") + public void shouldHaveStartupConfigForModularClasspathAndTestDescriptor() throws Exception { + AbstractSurefireMojo mojo = spy(new Mojo()); + doReturn(locationManager).when(mojo, "getLocationManager"); - when( handler.isAddedToClasspath() ).thenReturn( true ); + when(handler.isAddedToClasspath()).thenReturn(true); - VersionRange v1 = createFromVersion( "1" ); - Artifact modular = new DefaultArtifact( "x", "modular", v1, "compile", "jar", "", handler ); - modular.setFile( mockFile( "modular.jar" ) ); + VersionRange v1 = createFromVersion("1"); + Artifact modular = new DefaultArtifact("x", "modular", v1, "compile", "jar", "", handler); + modular.setFile(mockFile("modular.jar")); - VersionRange v2 = createFromVersion( "1" ); - Artifact nonModular = new DefaultArtifact( "x", "non-modular", v2, "test", "jar", "", handler ); - nonModular.setFile( mockFile( "non-modular.jar" ) ); + VersionRange v2 = createFromVersion("1"); + Artifact nonModular = new DefaultArtifact("x", "non-modular", v2, "test", "jar", "", handler); + nonModular.setFile(mockFile("non-modular.jar")); - VersionRange v3 = createFromVersion( "4.12" ); - Artifact junit = new DefaultArtifact( "junit", "junit", v3, "test", "jar", "", handler ); - junit.setFile( mockFile( "junit.jar" ) ); + VersionRange v3 = createFromVersion("4.12"); + Artifact junit = new DefaultArtifact("junit", "junit", v3, "test", "jar", "", handler); + junit.setFile(mockFile("junit.jar")); - VersionRange v4 = createFromVersion( "1.3.0" ); - Artifact hamcrest = new DefaultArtifact( "org.hamcrest", "hamcrest-core", v4, "test", "jar", "", handler ); - hamcrest.setFile( mockFile( "hamcrest.jar" ) ); + VersionRange v4 = createFromVersion("1.3.0"); + Artifact hamcrest = new DefaultArtifact("org.hamcrest", "hamcrest-core", v4, "test", "jar", "", handler); + hamcrest.setFile(mockFile("hamcrest.jar")); - File classesDir = mockFile( "classes" ); - File testClassesDir = mockFile( "test-classes" ); + File classesDir = mockFile("classes"); + File testClassesDir = mockFile("test-classes"); TestClassPath testClasspath = - new TestClassPath( asList( modular, nonModular, junit, hamcrest ), classesDir, testClassesDir, - null ); - - doReturn( testClasspath ).when( mojo, "generateTestClasspath" ); - doReturn( 1 ).when( mojo, "getEffectiveForkCount" ); - doReturn( true ).when( mojo, "effectiveIsEnableAssertions" ); - when( mojo.isChildDelegation() ).thenReturn( false ); - when( mojo.getTestClassesDirectory() ).thenReturn( testClassesDir ); - - DefaultScanResult scanResult = mock( DefaultScanResult.class ); - when( scanResult.getClasses() ).thenReturn( asList( "org.apache.A", "org.apache.B" ) ); - - ClassLoaderConfiguration classLoaderConfiguration = new ClassLoaderConfiguration( false, true ); - - VersionRange v5 = createFromVersion( "1" ); - Artifact providerArtifact = new DefaultArtifact( "org.apache.maven.surefire", "surefire-provider", - v5, "runtime", "jar", "", handler ); - providerArtifact.setFile( mockFile( "surefire-provider.jar" ) ); - Set providerClasspath = singleton( providerArtifact ); - - ResolvePathResult moduleInfo = mock( ResolvePathResult.class ); - when( moduleInfo.getModuleDescriptor() ).thenReturn( descriptor ); - - when( descriptor.name() ).thenReturn( "abc" ); - - Logger logger = mock( Logger.class ); - when( logger.isDebugEnabled() ).thenReturn( true ); - doNothing().when( logger ).debug( anyString() ); - when( mojo.getConsoleLogger() ).thenReturn( new PluginConsoleLogger( logger ) ); - - Artifact common = new DefaultArtifact( "org.apache.maven.surefire", "maven-surefire-common", v5, "runtime", - "jar", "", handler ); - common.setFile( mockFile( "maven-surefire-common.jar" ) ); - - Artifact ext = new DefaultArtifact( "org.apache.maven.surefire", "surefire-extensions-api", v5, "runtime", - "jar", "", handler ); - ext.setFile( mockFile( "surefire-extensions-api.jar" ) ); - - Artifact api = new DefaultArtifact( "org.apache.maven.surefire", "surefire-api", v5, "runtime", - "jar", "", handler ); - api.setFile( mockFile( "surefire-api.jar" ) ); - - Artifact loggerApi = new DefaultArtifact( "org.apache.maven.surefire", "surefire-logger-api", v5, "runtime", - "jar", "", handler ); - loggerApi.setFile( mockFile( "surefire-logger-api.jar" ) ); - - Artifact spi = new DefaultArtifact( "org.apache.maven.surefire", "surefire-extensions-spi", - createFromVersion( "1" ), "runtime", "jar", "", handler ); - spi.setFile( mockFile( "surefire-extensions-spi.jar" ) ); - - Artifact booter = new DefaultArtifact( "org.apache.maven.surefire", "surefire-booter", - createFromVersion( "1" ), "runtime", "jar", "", handler ); - booter.setFile( mockFile( "surefire-booter.jar" ) ); - - Artifact utils = new DefaultArtifact( "org.apache.maven.surefire", "surefire-shared-utils", - createFromVersion( "1" ), "runtime", "jar", "", handler ); - utils.setFile( mockFile( "surefire-shared-utils.jar" ) ); + new TestClassPath(asList(modular, nonModular, junit, hamcrest), classesDir, testClassesDir, null); + + doReturn(testClasspath).when(mojo, "generateTestClasspath"); + doReturn(1).when(mojo, "getEffectiveForkCount"); + doReturn(true).when(mojo, "effectiveIsEnableAssertions"); + when(mojo.isChildDelegation()).thenReturn(false); + when(mojo.getTestClassesDirectory()).thenReturn(testClassesDir); + + DefaultScanResult scanResult = mock(DefaultScanResult.class); + when(scanResult.getClasses()).thenReturn(asList("org.apache.A", "org.apache.B")); + + ClassLoaderConfiguration classLoaderConfiguration = new ClassLoaderConfiguration(false, true); + + VersionRange v5 = createFromVersion("1"); + Artifact providerArtifact = new DefaultArtifact( + "org.apache.maven.surefire", "surefire-provider", v5, "runtime", "jar", "", handler); + providerArtifact.setFile(mockFile("surefire-provider.jar")); + Set providerClasspath = singleton(providerArtifact); + + ResolvePathResult moduleInfo = mock(ResolvePathResult.class); + when(moduleInfo.getModuleDescriptor()).thenReturn(descriptor); + + when(descriptor.name()).thenReturn("abc"); + + Logger logger = mock(Logger.class); + when(logger.isDebugEnabled()).thenReturn(true); + doNothing().when(logger).debug(anyString()); + when(mojo.getConsoleLogger()).thenReturn(new PluginConsoleLogger(logger)); + + Artifact common = new DefaultArtifact( + "org.apache.maven.surefire", "maven-surefire-common", v5, "runtime", "jar", "", handler); + common.setFile(mockFile("maven-surefire-common.jar")); + + Artifact ext = new DefaultArtifact( + "org.apache.maven.surefire", "surefire-extensions-api", v5, "runtime", "jar", "", handler); + ext.setFile(mockFile("surefire-extensions-api.jar")); + + Artifact api = + new DefaultArtifact("org.apache.maven.surefire", "surefire-api", v5, "runtime", "jar", "", handler); + api.setFile(mockFile("surefire-api.jar")); + + Artifact loggerApi = new DefaultArtifact( + "org.apache.maven.surefire", "surefire-logger-api", v5, "runtime", "jar", "", handler); + loggerApi.setFile(mockFile("surefire-logger-api.jar")); + + Artifact spi = new DefaultArtifact( + "org.apache.maven.surefire", + "surefire-extensions-spi", + createFromVersion("1"), + "runtime", + "jar", + "", + handler); + spi.setFile(mockFile("surefire-extensions-spi.jar")); + + Artifact booter = new DefaultArtifact( + "org.apache.maven.surefire", "surefire-booter", createFromVersion("1"), "runtime", "jar", "", handler); + booter.setFile(mockFile("surefire-booter.jar")); + + Artifact utils = new DefaultArtifact( + "org.apache.maven.surefire", + "surefire-shared-utils", + createFromVersion("1"), + "runtime", + "jar", + "", + handler); + utils.setFile(mockFile("surefire-shared-utils.jar")); Map artifacts = new HashMap<>(); - artifacts.put( "org.apache.maven.surefire:maven-surefire-common", common ); - artifacts.put( "org.apache.maven.surefire:surefire-extensions-api", ext ); - artifacts.put( "org.apache.maven.surefire:surefire-api", api ); - artifacts.put( "org.apache.maven.surefire:surefire-logger-api", loggerApi ); - artifacts.put( "org.apache.maven.surefire:surefire-extensions-spi", spi ); - artifacts.put( "org.apache.maven.surefire:surefire-booter", booter ); - artifacts.put( "org.apache.maven.surefire:surefire-shared-utils", utils ); - when( mojo.getPluginArtifactMap() ).thenReturn( artifacts ); - - ProviderInfo providerInfo = mock( ProviderInfo.class ); - when( providerInfo.getProviderName() ).thenReturn( "org.asf.Provider" ); - when( providerInfo.getProviderClasspath() ).thenReturn( providerClasspath ); - - StartupConfiguration conf = invokeMethod( mojo, "newStartupConfigWithModularPath", - classLoaderConfiguration, providerInfo, - new ResolvePathResultWrapper( moduleInfo, false ), scanResult, "", testClasspath ); - - verify( mojo, times( 1 ) ).effectiveIsEnableAssertions(); - verify( mojo, times( 1 ) ).isChildDelegation(); - verify( mojo, never() ).getTestClassesDirectory(); - ArgumentCaptor argument = ArgumentCaptor.forClass( String.class ); - verify( logger, times( 9 ) ).debug( argument.capture() ); - assertThat( argument.getAllValues() ) - .containsExactly( "main module descriptor name: abc", - "test classpath:", - "test modulepath: test-classes classes modular.jar non-modular.jar junit.jar hamcrest.jar", - "provider classpath: surefire-provider.jar", - "test(compact) classpath:", - "test(compact) modulepath: test-classes classes modular.jar non-modular.jar junit.jar hamcrest.jar", - "provider(compact) classpath: surefire-provider.jar", - "in-process classpath: surefire-provider.jar maven-surefire-common.jar surefire-booter.jar surefire-extensions-api.jar surefire-api.jar surefire-extensions-spi.jar surefire-logger-api.jar surefire-shared-utils.jar", - "in-process(compact) classpath: surefire-provider.jar maven-surefire-common.jar surefire-booter.jar surefire-extensions-api.jar surefire-api.jar surefire-extensions-spi.jar surefire-logger-api.jar surefire-shared-utils.jar" - ); - - assertThat( conf ).isNotNull(); - assertThat( conf.isShadefire() ).isFalse(); - assertThat( conf.isProviderMainClass() ).isFalse(); - assertThat( conf.isManifestOnlyJarRequestedAndUsable() ).isFalse(); - assertThat( conf.getClassLoaderConfiguration() ).isSameAs( classLoaderConfiguration ); - assertThat( conf.getProviderClassName() ).isEqualTo( "org.asf.Provider" ); - assertThat( conf.getActualClassName() ).isEqualTo( "org.asf.Provider" ); - assertThat( conf.getClasspathConfiguration() ).isNotNull(); - assertThat( ( Object ) conf.getClasspathConfiguration().getTestClasspath() ) - .isEqualTo( Classpath.emptyClasspath() ); - assertThat( ( Object ) conf.getClasspathConfiguration().getProviderClasspath() ) - .isEqualTo( new Classpath( singleton( "surefire-provider.jar" ) ) ); - assertThat( conf.getClasspathConfiguration() ).isInstanceOf( ModularClasspathConfiguration.class ); - ModularClasspathConfiguration mcc = ( ModularClasspathConfiguration ) conf.getClasspathConfiguration(); - assertThat( mcc.getModularClasspath().getModuleNameFromDescriptor() ).isEqualTo( "abc" ); - assertThat( mcc.getModularClasspath().getPackages() ).isEmpty(); - assertThat( mcc.getModularClasspath().getPatchFile() ) - .isNull(); - assertThat( mcc.getModularClasspath().getModulePath() ) - .hasSize( 6 ) - .containsSequence( "test-classes", "classes", "modular.jar", "non-modular.jar", - "junit.jar", "hamcrest.jar" ); + artifacts.put("org.apache.maven.surefire:maven-surefire-common", common); + artifacts.put("org.apache.maven.surefire:surefire-extensions-api", ext); + artifacts.put("org.apache.maven.surefire:surefire-api", api); + artifacts.put("org.apache.maven.surefire:surefire-logger-api", loggerApi); + artifacts.put("org.apache.maven.surefire:surefire-extensions-spi", spi); + artifacts.put("org.apache.maven.surefire:surefire-booter", booter); + artifacts.put("org.apache.maven.surefire:surefire-shared-utils", utils); + when(mojo.getPluginArtifactMap()).thenReturn(artifacts); + + ProviderInfo providerInfo = mock(ProviderInfo.class); + when(providerInfo.getProviderName()).thenReturn("org.asf.Provider"); + when(providerInfo.getProviderClasspath()).thenReturn(providerClasspath); + + StartupConfiguration conf = invokeMethod( + mojo, + "newStartupConfigWithModularPath", + classLoaderConfiguration, + providerInfo, + new ResolvePathResultWrapper(moduleInfo, false), + scanResult, + "", + testClasspath); + + verify(mojo, times(1)).effectiveIsEnableAssertions(); + verify(mojo, times(1)).isChildDelegation(); + verify(mojo, never()).getTestClassesDirectory(); + ArgumentCaptor argument = ArgumentCaptor.forClass(String.class); + verify(logger, times(9)).debug(argument.capture()); + assertThat(argument.getAllValues()) + .containsExactly( + "main module descriptor name: abc", + "test classpath:", + "test modulepath: test-classes classes modular.jar non-modular.jar junit.jar hamcrest.jar", + "provider classpath: surefire-provider.jar", + "test(compact) classpath:", + "test(compact) modulepath: test-classes classes modular.jar non-modular.jar junit.jar hamcrest.jar", + "provider(compact) classpath: surefire-provider.jar", + "in-process classpath: surefire-provider.jar maven-surefire-common.jar surefire-booter.jar surefire-extensions-api.jar surefire-api.jar surefire-extensions-spi.jar surefire-logger-api.jar surefire-shared-utils.jar", + "in-process(compact) classpath: surefire-provider.jar maven-surefire-common.jar surefire-booter.jar surefire-extensions-api.jar surefire-api.jar surefire-extensions-spi.jar surefire-logger-api.jar surefire-shared-utils.jar"); + + assertThat(conf).isNotNull(); + assertThat(conf.isShadefire()).isFalse(); + assertThat(conf.isProviderMainClass()).isFalse(); + assertThat(conf.isManifestOnlyJarRequestedAndUsable()).isFalse(); + assertThat(conf.getClassLoaderConfiguration()).isSameAs(classLoaderConfiguration); + assertThat(conf.getProviderClassName()).isEqualTo("org.asf.Provider"); + assertThat(conf.getActualClassName()).isEqualTo("org.asf.Provider"); + assertThat(conf.getClasspathConfiguration()).isNotNull(); + assertThat((Object) conf.getClasspathConfiguration().getTestClasspath()).isEqualTo(Classpath.emptyClasspath()); + assertThat((Object) conf.getClasspathConfiguration().getProviderClasspath()) + .isEqualTo(new Classpath(singleton("surefire-provider.jar"))); + assertThat(conf.getClasspathConfiguration()).isInstanceOf(ModularClasspathConfiguration.class); + ModularClasspathConfiguration mcc = (ModularClasspathConfiguration) conf.getClasspathConfiguration(); + assertThat(mcc.getModularClasspath().getModuleNameFromDescriptor()).isEqualTo("abc"); + assertThat(mcc.getModularClasspath().getPackages()).isEmpty(); + assertThat(mcc.getModularClasspath().getPatchFile()).isNull(); + assertThat(mcc.getModularClasspath().getModulePath()) + .hasSize(6) + .containsSequence( + "test-classes", "classes", "modular.jar", "non-modular.jar", "junit.jar", "hamcrest.jar"); } @Test - public void testAllProviderInfo() - { + public void testAllProviderInfo() { Mojo mojo = new Mojo(); - ProviderRequirements providerRequirements = new ProviderRequirements( true, false, true ); + ProviderRequirements providerRequirements = new ProviderRequirements(true, false, true); ProviderInfo providerInfo = mojo.newDynamicProviderInfo(); - assertThat( providerInfo.getProviderName() ) - .isEqualTo( "custom.Provider" ); - assertThat( providerInfo.getJpmsArguments( providerRequirements ) ) - .isEmpty(); + assertThat(providerInfo.getProviderName()).isEqualTo("custom.Provider"); + assertThat(providerInfo.getJpmsArguments(providerRequirements)).isEmpty(); providerInfo = mojo.newJUnit3ProviderInfo(); - assertThat( providerInfo.getProviderName() ) - .isEqualTo( "org.apache.maven.surefire.junit.JUnit3Provider" ); - assertThat( providerInfo.getJpmsArguments( providerRequirements ) ) - .isEmpty(); + assertThat(providerInfo.getProviderName()).isEqualTo("org.apache.maven.surefire.junit.JUnit3Provider"); + assertThat(providerInfo.getJpmsArguments(providerRequirements)).isEmpty(); providerInfo = mojo.newJUnit4ProviderInfo(); - assertThat( providerInfo.getProviderName() ) - .isEqualTo( "org.apache.maven.surefire.junit4.JUnit4Provider" ); - assertThat( providerInfo.getJpmsArguments( providerRequirements ) ) - .isEmpty(); + assertThat(providerInfo.getProviderName()).isEqualTo("org.apache.maven.surefire.junit4.JUnit4Provider"); + assertThat(providerInfo.getJpmsArguments(providerRequirements)).isEmpty(); providerInfo = mojo.newJUnit47ProviderInfo(); - assertThat( providerInfo.getProviderName() ) - .isEqualTo( "org.apache.maven.surefire.junitcore.JUnitCoreProvider" ); - assertThat( providerInfo.getJpmsArguments( providerRequirements ) ) - .isEmpty(); + assertThat(providerInfo.getProviderName()).isEqualTo("org.apache.maven.surefire.junitcore.JUnitCoreProvider"); + assertThat(providerInfo.getJpmsArguments(providerRequirements)).isEmpty(); providerInfo = mojo.newTestNgProviderInfo(); - assertThat( providerInfo.getProviderName() ) - .isEqualTo( "org.apache.maven.surefire.testng.TestNGProvider" ); - assertThat( providerInfo.getJpmsArguments( providerRequirements ) ) - .isEmpty(); + assertThat(providerInfo.getProviderName()).isEqualTo("org.apache.maven.surefire.testng.TestNGProvider"); + assertThat(providerInfo.getJpmsArguments(providerRequirements)).isEmpty(); providerInfo = mojo.newJUnitPlatformProviderInfo(); - assertThat( providerInfo.getProviderName() ) - .isEqualTo( "org.apache.maven.surefire.junitplatform.JUnitPlatformProvider" ); - List args = providerInfo.getJpmsArguments( providerRequirements ); - assertThat( args ) - .isNotEmpty() - .hasSize( 2 ) - .contains( new String[] { - "--add-opens", "org.junit.platform.commons/org.junit.platform.commons.util=ALL-UNNAMED"}, atIndex( 0 ) ) - .contains( new String[] { - "--add-opens", "org.junit.platform.commons/org.junit.platform.commons.logging=ALL-UNNAMED"}, atIndex( 1 ) ); + assertThat(providerInfo.getProviderName()) + .isEqualTo("org.apache.maven.surefire.junitplatform.JUnitPlatformProvider"); + List args = providerInfo.getJpmsArguments(providerRequirements); + assertThat(args) + .isNotEmpty() + .hasSize(2) + .contains( + new String[] { + "--add-opens", "org.junit.platform.commons/org.junit.platform.commons.util=ALL-UNNAMED" + }, + atIndex(0)) + .contains( + new String[] { + "--add-opens", "org.junit.platform.commons/org.junit.platform.commons.logging=ALL-UNNAMED" + }, + atIndex(1)); } @Test - public void shouldJoinStrings() throws Exception - { + public void shouldJoinStrings() throws Exception { Class[] methodArgTypes = {String[].class}; - Object[] args = { new String[]{"my-engine"} }; - String result = invokeMethod( AbstractSurefireMojo.class, "join", methodArgTypes, args ); - assertThat( result ).isNotNull(); - assertThat( result ).isEqualTo( "my-engine" ); + Object[] args = {new String[] {"my-engine"}}; + String result = invokeMethod(AbstractSurefireMojo.class, "join", methodArgTypes, args); + assertThat(result).isNotNull(); + assertThat(result).isEqualTo("my-engine"); - args = new Object[]{ new String[]{"my-engine1", "my-engine2"} }; - result = invokeMethod( AbstractSurefireMojo.class, "join", methodArgTypes, args ); - assertThat( result ).isNotNull(); - assertThat( result ).isEqualTo( "my-engine1,my-engine2" ); + args = new Object[] {new String[] {"my-engine1", "my-engine2"}}; + result = invokeMethod(AbstractSurefireMojo.class, "join", methodArgTypes, args); + assertThat(result).isNotNull(); + assertThat(result).isEqualTo("my-engine1,my-engine2"); - args = new Object[]{new String[0]}; - result = invokeMethod( AbstractSurefireMojo.class, "join", methodArgTypes, args ); - assertThat( result ).isNotNull(); - assertThat( result ).isEmpty(); + args = new Object[] {new String[0]}; + result = invokeMethod(AbstractSurefireMojo.class, "join", methodArgTypes, args); + assertThat(result).isNotNull(); + assertThat(result).isEmpty(); } - private static File mockFile( String absolutePath ) - { - File f = mock( File.class ); - when( f.getAbsolutePath() ).thenReturn( absolutePath ); + private static File mockFile(String absolutePath) { + File f = mock(File.class); + when(f.getAbsolutePath()).thenReturn(absolutePath); return f; } /** * */ - public static class Mojo - extends AbstractSurefireMojo - { - ProviderInfo newDynamicProviderInfo() - { - return new DynamicProviderInfo( "custom.Provider" ); + public static class Mojo extends AbstractSurefireMojo { + ProviderInfo newDynamicProviderInfo() { + return new DynamicProviderInfo("custom.Provider"); } - ProviderInfo newJUnit3ProviderInfo() - { + ProviderInfo newJUnit3ProviderInfo() { return new JUnit3ProviderInfo(); } - ProviderInfo newJUnit4ProviderInfo() - { - return new JUnit4ProviderInfo( null, null ); + ProviderInfo newJUnit4ProviderInfo() { + return new JUnit4ProviderInfo(null, null); } - ProviderInfo newJUnit47ProviderInfo() - { - return new JUnitCoreProviderInfo( null, null ); + ProviderInfo newJUnit47ProviderInfo() { + return new JUnitCoreProviderInfo(null, null); } - ProviderInfo newTestNgProviderInfo() - { - return new TestNgProviderInfo( null ); + ProviderInfo newTestNgProviderInfo() { + return new TestNgProviderInfo(null); } - ProviderInfo newJUnitPlatformProviderInfo() - { - return new JUnitPlatformProviderInfo( null, null, null ); + ProviderInfo newJUnitPlatformProviderInfo() { + return new JUnitPlatformProviderInfo(null, null, null); } @Override - protected String getPluginName() - { + protected String getPluginName() { return null; } @Override - protected int getRerunFailingTestsCount() - { + protected int getRerunFailingTestsCount() { return 0; } @Override - public boolean isSkipTests() - { + public boolean isSkipTests() { return false; } @Override - public void setSkipTests( boolean skipTests ) - { - - } + public void setSkipTests(boolean skipTests) {} @Override - public boolean isSkipExec() - { + public boolean isSkipExec() { return false; } @Override - public void setSkipExec( boolean skipExec ) - { - - } + public void setSkipExec(boolean skipExec) {} @Override - public boolean isSkip() - { + public boolean isSkip() { return false; } @Override - public void setSkip( boolean skip ) - { - - } + public void setSkip(boolean skip) {} @Override - public File getBasedir() - { + public File getBasedir() { return null; } @Override - public void setBasedir( File basedir ) - { - - } + public void setBasedir(File basedir) {} @Override - public File getTestClassesDirectory() - { + public File getTestClassesDirectory() { return null; } @Override - public void setTestClassesDirectory( File testClassesDirectory ) - { - - } + public void setTestClassesDirectory(File testClassesDirectory) {} @Override - public File getMainBuildPath() - { + public File getMainBuildPath() { return null; } @Override - public void setMainBuildPath( File mainBuildPath ) - { - - } + public void setMainBuildPath(File mainBuildPath) {} @Override - public File getReportsDirectory() - { + public File getReportsDirectory() { return null; } @Override - public void setReportsDirectory( File reportsDirectory ) - { - - } + public void setReportsDirectory(File reportsDirectory) {} @Override - public String getTest() - { + public String getTest() { return null; } @Override - public void setTest( String test ) - { - - } + public void setTest(String test) {} @Override - public List getIncludes() - { + public List getIncludes() { return null; } @Override - public File getIncludesFile() - { + public File getIncludesFile() { return null; } @Override - public void setIncludes( List includes ) - { - - } + public void setIncludes(List includes) {} @Override - public List getExcludes() - { + public List getExcludes() { return null; } @Override - public void setExcludes( List excludes ) - { - - } + public void setExcludes(List excludes) {} @Override - public boolean isPrintSummary() - { + public boolean isPrintSummary() { return false; } @Override - public void setPrintSummary( boolean printSummary ) - { - - } + public void setPrintSummary(boolean printSummary) {} @Override - public String getReportFormat() - { + public String getReportFormat() { return null; } @Override - public void setReportFormat( String reportFormat ) - { - - } + public void setReportFormat(String reportFormat) {} @Override - public boolean isUseFile() - { + public boolean isUseFile() { return false; } @Override - public void setUseFile( boolean useFile ) - { - - } + public void setUseFile(boolean useFile) {} @Override - public String getDebugForkedProcess() - { + public String getDebugForkedProcess() { return null; } @Override - public void setDebugForkedProcess( String debugForkedProcess ) - { - - } + public void setDebugForkedProcess(String debugForkedProcess) {} @Override - public int getForkedProcessTimeoutInSeconds() - { + public int getForkedProcessTimeoutInSeconds() { return 0; } @Override - public void setForkedProcessTimeoutInSeconds( int forkedProcessTimeoutInSeconds ) - { - - } + public void setForkedProcessTimeoutInSeconds(int forkedProcessTimeoutInSeconds) {} @Override - public int getForkedProcessExitTimeoutInSeconds() - { + public int getForkedProcessExitTimeoutInSeconds() { return 0; } @Override - public void setForkedProcessExitTimeoutInSeconds( int forkedProcessTerminationTimeoutInSeconds ) - { - - } + public void setForkedProcessExitTimeoutInSeconds(int forkedProcessTerminationTimeoutInSeconds) {} @Override - public double getParallelTestsTimeoutInSeconds() - { + public double getParallelTestsTimeoutInSeconds() { return 0; } @Override - public void setParallelTestsTimeoutInSeconds( double parallelTestsTimeoutInSeconds ) - { - - } + public void setParallelTestsTimeoutInSeconds(double parallelTestsTimeoutInSeconds) {} @Override - public double getParallelTestsTimeoutForcedInSeconds() - { + public double getParallelTestsTimeoutForcedInSeconds() { return 0; } @Override - public void setParallelTestsTimeoutForcedInSeconds( double parallelTestsTimeoutForcedInSeconds ) - { - - } + public void setParallelTestsTimeoutForcedInSeconds(double parallelTestsTimeoutForcedInSeconds) {} @Override - public boolean isUseSystemClassLoader() - { + public boolean isUseSystemClassLoader() { return false; } @Override - public void setUseSystemClassLoader( boolean useSystemClassLoader ) - { - - } + public void setUseSystemClassLoader(boolean useSystemClassLoader) {} @Override - public boolean isUseManifestOnlyJar() - { + public boolean isUseManifestOnlyJar() { return false; } @Override - public void setUseManifestOnlyJar( boolean useManifestOnlyJar ) - { - - } + public void setUseManifestOnlyJar(boolean useManifestOnlyJar) {} @Override - public String getEncoding() - { + public String getEncoding() { return null; } @Override - public void setEncoding( String encoding ) - { - - } + public void setEncoding(String encoding) {} @Override - public boolean getFailIfNoSpecifiedTests() - { + public boolean getFailIfNoSpecifiedTests() { return false; } @Override - public void setFailIfNoSpecifiedTests( boolean failIfNoSpecifiedTests ) - { - - } + public void setFailIfNoSpecifiedTests(boolean failIfNoSpecifiedTests) {} @Override - public int getSkipAfterFailureCount() - { + public int getSkipAfterFailureCount() { return 0; } @Override - public String getShutdown() - { + public String getShutdown() { return null; } @Override - public File getExcludesFile() - { + public File getExcludesFile() { return null; } @Override - protected List suiteXmlFiles() - { + protected List suiteXmlFiles() { return null; } @Override - protected boolean hasSuiteXmlFiles() - { + protected boolean hasSuiteXmlFiles() { return false; } @Override - protected String[] getExcludedEnvironmentVariables() - { + protected String[] getExcludedEnvironmentVariables() { return new String[0]; } @Override - public File[] getSuiteXmlFiles() - { + public File[] getSuiteXmlFiles() { return new File[0]; } @Override - public void setSuiteXmlFiles( File[] suiteXmlFiles ) - { - - } + public void setSuiteXmlFiles(File[] suiteXmlFiles) {} @Override - public String getRunOrder() - { + public String getRunOrder() { return null; } @Override - public void setRunOrder( String runOrder ) - { - - } + public void setRunOrder(String runOrder) {} @Override - public Long getRunOrderRandomSeed() - { + public Long getRunOrderRandomSeed() { return null; } @Override - public void setRunOrderRandomSeed( Long runOrderRandomSeed ) - { - - } + public void setRunOrderRandomSeed(Long runOrderRandomSeed) {} @Override - protected void handleSummary( RunResult summary, Exception firstForkException ) - { - - } + protected void handleSummary(RunResult summary, Exception firstForkException) {} @Override - protected boolean isSkipExecution() - { + protected boolean isSkipExecution() { return false; } @Override - protected String[] getDefaultIncludes() - { + protected String[] getDefaultIncludes() { return new String[0]; } @Override - protected String getReportSchemaLocation() - { + protected String getReportSchemaLocation() { return null; } @Override - protected boolean useModulePath() - { + protected boolean useModulePath() { return false; } @Override - protected void setUseModulePath( boolean useModulePath ) - { - - } + protected void setUseModulePath(boolean useModulePath) {} @Override - protected String getEnableProcessChecker() - { + protected String getEnableProcessChecker() { return null; } @Override - protected ForkNodeFactory getForkNode() - { + protected ForkNodeFactory getForkNode() { return null; } @Override - protected Artifact getMojoArtifact() - { + protected Artifact getMojoArtifact() { return null; } @Override - public File getSystemPropertiesFile() - { + public File getSystemPropertiesFile() { return null; } @Override - public void setSystemPropertiesFile( File systemPropertiesFile ) - { - - } + public void setSystemPropertiesFile(File systemPropertiesFile) {} @Override - public String[] getIncludeJUnit5Engines() - { + public String[] getIncludeJUnit5Engines() { return null; } @Override - public void setIncludeJUnit5Engines( String[] includeJUnit5Engines ) - { - - } + public void setIncludeJUnit5Engines(String[] includeJUnit5Engines) {} @Override - public String[] getExcludeJUnit5Engines() - { + public String[] getExcludeJUnit5Engines() { return null; } @Override - public void setExcludeJUnit5Engines( String[] excludeJUnit5Engines ) - { - - } + public void setExcludeJUnit5Engines(String[] excludeJUnit5Engines) {} } } diff --git a/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/AbstractSurefireMojoJunitCoreProvidersInfoTest.java b/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/AbstractSurefireMojoJunitCoreProvidersInfoTest.java index 190d8b3eb0..34da1018f5 100644 --- a/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/AbstractSurefireMojoJunitCoreProvidersInfoTest.java +++ b/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/AbstractSurefireMojoJunitCoreProvidersInfoTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.surefire; import java.util.Arrays; import java.util.Collection; @@ -36,9 +35,8 @@ /** * Testing JUnitCoreProviderInfo applicable behavior. */ -@RunWith( Parameterized.class ) -public class AbstractSurefireMojoJunitCoreProvidersInfoTest -{ +@RunWith(Parameterized.class) +public class AbstractSurefireMojoJunitCoreProvidersInfoTest { private final Artifact junitArtifact; private final Artifact junitDepArtifact; private final boolean isParallel; @@ -46,12 +44,9 @@ public class AbstractSurefireMojoJunitCoreProvidersInfoTest private final boolean isApplicable; - - @Parameterized.Parameters( - name = "{index}: junit={0}, junitDep={1}, parallel={2}, groups={3} then isApplicable={4}" ) - public static Collection data() - { - return Arrays.asList( new Object[][] { + @Parameterized.Parameters(name = "{index}: junit={0}, junitDep={1}, parallel={2}, groups={3} then isApplicable={4}") + public static Collection data() { + return Arrays.asList(new Object[][] { // junit and junitDep are null {null, null, false, false, false}, {null, null, true, false, false}, @@ -83,35 +78,31 @@ public static Collection data() // with groups {null, "4.5", false, true, false}, {null, "4.7", false, true, true} - } ); + }); } - public AbstractSurefireMojoJunitCoreProvidersInfoTest( String junitVersion, String junitDepVersion, - boolean isParallel, boolean hasGroups, - boolean isApplicable ) - { - this.junitArtifact = junitVersion != null ? aArtifact( junitVersion ) : null; - this.junitDepArtifact = junitDepVersion != null ? aArtifact( junitDepVersion ) : null; + public AbstractSurefireMojoJunitCoreProvidersInfoTest( + String junitVersion, String junitDepVersion, boolean isParallel, boolean hasGroups, boolean isApplicable) { + this.junitArtifact = junitVersion != null ? aArtifact(junitVersion) : null; + this.junitDepArtifact = junitDepVersion != null ? aArtifact(junitDepVersion) : null; this.isParallel = isParallel; this.hasGroups = hasGroups; this.isApplicable = isApplicable; } - private Artifact aArtifact( String version ) - { - return new DefaultArtifact( "test", "test", version, "test", "jar", "", null ); + private Artifact aArtifact(String version) { + return new DefaultArtifact("test", "test", version, "test", "jar", "", null); } @Test - public void test() - { - AbstractSurefireMojo mojo = spy( AbstractSurefireMojo.class ); + public void test() { + AbstractSurefireMojo mojo = spy(AbstractSurefireMojo.class); - when( mojo.isAnyConcurrencySelected() ).thenReturn( isParallel ); - when( mojo.isAnyGroupsSelected() ).thenReturn( hasGroups ); + when(mojo.isAnyConcurrencySelected()).thenReturn(isParallel); + when(mojo.isAnyGroupsSelected()).thenReturn(hasGroups); - ProviderInfo providerInfo = mojo.new JUnitCoreProviderInfo( junitArtifact, junitDepArtifact ); + ProviderInfo providerInfo = mojo.new JUnitCoreProviderInfo(junitArtifact, junitDepArtifact); - assertThat( providerInfo.isApplicable() ).isEqualTo( isApplicable ); + assertThat(providerInfo.isApplicable()).isEqualTo(isApplicable); } } diff --git a/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/AbstractSurefireMojoProvidersInfoTest.java b/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/AbstractSurefireMojoProvidersInfoTest.java index 1429428509..cf6d0cd0f2 100644 --- a/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/AbstractSurefireMojoProvidersInfoTest.java +++ b/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/AbstractSurefireMojoProvidersInfoTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.surefire; import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.DefaultArtifact; @@ -34,152 +33,132 @@ /** * Testing providerInfo applicable behavior. */ -@RunWith( MockitoJUnitRunner.class ) -public class AbstractSurefireMojoProvidersInfoTest -{ +@RunWith(MockitoJUnitRunner.class) +public class AbstractSurefireMojoProvidersInfoTest { @Spy private AbstractSurefireMojo mojo; @Test - public void defaultProviderAreAlwaysAvailable() - { + public void defaultProviderAreAlwaysAvailable() { ProviderInfo providerInfo = mojo.new JUnit3ProviderInfo(); - assertThat( providerInfo.isApplicable() ).isTrue(); + assertThat(providerInfo.isApplicable()).isTrue(); } @Test - public void dynamicProviderAreAlwaysApplicable() - { - ProviderInfo providerInfo = mojo.new DynamicProviderInfo( "test" ); - assertThat( providerInfo.isApplicable() ).isTrue(); + public void dynamicProviderAreAlwaysApplicable() { + ProviderInfo providerInfo = mojo.new DynamicProviderInfo("test"); + assertThat(providerInfo.isApplicable()).isTrue(); } @Test - public void testNgProviderApplicable() - { - Artifact testNg = mock( Artifact.class ); - ProviderInfo providerInfo = mojo.new TestNgProviderInfo( testNg ); + public void testNgProviderApplicable() { + Artifact testNg = mock(Artifact.class); + ProviderInfo providerInfo = mojo.new TestNgProviderInfo(testNg); - assertThat( providerInfo.isApplicable() ).isTrue(); + assertThat(providerInfo.isApplicable()).isTrue(); // no interaction with artifact only reference are checked - verifyNoMoreInteractions( testNg ); + verifyNoMoreInteractions(testNg); } @Test - public void testNgProviderNotApplicable() - { - ProviderInfo providerInfo = mojo.new TestNgProviderInfo( null ); - assertThat( providerInfo.isApplicable() ).isFalse(); + public void testNgProviderNotApplicable() { + ProviderInfo providerInfo = mojo.new TestNgProviderInfo(null); + assertThat(providerInfo.isApplicable()).isFalse(); } - //surefire-junit-platform + // surefire-junit-platform @Test - public void jUnitPlatformProviderApplicable() - { - Artifact junitPlatform = mock( Artifact.class ); - ProviderInfo providerInfo = mojo.new JUnitPlatformProviderInfo( null, junitPlatform, aTestClassPath() ); + public void jUnitPlatformProviderApplicable() { + Artifact junitPlatform = mock(Artifact.class); + ProviderInfo providerInfo = mojo.new JUnitPlatformProviderInfo(null, junitPlatform, aTestClassPath()); - assertThat( providerInfo.isApplicable() ).isTrue(); + assertThat(providerInfo.isApplicable()).isTrue(); // no interaction with artifact only reference are checked - verifyNoMoreInteractions( junitPlatform ); + verifyNoMoreInteractions(junitPlatform); } @Test - public void jUnitPlatformProviderNotApplicable() - { - ProviderInfo providerInfo = mojo.new JUnitPlatformProviderInfo( null, null, aTestClassPath() ); - assertThat( providerInfo.isApplicable() ).isFalse(); + public void jUnitPlatformProviderNotApplicable() { + ProviderInfo providerInfo = mojo.new JUnitPlatformProviderInfo(null, null, aTestClassPath()); + assertThat(providerInfo.isApplicable()).isFalse(); } @Test - public void jUnitPlatformProviderNotApplicableForPlatformRunner() - { + public void jUnitPlatformProviderNotApplicableForPlatformRunner() { // not applicable if junit-platform-runner is on classpath - Artifact junitPlatformRunnerArtifact = mock( Artifact.class ); - ProviderInfo providerInfo = mojo.new JUnitPlatformProviderInfo( - junitPlatformRunnerArtifact, null, aTestClassPath() ); - assertThat( providerInfo.isApplicable() ).isFalse(); + Artifact junitPlatformRunnerArtifact = mock(Artifact.class); + ProviderInfo providerInfo = + mojo.new JUnitPlatformProviderInfo(junitPlatformRunnerArtifact, null, aTestClassPath()); + assertThat(providerInfo.isApplicable()).isFalse(); // no interaction with artifact only reference are checked - verifyNoMoreInteractions( junitPlatformRunnerArtifact ); + verifyNoMoreInteractions(junitPlatformRunnerArtifact); } // surefire-junit4 @Test - public void jUnit4ProviderNullArtifacts() - { - ProviderInfo providerInfo = mojo.new JUnit4ProviderInfo( null, null ); - assertThat( providerInfo.isApplicable() ).isFalse(); + public void jUnit4ProviderNullArtifacts() { + ProviderInfo providerInfo = mojo.new JUnit4ProviderInfo(null, null); + assertThat(providerInfo.isApplicable()).isFalse(); } @Test - public void jUnit4ProviderOnlyJunitDepArtifact() - { - Artifact junitDep = mock( Artifact.class ); - ProviderInfo providerInfo = mojo.new JUnit4ProviderInfo( null, junitDep ); + public void jUnit4ProviderOnlyJunitDepArtifact() { + Artifact junitDep = mock(Artifact.class); + ProviderInfo providerInfo = mojo.new JUnit4ProviderInfo(null, junitDep); - assertThat( providerInfo.isApplicable() ).isTrue(); + assertThat(providerInfo.isApplicable()).isTrue(); // no interaction with artifact only reference are checked - verifyNoMoreInteractions( junitDep ); + verifyNoMoreInteractions(junitDep); } - @Test - public void jUnit4ProviderJunit3WithJDepArtifact() - { - Artifact junit = aArtifact( "3.8.1" ); - Artifact junitDep = mock( Artifact.class ); + public void jUnit4ProviderJunit3WithJDepArtifact() { + Artifact junit = aArtifact("3.8.1"); + Artifact junitDep = mock(Artifact.class); - ProviderInfo providerInfo = mojo.new JUnit4ProviderInfo( junit, junitDep ); + ProviderInfo providerInfo = mojo.new JUnit4ProviderInfo(junit, junitDep); // ??? only existing for junitDep in any version is checked - assertThat( providerInfo.isApplicable() ).isTrue(); + assertThat(providerInfo.isApplicable()).isTrue(); // no interaction with artifact only reference are checked - verifyNoMoreInteractions( junitDep ); + verifyNoMoreInteractions(junitDep); } @Test - public void jUnit4ProviderJunit3AsDependencyArtifact() - { - Artifact junit = aArtifact( "3.8.1" ); - ProviderInfo providerInfo = mojo.new JUnit4ProviderInfo( junit, null ); - assertThat( providerInfo.isApplicable() ).isFalse(); + public void jUnit4ProviderJunit3AsDependencyArtifact() { + Artifact junit = aArtifact("3.8.1"); + ProviderInfo providerInfo = mojo.new JUnit4ProviderInfo(junit, null); + assertThat(providerInfo.isApplicable()).isFalse(); } @Test - public void jUnit4ProviderJunit45AsDependencyArtifact() - { - Artifact junit = aArtifact( "4.5" ); - ProviderInfo providerInfo = mojo.new JUnit4ProviderInfo( junit, null ); - assertThat( providerInfo.isApplicable() ).isTrue(); + public void jUnit4ProviderJunit45AsDependencyArtifact() { + Artifact junit = aArtifact("4.5"); + ProviderInfo providerInfo = mojo.new JUnit4ProviderInfo(junit, null); + assertThat(providerInfo.isApplicable()).isTrue(); } @Test - public void jUnit4ProviderJunit47AsDependencyArtifact() - { - Artifact junit = aArtifact( "4.7" ); - ProviderInfo providerInfo = mojo.new JUnit4ProviderInfo( junit, null ); + public void jUnit4ProviderJunit47AsDependencyArtifact() { + Artifact junit = aArtifact("4.7"); + ProviderInfo providerInfo = mojo.new JUnit4ProviderInfo(junit, null); // ??? it is ok for 4.7 ??? - assertThat( providerInfo.isApplicable() ).isTrue(); + assertThat(providerInfo.isApplicable()).isTrue(); } - - private TestClassPath aTestClassPath() - { - return new TestClassPath( null, null, null, null ); + private TestClassPath aTestClassPath() { + return new TestClassPath(null, null, null, null); } - private Artifact aArtifact( String version ) - { - return new DefaultArtifact( "test", "test", version, "test", "jar", "", null ); + private Artifact aArtifact(String version) { + return new DefaultArtifact("test", "test", version, "test", "jar", "", null); } - - } diff --git a/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/AbstractSurefireMojoTest.java b/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/AbstractSurefireMojoTest.java index 2ee2c94b05..76e3729547 100644 --- a/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/AbstractSurefireMojoTest.java +++ b/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/AbstractSurefireMojoTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.surefire; import java.io.File; import java.io.IOException; @@ -120,11 +119,10 @@ /** * Test for {@link AbstractSurefireMojo}. */ -@RunWith( PowerMockRunner.class ) -@PrepareForTest( AbstractSurefireMojo.class ) -@PowerMockIgnore( {"org.jacoco.agent.rt.*", "com.vladium.emma.rt.*"} ) -public class AbstractSurefireMojoTest -{ +@RunWith(PowerMockRunner.class) +@PrepareForTest(AbstractSurefireMojo.class) +@PowerMockIgnore({"org.jacoco.agent.rt.*", "com.vladium.emma.rt.*"}) +public class AbstractSurefireMojoTest { @Rule public final ExpectedException e = ExpectedException.none(); @@ -137,1860 +135,2446 @@ public class AbstractSurefireMojoTest private final Mojo mojo = new Mojo(); @Before - public void setupMojo() - { + public void setupMojo() { Artifact mojoArtifact = mojo.getMojoArtifact(); - mojo.setPluginArtifactMap( new LinkedHashMap() ); - mojo.getPluginArtifactMap().put( mojoArtifact.getGroupId() + ":" + mojoArtifact.getArtifactId(), mojoArtifact ); - Artifact forkedBooter = new DefaultArtifact( "org.apache.maven.surefire", "surefire-booter", - mojoArtifact.getVersion(), null, "jar", null, mock( ArtifactHandler.class ) ); - mojo.getPluginArtifactMap().put( "org.apache.maven.surefire:surefire-booter", forkedBooter ); + mojo.setPluginArtifactMap(new LinkedHashMap()); + mojo.getPluginArtifactMap().put(mojoArtifact.getGroupId() + ":" + mojoArtifact.getArtifactId(), mojoArtifact); + Artifact forkedBooter = new DefaultArtifact( + "org.apache.maven.surefire", + "surefire-booter", + mojoArtifact.getVersion(), + null, + "jar", + null, + mock(ArtifactHandler.class)); + mojo.getPluginArtifactMap().put("org.apache.maven.surefire:surefire-booter", forkedBooter); - mojo.setProjectArtifactMap( new LinkedHashMap() ); + mojo.setProjectArtifactMap(new LinkedHashMap()); - MavenSession session = mock( MavenSession.class ); - mojo.setSession( session ); + MavenSession session = mock(MavenSession.class); + mojo.setSession(session); - PluginDescriptor pluginDescriptor = mock( PluginDescriptor.class ); + PluginDescriptor pluginDescriptor = mock(PluginDescriptor.class); Plugin plugin = new Plugin(); - plugin.setGroupId( mojoArtifact.getGroupId() ); - plugin.setArtifactId( mojoArtifact.getArtifactId() ); - plugin.setVersion( mojoArtifact.getVersion() ); - when( pluginDescriptor.getPlugin() ).thenReturn( plugin ); - mojo.setPluginDescriptor( pluginDescriptor ); - mojo.setResolutionErrorHandler( new DefaultResolutionErrorHandler() ); + plugin.setGroupId(mojoArtifact.getGroupId()); + plugin.setArtifactId(mojoArtifact.getArtifactId()); + plugin.setVersion(mojoArtifact.getVersion()); + when(pluginDescriptor.getPlugin()).thenReturn(plugin); + mojo.setPluginDescriptor(pluginDescriptor); + mojo.setResolutionErrorHandler(new DefaultResolutionErrorHandler()); } @Test - public void noModuleDescriptorFile() throws Exception - { - AbstractSurefireMojo mojo = spy( new Mojo() ); - mojo.setMainBuildPath( tempFolder.newFolder() ); + public void noModuleDescriptorFile() throws Exception { + AbstractSurefireMojo mojo = spy(new Mojo()); + mojo.setMainBuildPath(tempFolder.newFolder()); File testClassesDir = tempFolder.newFolder(); - mojo.setTestClassesDirectory( testClassesDir ); - File jdkHome = new File( System.getProperty( "java.home" ) ); - ResolvePathResultWrapper wrapper = invokeMethod( mojo, "findModuleDescriptor", jdkHome ); + mojo.setTestClassesDirectory(testClassesDir); + File jdkHome = new File(System.getProperty("java.home")); + ResolvePathResultWrapper wrapper = invokeMethod(mojo, "findModuleDescriptor", jdkHome); - assertThat( wrapper ) - .isNotNull(); + assertThat(wrapper).isNotNull(); - assertThat( wrapper.getResolvePathResult() ) - .isNull(); + assertThat(wrapper.getResolvePathResult()).isNull(); - assertThat( (boolean) invokeMethod( mojo, "existsModuleDescriptor", wrapper ) ) - .isEqualTo( false ); + assertThat((boolean) invokeMethod(mojo, "existsModuleDescriptor", wrapper)) + .isEqualTo(false); - when( mojo.useModulePath() ).thenReturn( true ); + when(mojo.useModulePath()).thenReturn(true); - File jvmExecutable = new File( jdkHome, IS_OS_WINDOWS ? "bin\\java.exe" : "bin/java" ); - JdkAttributes jdkAttributes = new JdkAttributes( jvmExecutable, jdkHome, true ); - Platform platform = new Platform().withJdkExecAttributesForTests( jdkAttributes ); - assertThat( (boolean) invokeMethod( mojo, "canExecuteProviderWithModularPath", platform, wrapper ) ) - .isEqualTo( false ); + File jvmExecutable = new File(jdkHome, IS_OS_WINDOWS ? "bin\\java.exe" : "bin/java"); + JdkAttributes jdkAttributes = new JdkAttributes(jvmExecutable, jdkHome, true); + Platform platform = new Platform().withJdkExecAttributesForTests(jdkAttributes); + assertThat((boolean) invokeMethod(mojo, "canExecuteProviderWithModularPath", platform, wrapper)) + .isEqualTo(false); } @Test - public void correctModuleDescriptor() throws Exception - { - AbstractSurefireMojo mojo = spy( new Mojo() ); - LocationManager locationManager = mock( LocationManager.class ); - ResolvePathResult result = mock( ResolvePathResult.class ); - when( result.getModuleNameSource() ).thenReturn( MODULEDESCRIPTOR ); - JavaModuleDescriptor descriptor = mock( JavaModuleDescriptor.class ); - when( result.getModuleDescriptor() ).thenReturn( descriptor ); - when( locationManager.resolvePath( any( ResolvePathRequest.class ) ) ).thenReturn( result ); - doReturn( locationManager ) - .when( mojo, "getLocationManager" ); + public void correctModuleDescriptor() throws Exception { + AbstractSurefireMojo mojo = spy(new Mojo()); + LocationManager locationManager = mock(LocationManager.class); + ResolvePathResult result = mock(ResolvePathResult.class); + when(result.getModuleNameSource()).thenReturn(MODULEDESCRIPTOR); + JavaModuleDescriptor descriptor = mock(JavaModuleDescriptor.class); + when(result.getModuleDescriptor()).thenReturn(descriptor); + when(locationManager.resolvePath(any(ResolvePathRequest.class))).thenReturn(result); + doReturn(locationManager).when(mojo, "getLocationManager"); File classesDir = tempFolder.newFolder(); - mojo.setMainBuildPath( classesDir ); + mojo.setMainBuildPath(classesDir); File testClassesDir = tempFolder.newFolder(); - mojo.setTestClassesDirectory( testClassesDir ); - File descriptorFile = new File( classesDir, "module-info.class" ); - assertThat( descriptorFile.createNewFile() ).isTrue(); - File jdkHome = new File( System.getProperty( "java.home" ) ); - ResolvePathResultWrapper wrapper = invokeMethod( mojo, "findModuleDescriptor", jdkHome ); + mojo.setTestClassesDirectory(testClassesDir); + File descriptorFile = new File(classesDir, "module-info.class"); + assertThat(descriptorFile.createNewFile()).isTrue(); + File jdkHome = new File(System.getProperty("java.home")); + ResolvePathResultWrapper wrapper = invokeMethod(mojo, "findModuleDescriptor", jdkHome); - assertThat( wrapper ) - .isNotNull(); + assertThat(wrapper).isNotNull(); - assertThat( wrapper.getResolvePathResult() ) - .isSameAs( result ); + assertThat(wrapper.getResolvePathResult()).isSameAs(result); - assertThat( wrapper.getResolvePathResult().getModuleNameSource() ) - .isSameAs( MODULEDESCRIPTOR ); + assertThat(wrapper.getResolvePathResult().getModuleNameSource()).isSameAs(MODULEDESCRIPTOR); - assertThat( wrapper.getResolvePathResult().getModuleDescriptor() ) - .isSameAs( descriptor ); + assertThat(wrapper.getResolvePathResult().getModuleDescriptor()).isSameAs(descriptor); - assertThat( (boolean) invokeMethod( mojo, "existsModuleDescriptor", wrapper ) ) - .isEqualTo( true ); + assertThat((boolean) invokeMethod(mojo, "existsModuleDescriptor", wrapper)) + .isEqualTo(true); - when( mojo.useModulePath() ).thenReturn( true ); + when(mojo.useModulePath()).thenReturn(true); - File jvmExecutable = new File( jdkHome, IS_OS_WINDOWS ? "bin\\java.exe" : "bin/java" ); - JdkAttributes jdkAttributes = new JdkAttributes( jvmExecutable, jdkHome, true ); - Platform platform = new Platform().withJdkExecAttributesForTests( jdkAttributes ); - assertThat( (boolean) invokeMethod( mojo, "canExecuteProviderWithModularPath", platform, wrapper ) ) - .isEqualTo( true ); + File jvmExecutable = new File(jdkHome, IS_OS_WINDOWS ? "bin\\java.exe" : "bin/java"); + JdkAttributes jdkAttributes = new JdkAttributes(jvmExecutable, jdkHome, true); + Platform platform = new Platform().withJdkExecAttributesForTests(jdkAttributes); + assertThat((boolean) invokeMethod(mojo, "canExecuteProviderWithModularPath", platform, wrapper)) + .isEqualTo(true); - jdkAttributes = new JdkAttributes( jvmExecutable, jdkHome, false ); - platform = new Platform().withJdkExecAttributesForTests( jdkAttributes ); - assertThat( (boolean) invokeMethod( mojo, "canExecuteProviderWithModularPath", platform, wrapper ) ) - .isEqualTo( false ); + jdkAttributes = new JdkAttributes(jvmExecutable, jdkHome, false); + platform = new Platform().withJdkExecAttributesForTests(jdkAttributes); + assertThat((boolean) invokeMethod(mojo, "canExecuteProviderWithModularPath", platform, wrapper)) + .isEqualTo(false); - when( mojo.useModulePath() ).thenReturn( false ); + when(mojo.useModulePath()).thenReturn(false); - jdkAttributes = new JdkAttributes( jvmExecutable, jdkHome, true ); - platform = new Platform().withJdkExecAttributesForTests( jdkAttributes ); - assertThat( (boolean) invokeMethod( mojo, "canExecuteProviderWithModularPath", platform, wrapper ) ) - .isEqualTo( false ); + jdkAttributes = new JdkAttributes(jvmExecutable, jdkHome, true); + platform = new Platform().withJdkExecAttributesForTests(jdkAttributes); + assertThat((boolean) invokeMethod(mojo, "canExecuteProviderWithModularPath", platform, wrapper)) + .isEqualTo(false); } @Test - @SuppressWarnings( "checkstyle:magicnumber" ) - public void corruptedModuleDescriptor() throws Exception - { - if ( !JAVA_RECENT.atLeast( JAVA_9 ) ) - { + @SuppressWarnings("checkstyle:magicnumber") + public void corruptedModuleDescriptor() throws Exception { + if (!JAVA_RECENT.atLeast(JAVA_9)) { return; } - AbstractSurefireMojo mojo = spy( new Mojo() ); - doReturn( new LocationManager() ) - .when( mojo, "getLocationManager" ); + AbstractSurefireMojo mojo = spy(new Mojo()); + doReturn(new LocationManager()).when(mojo, "getLocationManager"); File classesDir = tempFolder.newFolder(); - mojo.setMainBuildPath( classesDir ); + mojo.setMainBuildPath(classesDir); File testClassesDir = tempFolder.newFolder(); - mojo.setTestClassesDirectory( testClassesDir ); + mojo.setTestClassesDirectory(testClassesDir); - File descriptorFile = new File( classesDir, "module-info.class" ); - assertThat( descriptorFile.createNewFile() ).isTrue(); - write( descriptorFile.toPath(), new byte[] {(byte) 0xCA, (byte) 0xFE, (byte) 0xBA, (byte) 0xBE} ); + File descriptorFile = new File(classesDir, "module-info.class"); + assertThat(descriptorFile.createNewFile()).isTrue(); + write(descriptorFile.toPath(), new byte[] {(byte) 0xCA, (byte) 0xFE, (byte) 0xBA, (byte) 0xBE}); - File jdkHome = new File( System.getProperty( "java.home" ) ); - ResolvePathResultWrapper wrapper = invokeMethod( mojo, "findModuleDescriptor", jdkHome ); + File jdkHome = new File(System.getProperty("java.home")); + ResolvePathResultWrapper wrapper = invokeMethod(mojo, "findModuleDescriptor", jdkHome); - assertThat( wrapper ) - .isNotNull(); + assertThat(wrapper).isNotNull(); - assertThat( wrapper.getResolvePathResult() ) - .isNull(); + assertThat(wrapper.getResolvePathResult()).isNull(); - assertThat( (boolean) invokeMethod( mojo, "existsModuleDescriptor", wrapper ) ) - .isEqualTo( false ); + assertThat((boolean) invokeMethod(mojo, "existsModuleDescriptor", wrapper)) + .isEqualTo(false); } @Test - public void shouldShowArray() throws Exception - { - Logger logger = mock( Logger.class ); - when( logger.isDebugEnabled() ).thenReturn( true ); - doNothing().when( logger ).debug( anyString() ); + public void shouldShowArray() throws Exception { + Logger logger = mock(Logger.class); + when(logger.isDebugEnabled()).thenReturn(true); + doNothing().when(logger).debug(anyString()); - AbstractSurefireMojo mojo = spy( this.mojo ); + AbstractSurefireMojo mojo = spy(this.mojo); - when( mojo.getConsoleLogger() ).thenReturn( new PluginConsoleLogger( logger ) ); + when(mojo.getConsoleLogger()).thenReturn(new PluginConsoleLogger(logger)); Object[] array = {"ABC", "XYZ"}; - invokeMethod( mojo, "showArray", array, "prefix" ); + invokeMethod(mojo, "showArray", array, "prefix"); - ArgumentCaptor argument = ArgumentCaptor.forClass( String.class ); - verify( logger, times( 2 ) ).debug( argument.capture() ); - assertThat( argument.getAllValues() ) - .containsExactly( "Setting prefix [ABC]", "Setting prefix [XYZ]" ); + ArgumentCaptor argument = ArgumentCaptor.forClass(String.class); + verify(logger, times(2)).debug(argument.capture()); + assertThat(argument.getAllValues()).containsExactly("Setting prefix [ABC]", "Setting prefix [XYZ]"); } @Test - public void shouldShowMap() throws Exception - { - Logger logger = mock( Logger.class ); - when( logger.isDebugEnabled() ).thenReturn( true ); - doNothing().when( logger ).debug( anyString() ); + public void shouldShowMap() throws Exception { + Logger logger = mock(Logger.class); + when(logger.isDebugEnabled()).thenReturn(true); + doNothing().when(logger).debug(anyString()); - AbstractSurefireMojo mojo = spy( this.mojo ); + AbstractSurefireMojo mojo = spy(this.mojo); - when( mojo.getConsoleLogger() ).thenReturn( new PluginConsoleLogger( logger ) ); + when(mojo.getConsoleLogger()).thenReturn(new PluginConsoleLogger(logger)); Map map = new LinkedHashMap<>(); - map.put( "ABC", "123" ); - map.put( "XYZ", "987" ); - invokeMethod( mojo, "showMap", map, "prefix" ); - - ArgumentCaptor argument = ArgumentCaptor.forClass( String.class ); - verify( logger, times( 2 ) ).debug( argument.capture() ); - assertThat( argument.getAllValues() ) - .containsExactly( "Setting prefix [ABC]=[123]", "Setting prefix [XYZ]=[987]" ); + map.put("ABC", "123"); + map.put("XYZ", "987"); + invokeMethod(mojo, "showMap", map, "prefix"); + + ArgumentCaptor argument = ArgumentCaptor.forClass(String.class); + verify(logger, times(2)).debug(argument.capture()); + assertThat(argument.getAllValues()).containsExactly("Setting prefix [ABC]=[123]", "Setting prefix [XYZ]=[987]"); } @Test - public void shouldRetainInPluginArtifacts() throws Exception - { - Artifact provider = new DefaultArtifact( "g", "a", createFromVersionSpec( "1" ), "compile", "jar", "", null ); - Artifact common = new DefaultArtifact( "g", "c", createFromVersionSpec( "1" ), "compile", "jar", "", null ); - Artifact api = new DefaultArtifact( "g", "a", createFromVersionSpec( "1" ), "compile", "jar", "", null ); + public void shouldRetainInPluginArtifacts() throws Exception { + Artifact provider = new DefaultArtifact("g", "a", createFromVersionSpec("1"), "compile", "jar", "", null); + Artifact common = new DefaultArtifact("g", "c", createFromVersionSpec("1"), "compile", "jar", "", null); + Artifact api = new DefaultArtifact("g", "a", createFromVersionSpec("1"), "compile", "jar", "", null); - Set providerArtifacts = singleton( provider ); + Set providerArtifacts = singleton(provider); Artifact[] inPluginArtifacts = {common, api}; - Set inPluginClasspath = invokeMethod( AbstractSurefireMojo.class, - "retainInProcArtifactsUnique", providerArtifacts, inPluginArtifacts ); + Set inPluginClasspath = invokeMethod( + AbstractSurefireMojo.class, "retainInProcArtifactsUnique", providerArtifacts, inPluginArtifacts); - assertThat( inPluginClasspath ) - .containsOnly( common ); + assertThat(inPluginClasspath).containsOnly(common); } @Test - public void shouldRetainInProcArtifactsUnique() throws Exception - { - Artifact provider = new DefaultArtifact( "g", "p", createFromVersionSpec( "1" ), "compile", "jar", "", null ); - Artifact common = new DefaultArtifact( "g", "c", createFromVersionSpec( "1" ), "compile", "jar", "", null ); - Artifact api = new DefaultArtifact( "g", "a", createFromVersionSpec( "1" ), "compile", "jar", "", null ); + public void shouldRetainInProcArtifactsUnique() throws Exception { + Artifact provider = new DefaultArtifact("g", "p", createFromVersionSpec("1"), "compile", "jar", "", null); + Artifact common = new DefaultArtifact("g", "c", createFromVersionSpec("1"), "compile", "jar", "", null); + Artifact api = new DefaultArtifact("g", "a", createFromVersionSpec("1"), "compile", "jar", "", null); - Set providerArtifacts = singleton( provider ); + Set providerArtifacts = singleton(provider); Artifact[] inPluginArtifacts = {common, api}; - Set inPluginClasspath = invokeMethod( AbstractSurefireMojo.class, - "retainInProcArtifactsUnique", providerArtifacts, inPluginArtifacts ); + Set inPluginClasspath = invokeMethod( + AbstractSurefireMojo.class, "retainInProcArtifactsUnique", providerArtifacts, inPluginArtifacts); - assertThat( inPluginClasspath ) - .containsOnly( common, api ); + assertThat(inPluginClasspath).containsOnly(common, api); } @Test - public void shouldCreateInProcClasspath() throws Exception - { - Artifact provider = new DefaultArtifact( "g", "p", createFromVersionSpec( "1" ), "compile", "jar", "", null ); - provider.setFile( mockFile( "provider.jar" ) ); + public void shouldCreateInProcClasspath() throws Exception { + Artifact provider = new DefaultArtifact("g", "p", createFromVersionSpec("1"), "compile", "jar", "", null); + provider.setFile(mockFile("provider.jar")); - Artifact common = new DefaultArtifact( "g", "c", createFromVersionSpec( "1" ), "compile", "jar", "", null ); - common.setFile( mockFile( "maven-surefire-common.jar" ) ); + Artifact common = new DefaultArtifact("g", "c", createFromVersionSpec("1"), "compile", "jar", "", null); + common.setFile(mockFile("maven-surefire-common.jar")); - Artifact api = new DefaultArtifact( "g", "a", createFromVersionSpec( "1" ), "compile", "jar", "", null ); - api.setFile( mockFile( "surefire-api.jar" ) ); + Artifact api = new DefaultArtifact("g", "a", createFromVersionSpec("1"), "compile", "jar", "", null); + api.setFile(mockFile("surefire-api.jar")); Set newArtifacts = new LinkedHashSet<>(); - newArtifacts.add( common ); - newArtifacts.add( api ); + newArtifacts.add(common); + newArtifacts.add(api); - Classpath providerClasspath = new Classpath( singleton( provider.getFile().getAbsolutePath() ) ); + Classpath providerClasspath = new Classpath(singleton(provider.getFile().getAbsolutePath())); - Classpath inPluginClasspath = invokeMethod( AbstractSurefireMojo.class, - "createInProcClasspath", providerClasspath, newArtifacts ); + Classpath inPluginClasspath = + invokeMethod(AbstractSurefireMojo.class, "createInProcClasspath", providerClasspath, newArtifacts); - Classpath expectedClasspath = - new Classpath( asList( provider.getFile().getAbsolutePath(), + Classpath expectedClasspath = new Classpath(asList( + provider.getFile().getAbsolutePath(), common.getFile().getAbsolutePath(), - api.getFile().getAbsolutePath() ) ); - - assertThat( (Object) inPluginClasspath ) - .isEqualTo( expectedClasspath ); + api.getFile().getAbsolutePath())); + assertThat((Object) inPluginClasspath).isEqualTo(expectedClasspath); } @Test - public void shouldGenerateTestClasspath() throws Exception - { - AbstractSurefireMojo mojo = spy( this.mojo ); + public void shouldGenerateTestClasspath() throws Exception { + AbstractSurefireMojo mojo = spy(this.mojo); - when( mojo.getMainBuildPath() ).thenReturn( new File( "target" + separatorChar + "classes" ) ); - when( mojo.getTestClassesDirectory() ).thenReturn( new File( "target" + separatorChar + "test-classes" ) ); - when( mojo.getClasspathDependencyScopeExclude() ).thenReturn( "runtime" ); - when( mojo.getClasspathDependencyExcludes() ).thenReturn( new String[] {"g3:a3"} ); - doReturn( mock( Artifact.class ) ).when( mojo, "getTestNgArtifact" ); + when(mojo.getMainBuildPath()).thenReturn(new File("target" + separatorChar + "classes")); + when(mojo.getTestClassesDirectory()).thenReturn(new File("target" + separatorChar + "test-classes")); + when(mojo.getClasspathDependencyScopeExclude()).thenReturn("runtime"); + when(mojo.getClasspathDependencyExcludes()).thenReturn(new String[] {"g3:a3"}); + doReturn(mock(Artifact.class)).when(mojo, "getTestNgArtifact"); Set artifacts = new HashSet<>(); - Artifact a1 = mock( Artifact.class ); - when( a1.getGroupId() ).thenReturn( "g1" ); - when( a1.getArtifactId() ).thenReturn( "a1" ); - when( a1.getVersion() ).thenReturn( "1" ); - when( a1.getScope() ).thenReturn( "runtime" ); - when( a1.getDependencyConflictId() ).thenReturn( "g1:a1:jar" ); - when( a1.getId() ).thenReturn( "g1:a1:jar:1" ); - artifacts.add( a1 ); - - ArtifactHandler artifactHandler = mock( ArtifactHandler.class ); - when( artifactHandler.isAddedToClasspath() ).thenReturn( true ); - - Artifact a2 = mock( Artifact.class ); - when( a2.getGroupId() ).thenReturn( "g2" ); - when( a2.getArtifactId() ).thenReturn( "a2" ); - when( a2.getVersion() ).thenReturn( "2" ); - when( a2.getScope() ).thenReturn( "test" ); - when( a2.getDependencyConflictId() ).thenReturn( "g2:a2:jar" ); - when( a2.getId() ).thenReturn( "g2:a2:jar:2" ); - when( a2.getFile() ).thenReturn( new File( "a2-2.jar" ) ); - when( a2.getArtifactHandler() ).thenReturn( artifactHandler ); - artifacts.add( a2 ); - - Artifact a3 = mock( Artifact.class ); - when( a3.getGroupId() ).thenReturn( "g3" ); - when( a3.getArtifactId() ).thenReturn( "a3" ); - when( a3.getVersion() ).thenReturn( "3" ); - when( a3.getScope() ).thenReturn( "test" ); - when( a3.getDependencyConflictId() ).thenReturn( "g3:a3:jar" ); - when( a3.getId() ).thenReturn( "g3:a3:jar:3" ); - when( a3.getFile() ).thenReturn( new File( "a3-3.jar" ) ); - when( a3.getArtifactHandler() ).thenReturn( artifactHandler ); - artifacts.add( a3 ); - - MavenProject project = mock( MavenProject.class ); - when( project.getArtifacts() ).thenReturn( artifacts ); - when( mojo.getProject() ).thenReturn( project ); - - TestClassPath cp = invokeMethod( mojo, "generateTestClasspath" ); - - verifyPrivate( mojo, times( 1 ) ).invoke( "generateTestClasspath" ); - verify( mojo, times( 1 ) ).getMainBuildPath(); - verify( mojo, times( 1 ) ).getTestClassesDirectory(); - verify( mojo, times( 3 ) ).getClasspathDependencyScopeExclude(); - verify( mojo, times( 2 ) ).getClasspathDependencyExcludes(); - verify( mojo, times( 1 ) ).getAdditionalClasspathElements(); - - assertThat( cp.toClasspath().getClassPath() ).hasSize( 3 ); - assertThat( cp.toClasspath().getClassPath().get( 0 ) ).endsWith( "test-classes" ); - assertThat( cp.toClasspath().getClassPath().get( 1 ) ).endsWith( "classes" ); - assertThat( cp.toClasspath().getClassPath().get( 2 ) ).endsWith( "a2-2.jar" ); + Artifact a1 = mock(Artifact.class); + when(a1.getGroupId()).thenReturn("g1"); + when(a1.getArtifactId()).thenReturn("a1"); + when(a1.getVersion()).thenReturn("1"); + when(a1.getScope()).thenReturn("runtime"); + when(a1.getDependencyConflictId()).thenReturn("g1:a1:jar"); + when(a1.getId()).thenReturn("g1:a1:jar:1"); + artifacts.add(a1); + + ArtifactHandler artifactHandler = mock(ArtifactHandler.class); + when(artifactHandler.isAddedToClasspath()).thenReturn(true); + + Artifact a2 = mock(Artifact.class); + when(a2.getGroupId()).thenReturn("g2"); + when(a2.getArtifactId()).thenReturn("a2"); + when(a2.getVersion()).thenReturn("2"); + when(a2.getScope()).thenReturn("test"); + when(a2.getDependencyConflictId()).thenReturn("g2:a2:jar"); + when(a2.getId()).thenReturn("g2:a2:jar:2"); + when(a2.getFile()).thenReturn(new File("a2-2.jar")); + when(a2.getArtifactHandler()).thenReturn(artifactHandler); + artifacts.add(a2); + + Artifact a3 = mock(Artifact.class); + when(a3.getGroupId()).thenReturn("g3"); + when(a3.getArtifactId()).thenReturn("a3"); + when(a3.getVersion()).thenReturn("3"); + when(a3.getScope()).thenReturn("test"); + when(a3.getDependencyConflictId()).thenReturn("g3:a3:jar"); + when(a3.getId()).thenReturn("g3:a3:jar:3"); + when(a3.getFile()).thenReturn(new File("a3-3.jar")); + when(a3.getArtifactHandler()).thenReturn(artifactHandler); + artifacts.add(a3); + + MavenProject project = mock(MavenProject.class); + when(project.getArtifacts()).thenReturn(artifacts); + when(mojo.getProject()).thenReturn(project); + + TestClassPath cp = invokeMethod(mojo, "generateTestClasspath"); + + verifyPrivate(mojo, times(1)).invoke("generateTestClasspath"); + verify(mojo, times(1)).getMainBuildPath(); + verify(mojo, times(1)).getTestClassesDirectory(); + verify(mojo, times(3)).getClasspathDependencyScopeExclude(); + verify(mojo, times(2)).getClasspathDependencyExcludes(); + verify(mojo, times(1)).getAdditionalClasspathElements(); + + assertThat(cp.toClasspath().getClassPath()).hasSize(3); + assertThat(cp.toClasspath().getClassPath().get(0)).endsWith("test-classes"); + assertThat(cp.toClasspath().getClassPath().get(1)).endsWith("classes"); + assertThat(cp.toClasspath().getClassPath().get(2)).endsWith("a2-2.jar"); } @Test - @SuppressWarnings( "checkstyle:linelength" ) - public void shouldHaveStartupConfigForNonModularClasspath() - throws Exception - { - AbstractSurefireMojo mojo = spy( this.mojo ); - - Artifact common = new DefaultArtifact( "org.apache.maven.surefire", "maven-surefire-common", - createFromVersion( "1" ), "runtime", "jar", "", handler ); - common.setFile( mockFile( "maven-surefire-common.jar" ) ); - - Artifact ext = new DefaultArtifact( "org.apache.maven.surefire", "surefire-extensions-api", - createFromVersion( "1" ), "runtime", "jar", "", handler ); - ext.setFile( mockFile( "surefire-extensions-api.jar" ) ); - - Artifact api = new DefaultArtifact( "org.apache.maven.surefire", "surefire-api", - createFromVersion( "1" ), "runtime", "jar", "", handler ); - api.setFile( mockFile( "surefire-api.jar" ) ); - - Artifact loggerApi = new DefaultArtifact( "org.apache.maven.surefire", "surefire-logger-api", - createFromVersion( "1" ), "runtime", "jar", "", handler ); - loggerApi.setFile( mockFile( "surefire-logger-api.jar" ) ); - - Artifact spi = new DefaultArtifact( "org.apache.maven.surefire", "surefire-extensions-spi", - createFromVersion( "1" ), "runtime", "jar", "", handler ); - spi.setFile( mockFile( "surefire-extensions-spi.jar" ) ); - - Artifact booter = new DefaultArtifact( "org.apache.maven.surefire", "surefire-booter", - createFromVersion( "1" ), "runtime", "jar", "", handler ); - booter.setFile( mockFile( "surefire-booter.jar" ) ); - - Artifact utils = new DefaultArtifact( "org.apache.maven.surefire", "surefire-shared-utils", - createFromVersion( "1" ), "runtime", "jar", "", handler ); - utils.setFile( mockFile( "surefire-shared-utils.jar" ) ); + @SuppressWarnings("checkstyle:linelength") + public void shouldHaveStartupConfigForNonModularClasspath() throws Exception { + AbstractSurefireMojo mojo = spy(this.mojo); + + Artifact common = new DefaultArtifact( + "org.apache.maven.surefire", + "maven-surefire-common", + createFromVersion("1"), + "runtime", + "jar", + "", + handler); + common.setFile(mockFile("maven-surefire-common.jar")); + + Artifact ext = new DefaultArtifact( + "org.apache.maven.surefire", + "surefire-extensions-api", + createFromVersion("1"), + "runtime", + "jar", + "", + handler); + ext.setFile(mockFile("surefire-extensions-api.jar")); + + Artifact api = new DefaultArtifact( + "org.apache.maven.surefire", "surefire-api", createFromVersion("1"), "runtime", "jar", "", handler); + api.setFile(mockFile("surefire-api.jar")); + + Artifact loggerApi = new DefaultArtifact( + "org.apache.maven.surefire", + "surefire-logger-api", + createFromVersion("1"), + "runtime", + "jar", + "", + handler); + loggerApi.setFile(mockFile("surefire-logger-api.jar")); + + Artifact spi = new DefaultArtifact( + "org.apache.maven.surefire", + "surefire-extensions-spi", + createFromVersion("1"), + "runtime", + "jar", + "", + handler); + spi.setFile(mockFile("surefire-extensions-spi.jar")); + + Artifact booter = new DefaultArtifact( + "org.apache.maven.surefire", "surefire-booter", createFromVersion("1"), "runtime", "jar", "", handler); + booter.setFile(mockFile("surefire-booter.jar")); + + Artifact utils = new DefaultArtifact( + "org.apache.maven.surefire", + "surefire-shared-utils", + createFromVersion("1"), + "runtime", + "jar", + "", + handler); + utils.setFile(mockFile("surefire-shared-utils.jar")); Map providerArtifactsMap = new HashMap<>(); - providerArtifactsMap.put( "org.apache.maven.surefire:maven-surefire-common", common ); - providerArtifactsMap.put( "org.apache.maven.surefire:surefire-extensions-api", ext ); - providerArtifactsMap.put( "org.apache.maven.surefire:surefire-api", api ); - providerArtifactsMap.put( "org.apache.maven.surefire:surefire-logger-api", loggerApi ); - providerArtifactsMap.put( "org.apache.maven.surefire:surefire-extensions-spi", spi ); - providerArtifactsMap.put( "org.apache.maven.surefire:surefire-booter", booter ); - providerArtifactsMap.put( "org.apache.maven.surefire:surefire-shared-utils", utils ); - - when( mojo.getPluginArtifactMap() ) - .thenReturn( providerArtifactsMap ); - - when( handler.isAddedToClasspath() ).thenReturn( true ); - - VersionRange v1 = createFromVersion( "4.12" ); - Artifact junit = new DefaultArtifact( "junit", "junit", v1, "test", "jar", "", handler ); - junit.setFile( mockFile( "junit.jar" ) ); - - VersionRange v2 = createFromVersion( "1.3.0" ); - Artifact hamcrest = new DefaultArtifact( "org.hamcrest", "hamcrest-core", v2, "test", "jar", "", handler ); - hamcrest.setFile( mockFile( "hamcrest.jar" ) ); - - File classesDir = mockFile( "classes" ); - File testClassesDir = mockFile( "test-classes" ); - TestClassPath testClasspath = - new TestClassPath( asList( junit, hamcrest ), classesDir, testClassesDir, null ); - - doReturn( testClasspath ).when( mojo, "generateTestClasspath" ); - doReturn( 1 ).when( mojo, "getEffectiveForkCount" ); - doReturn( true ).when( mojo, "effectiveIsEnableAssertions" ); - when( mojo.isChildDelegation() ).thenReturn( false ); - - ClassLoaderConfiguration classLoaderConfiguration = new ClassLoaderConfiguration( false, true ); - - VersionRange v3 = createFromVersion( "1" ); - Artifact provider = new DefaultArtifact( "x", "surefire-provider", v3, "runtime", "jar", "", handler ); - provider.setFile( mockFile( "surefire-provider.jar" ) ); - Set providerArtifacts = singleton( provider ); - - Logger logger = mock( Logger.class ); - when( logger.isDebugEnabled() ).thenReturn( true ); - doNothing().when( logger ).debug( anyString() ); - when( mojo.getConsoleLogger() ).thenReturn( new PluginConsoleLogger( logger ) ); - - ProviderInfo providerInfo = mock( ProviderInfo.class ); - when( providerInfo.getProviderName() ).thenReturn( "org.asf.Provider" ); - when( providerInfo.getProviderClasspath() ).thenReturn( providerArtifacts ); - - StartupConfiguration conf = invokeMethod( mojo, "newStartupConfigWithClasspath", - classLoaderConfiguration, providerInfo, testClasspath ); - - verify( mojo, times( 1 ) ).effectiveIsEnableAssertions(); - verify( mojo, times( 1 ) ).isChildDelegation(); - ArgumentCaptor argument = ArgumentCaptor.forClass( String.class ); - verify( logger, times( 6 ) ).debug( argument.capture() ); - assertThat( argument.getAllValues() ) - .containsExactly( "test classpath: test-classes classes junit.jar hamcrest.jar", - "provider classpath: surefire-provider.jar", - "test(compact) classpath: test-classes classes junit.jar hamcrest.jar", - "provider(compact) classpath: surefire-provider.jar", - "in-process classpath: surefire-provider.jar maven-surefire-common.jar surefire-booter.jar surefire-extensions-api.jar surefire-api.jar surefire-extensions-spi.jar surefire-logger-api.jar surefire-shared-utils.jar", - "in-process(compact) classpath: surefire-provider.jar maven-surefire-common.jar surefire-booter.jar surefire-extensions-api.jar surefire-api.jar surefire-extensions-spi.jar surefire-logger-api.jar surefire-shared-utils.jar" - ); - - assertThat( conf.getClassLoaderConfiguration() ) - .isSameAs( classLoaderConfiguration ); - - assertThat( (Object) conf.getClasspathConfiguration().getTestClasspath() ) - .isEqualTo( testClasspath.toClasspath() ); + providerArtifactsMap.put("org.apache.maven.surefire:maven-surefire-common", common); + providerArtifactsMap.put("org.apache.maven.surefire:surefire-extensions-api", ext); + providerArtifactsMap.put("org.apache.maven.surefire:surefire-api", api); + providerArtifactsMap.put("org.apache.maven.surefire:surefire-logger-api", loggerApi); + providerArtifactsMap.put("org.apache.maven.surefire:surefire-extensions-spi", spi); + providerArtifactsMap.put("org.apache.maven.surefire:surefire-booter", booter); + providerArtifactsMap.put("org.apache.maven.surefire:surefire-shared-utils", utils); + + when(mojo.getPluginArtifactMap()).thenReturn(providerArtifactsMap); + + when(handler.isAddedToClasspath()).thenReturn(true); + + VersionRange v1 = createFromVersion("4.12"); + Artifact junit = new DefaultArtifact("junit", "junit", v1, "test", "jar", "", handler); + junit.setFile(mockFile("junit.jar")); + + VersionRange v2 = createFromVersion("1.3.0"); + Artifact hamcrest = new DefaultArtifact("org.hamcrest", "hamcrest-core", v2, "test", "jar", "", handler); + hamcrest.setFile(mockFile("hamcrest.jar")); + + File classesDir = mockFile("classes"); + File testClassesDir = mockFile("test-classes"); + TestClassPath testClasspath = new TestClassPath(asList(junit, hamcrest), classesDir, testClassesDir, null); + + doReturn(testClasspath).when(mojo, "generateTestClasspath"); + doReturn(1).when(mojo, "getEffectiveForkCount"); + doReturn(true).when(mojo, "effectiveIsEnableAssertions"); + when(mojo.isChildDelegation()).thenReturn(false); + + ClassLoaderConfiguration classLoaderConfiguration = new ClassLoaderConfiguration(false, true); + + VersionRange v3 = createFromVersion("1"); + Artifact provider = new DefaultArtifact("x", "surefire-provider", v3, "runtime", "jar", "", handler); + provider.setFile(mockFile("surefire-provider.jar")); + Set providerArtifacts = singleton(provider); + + Logger logger = mock(Logger.class); + when(logger.isDebugEnabled()).thenReturn(true); + doNothing().when(logger).debug(anyString()); + when(mojo.getConsoleLogger()).thenReturn(new PluginConsoleLogger(logger)); + + ProviderInfo providerInfo = mock(ProviderInfo.class); + when(providerInfo.getProviderName()).thenReturn("org.asf.Provider"); + when(providerInfo.getProviderClasspath()).thenReturn(providerArtifacts); + + StartupConfiguration conf = invokeMethod( + mojo, "newStartupConfigWithClasspath", classLoaderConfiguration, providerInfo, testClasspath); + + verify(mojo, times(1)).effectiveIsEnableAssertions(); + verify(mojo, times(1)).isChildDelegation(); + ArgumentCaptor argument = ArgumentCaptor.forClass(String.class); + verify(logger, times(6)).debug(argument.capture()); + assertThat(argument.getAllValues()) + .containsExactly( + "test classpath: test-classes classes junit.jar hamcrest.jar", + "provider classpath: surefire-provider.jar", + "test(compact) classpath: test-classes classes junit.jar hamcrest.jar", + "provider(compact) classpath: surefire-provider.jar", + "in-process classpath: surefire-provider.jar maven-surefire-common.jar surefire-booter.jar surefire-extensions-api.jar surefire-api.jar surefire-extensions-spi.jar surefire-logger-api.jar surefire-shared-utils.jar", + "in-process(compact) classpath: surefire-provider.jar maven-surefire-common.jar surefire-booter.jar surefire-extensions-api.jar surefire-api.jar surefire-extensions-spi.jar surefire-logger-api.jar surefire-shared-utils.jar"); + + assertThat(conf.getClassLoaderConfiguration()).isSameAs(classLoaderConfiguration); + + assertThat((Object) conf.getClasspathConfiguration().getTestClasspath()).isEqualTo(testClasspath.toClasspath()); Collection files = new ArrayList<>(); - for ( Artifact providerArtifact : providerArtifacts ) - { - files.add( providerArtifact.getFile().getAbsolutePath() ); + for (Artifact providerArtifact : providerArtifacts) { + files.add(providerArtifact.getFile().getAbsolutePath()); } - assertThat( (Object) conf.getClasspathConfiguration().getProviderClasspath() ) - .isEqualTo( new Classpath( files ) ); + assertThat((Object) conf.getClasspathConfiguration().getProviderClasspath()) + .isEqualTo(new Classpath(files)); - assertThat( (Object) conf.getClasspathConfiguration().isClassPathConfig() ) - .isEqualTo( true ); + assertThat((Object) conf.getClasspathConfiguration().isClassPathConfig()) + .isEqualTo(true); - assertThat( (Object) conf.getClasspathConfiguration().isModularPathConfig() ) - .isEqualTo( false ); + assertThat((Object) conf.getClasspathConfiguration().isModularPathConfig()) + .isEqualTo(false); - assertThat( (Object) conf.getClasspathConfiguration().isEnableAssertions() ) - .isEqualTo( true ); + assertThat((Object) conf.getClasspathConfiguration().isEnableAssertions()) + .isEqualTo(true); - assertThat( conf.getProviderClassName() ) - .isEqualTo( "org.asf.Provider" ); + assertThat(conf.getProviderClassName()).isEqualTo("org.asf.Provider"); } @Test - public void providerClasspathCachingIsNotSharedAcrossMojoInstances() throws Exception - { - ProviderInfo providerInfo = mock( ProviderInfo.class ); - when( providerInfo.getProviderName() ).thenReturn( "test-provider" ); - Artifact provider = new DefaultArtifact( "com.example", "provider", createFromVersion( "1" ), "runtime", - "jar", "", handler ); - provider.setFile( mockFile( "original-test-provider.jar" ) ); - Set providerClasspath = singleton( provider ); - when( providerInfo.getProviderClasspath() ).thenReturn( providerClasspath ); - - StartupConfiguration startupConfiguration = startupConfigurationForProvider( providerInfo ); - assertThat( startupConfiguration.getClasspathConfiguration().getProviderClasspath().getClassPath() ) - .containsExactly( "original-test-provider.jar" ); - - provider.setFile( mockFile( "modified-test-provider.jar" ) ); - startupConfiguration = startupConfigurationForProvider( providerInfo ); - assertThat( startupConfiguration.getClasspathConfiguration().getProviderClasspath().getClassPath() ) - .containsExactly( "modified-test-provider.jar" ); + public void providerClasspathCachingIsNotSharedAcrossMojoInstances() throws Exception { + ProviderInfo providerInfo = mock(ProviderInfo.class); + when(providerInfo.getProviderName()).thenReturn("test-provider"); + Artifact provider = + new DefaultArtifact("com.example", "provider", createFromVersion("1"), "runtime", "jar", "", handler); + provider.setFile(mockFile("original-test-provider.jar")); + Set providerClasspath = singleton(provider); + when(providerInfo.getProviderClasspath()).thenReturn(providerClasspath); + + StartupConfiguration startupConfiguration = startupConfigurationForProvider(providerInfo); + assertThat(startupConfiguration + .getClasspathConfiguration() + .getProviderClasspath() + .getClassPath()) + .containsExactly("original-test-provider.jar"); + + provider.setFile(mockFile("modified-test-provider.jar")); + startupConfiguration = startupConfigurationForProvider(providerInfo); + assertThat(startupConfiguration + .getClasspathConfiguration() + .getProviderClasspath() + .getClassPath()) + .containsExactly("modified-test-provider.jar"); } - private StartupConfiguration startupConfigurationForProvider( ProviderInfo providerInfo ) throws Exception - { - AbstractSurefireMojo mojo = spy( new Mojo() ); + private StartupConfiguration startupConfigurationForProvider(ProviderInfo providerInfo) throws Exception { + AbstractSurefireMojo mojo = spy(new Mojo()); - Logger logger = mock( Logger.class ); - when( logger.isDebugEnabled() ).thenReturn( true ); - doNothing().when( logger ).debug( anyString() ); - when( mojo.getConsoleLogger() ).thenReturn( new PluginConsoleLogger( logger ) ); + Logger logger = mock(Logger.class); + when(logger.isDebugEnabled()).thenReturn(true); + doNothing().when(logger).debug(anyString()); + when(mojo.getConsoleLogger()).thenReturn(new PluginConsoleLogger(logger)); - File classesDir = mockFile( "classes" ); - File testClassesDir = mockFile( "test-classes" ); + File classesDir = mockFile("classes"); + File testClassesDir = mockFile("test-classes"); TestClassPath testClassPath = - new TestClassPath( new ArrayList(), classesDir, testClassesDir, new String[0] ); - - Artifact common = new DefaultArtifact( "org.apache.maven.surefire", "maven-surefire-common", - createFromVersion( "1" ), "runtime", "jar", "", handler ); - common.setFile( mockFile( "maven-surefire-common.jar" ) ); - - Artifact ext = new DefaultArtifact( "org.apache.maven.surefire", "surefire-extensions-api", - createFromVersion( "1" ), "runtime", "jar", "", handler ); - ext.setFile( mockFile( "surefire-extensions-api.jar" ) ); - - Artifact api = new DefaultArtifact( "org.apache.maven.surefire", "surefire-api", - createFromVersion( "1" ), "runtime", "jar", "", handler ); - api.setFile( mockFile( "surefire-api.jar" ) ); - - Artifact loggerApi = new DefaultArtifact( "org.apache.maven.surefire", "surefire-logger-api", - createFromVersion( "1" ), "runtime", "jar", "", handler ); - loggerApi.setFile( mockFile( "surefire-logger-api.jar" ) ); - - Artifact spi = new DefaultArtifact( "org.apache.maven.surefire", "surefire-extensions-spi", - createFromVersion( "1" ), "runtime", "jar", "", handler ); - spi.setFile( mockFile( "surefire-extensions-spi.jar" ) ); - - Artifact booter = new DefaultArtifact( "org.apache.maven.surefire", "surefire-booter", - createFromVersion( "1" ), "runtime", "jar", "", handler ); - booter.setFile( mockFile( "surefire-booter.jar" ) ); - - Artifact utils = new DefaultArtifact( "org.apache.maven.surefire", "surefire-shared-utils", - createFromVersion( "1" ), "runtime", "jar", "", handler ); - utils.setFile( mockFile( "surefire-shared-utils.jar" ) ); + new TestClassPath(new ArrayList(), classesDir, testClassesDir, new String[0]); + + Artifact common = new DefaultArtifact( + "org.apache.maven.surefire", + "maven-surefire-common", + createFromVersion("1"), + "runtime", + "jar", + "", + handler); + common.setFile(mockFile("maven-surefire-common.jar")); + + Artifact ext = new DefaultArtifact( + "org.apache.maven.surefire", + "surefire-extensions-api", + createFromVersion("1"), + "runtime", + "jar", + "", + handler); + ext.setFile(mockFile("surefire-extensions-api.jar")); + + Artifact api = new DefaultArtifact( + "org.apache.maven.surefire", "surefire-api", createFromVersion("1"), "runtime", "jar", "", handler); + api.setFile(mockFile("surefire-api.jar")); + + Artifact loggerApi = new DefaultArtifact( + "org.apache.maven.surefire", + "surefire-logger-api", + createFromVersion("1"), + "runtime", + "jar", + "", + handler); + loggerApi.setFile(mockFile("surefire-logger-api.jar")); + + Artifact spi = new DefaultArtifact( + "org.apache.maven.surefire", + "surefire-extensions-spi", + createFromVersion("1"), + "runtime", + "jar", + "", + handler); + spi.setFile(mockFile("surefire-extensions-spi.jar")); + + Artifact booter = new DefaultArtifact( + "org.apache.maven.surefire", "surefire-booter", createFromVersion("1"), "runtime", "jar", "", handler); + booter.setFile(mockFile("surefire-booter.jar")); + + Artifact utils = new DefaultArtifact( + "org.apache.maven.surefire", + "surefire-shared-utils", + createFromVersion("1"), + "runtime", + "jar", + "", + handler); + utils.setFile(mockFile("surefire-shared-utils.jar")); Map providerArtifactsMap = new HashMap<>(); - providerArtifactsMap.put( "org.apache.maven.surefire:maven-surefire-common", common ); - providerArtifactsMap.put( "org.apache.maven.surefire:surefire-extensions-api", ext ); - providerArtifactsMap.put( "org.apache.maven.surefire:surefire-api", api ); - providerArtifactsMap.put( "org.apache.maven.surefire:surefire-logger-api", loggerApi ); - providerArtifactsMap.put( "org.apache.maven.surefire:surefire-extensions-spi", spi ); - providerArtifactsMap.put( "org.apache.maven.surefire:surefire-booter", booter ); - providerArtifactsMap.put( "org.apache.maven.surefire:surefire-shared-utils", utils ); + providerArtifactsMap.put("org.apache.maven.surefire:maven-surefire-common", common); + providerArtifactsMap.put("org.apache.maven.surefire:surefire-extensions-api", ext); + providerArtifactsMap.put("org.apache.maven.surefire:surefire-api", api); + providerArtifactsMap.put("org.apache.maven.surefire:surefire-logger-api", loggerApi); + providerArtifactsMap.put("org.apache.maven.surefire:surefire-extensions-spi", spi); + providerArtifactsMap.put("org.apache.maven.surefire:surefire-booter", booter); + providerArtifactsMap.put("org.apache.maven.surefire:surefire-shared-utils", utils); - when( mojo.getPluginArtifactMap() ).thenReturn( providerArtifactsMap ); + when(mojo.getPluginArtifactMap()).thenReturn(providerArtifactsMap); - doReturn( 1 ).when( mojo, "getEffectiveForkCount" ); + doReturn(1).when(mojo, "getEffectiveForkCount"); - return invokeMethod( mojo, "createStartupConfiguration", - providerInfo, false, null, null, testClassPath, null, null ); + return invokeMethod( + mojo, "createStartupConfiguration", providerInfo, false, null, null, testClassPath, null, null); } @Test - public void shouldCreateStartupConfigWithModularPath() throws Exception - { - String baseDir = System.getProperty( "user.dir" ); + public void shouldCreateStartupConfigWithModularPath() throws Exception { + String baseDir = System.getProperty("user.dir"); Mojo mojo = new Mojo(); // ### BEGIN // we cannot mock private method newStartupConfigWithModularPath() - mocking the data to prevent from errors - LocationManager locationManager = mock( LocationManager.class ); - ResolvePathsResult resolvePathsResult = mock( ResolvePathsResult.class ); - when( locationManager.resolvePaths( any( ResolvePathsRequest.class ) ) ).thenReturn( resolvePathsResult ); - when( resolvePathsResult.getPathExceptions() ).thenReturn( emptyMap() ); - when( resolvePathsResult.getClasspathElements() ).thenReturn( emptyList() ); - when( resolvePathsResult.getModulepathElements() ).thenReturn( emptyMap() ); - - mojo.setLogger( mock( Logger.class ) ); - mojo.setUseModulePath( true ); - setInternalState( mojo, "locationManager", locationManager ); - - File jdkHome = new File( System.getProperty( "java.home" ) ); - File jvmExecutable = new File( jdkHome, IS_OS_WINDOWS ? "bin\\java.exe" : "bin/java" ); - JdkAttributes jdkAttributes = new JdkAttributes( jvmExecutable, jdkHome, true ); - Platform platform = new Platform().withJdkExecAttributesForTests( jdkAttributes ); - - File classesDirectory = new File( baseDir, "mock-dir" ); - File testClassesDirectory = new File( baseDir, "mock-dir" ); - mojo.setTestClassesDirectory( testClassesDirectory ); - TestClassPath testClassPath = new TestClassPath( Collections.emptySet(), - classesDirectory, testClassesDirectory, new String[0] ); - - ProviderInfo providerInfo = mock( ProviderInfo.class ); - when( providerInfo.getProviderName() ).thenReturn( "provider mock" ); - when( providerInfo.getProviderClasspath() ).thenReturn( Collections.emptySet() ); - - DefaultScanResult defaultScanResult = mock( DefaultScanResult.class ); - when( defaultScanResult.getClasses() ).thenReturn( Collections.emptyList() ); + LocationManager locationManager = mock(LocationManager.class); + ResolvePathsResult resolvePathsResult = mock(ResolvePathsResult.class); + when(locationManager.resolvePaths(any(ResolvePathsRequest.class))).thenReturn(resolvePathsResult); + when(resolvePathsResult.getPathExceptions()).thenReturn(emptyMap()); + when(resolvePathsResult.getClasspathElements()).thenReturn(emptyList()); + when(resolvePathsResult.getModulepathElements()).thenReturn(emptyMap()); + + mojo.setLogger(mock(Logger.class)); + mojo.setUseModulePath(true); + setInternalState(mojo, "locationManager", locationManager); + + File jdkHome = new File(System.getProperty("java.home")); + File jvmExecutable = new File(jdkHome, IS_OS_WINDOWS ? "bin\\java.exe" : "bin/java"); + JdkAttributes jdkAttributes = new JdkAttributes(jvmExecutable, jdkHome, true); + Platform platform = new Platform().withJdkExecAttributesForTests(jdkAttributes); + + File classesDirectory = new File(baseDir, "mock-dir"); + File testClassesDirectory = new File(baseDir, "mock-dir"); + mojo.setTestClassesDirectory(testClassesDirectory); + TestClassPath testClassPath = new TestClassPath( + Collections.emptySet(), classesDirectory, testClassesDirectory, new String[0]); + + ProviderInfo providerInfo = mock(ProviderInfo.class); + when(providerInfo.getProviderName()).thenReturn("provider mock"); + when(providerInfo.getProviderClasspath()).thenReturn(Collections.emptySet()); + + DefaultScanResult defaultScanResult = mock(DefaultScanResult.class); + when(defaultScanResult.getClasses()).thenReturn(Collections.emptyList()); Path pathToModularDescriptor = - Paths.get( baseDir, "src", "test", "resources", "org", "apache", "maven", "plugin", "surefire" ); - mojo.setMainBuildPath( pathToModularDescriptor.toFile() ); + Paths.get(baseDir, "src", "test", "resources", "org", "apache", "maven", "plugin", "surefire"); + mojo.setMainBuildPath(pathToModularDescriptor.toFile()); Map artifacts = new HashMap<>(); - Artifact dummyArtifact = mock( Artifact.class ); - when( dummyArtifact.getFile() ).thenReturn( new File( baseDir, "mock-file" ) ); - artifacts.put( "org.apache.maven.surefire:maven-surefire-common", dummyArtifact ); - artifacts.put( "org.apache.maven.surefire:surefire-extensions-api", dummyArtifact ); - artifacts.put( "org.apache.maven.surefire:surefire-api", dummyArtifact ); - artifacts.put( "org.apache.maven.surefire:surefire-logger-api", dummyArtifact ); - artifacts.put( "org.apache.maven.surefire:surefire-extensions-spi", dummyArtifact ); - artifacts.put( "org.apache.maven.surefire:surefire-booter", dummyArtifact ); - artifacts.put( "org.apache.maven.surefire:surefire-shared-utils", dummyArtifact ); - mojo.setPluginArtifactMap( artifacts ); - - ResolvePathResult resolvePathResult = mock( ResolvePathResult.class ); - JavaModuleDescriptor desc = mock( JavaModuleDescriptor.class ); - when( desc.name() ).thenReturn( "" ); - when( resolvePathResult.getModuleDescriptor() ).thenReturn( desc ); - ResolvePathResultWrapper wrapper = new ResolvePathResultWrapper( resolvePathResult, true ); + Artifact dummyArtifact = mock(Artifact.class); + when(dummyArtifact.getFile()).thenReturn(new File(baseDir, "mock-file")); + artifacts.put("org.apache.maven.surefire:maven-surefire-common", dummyArtifact); + artifacts.put("org.apache.maven.surefire:surefire-extensions-api", dummyArtifact); + artifacts.put("org.apache.maven.surefire:surefire-api", dummyArtifact); + artifacts.put("org.apache.maven.surefire:surefire-logger-api", dummyArtifact); + artifacts.put("org.apache.maven.surefire:surefire-extensions-spi", dummyArtifact); + artifacts.put("org.apache.maven.surefire:surefire-booter", dummyArtifact); + artifacts.put("org.apache.maven.surefire:surefire-shared-utils", dummyArtifact); + mojo.setPluginArtifactMap(artifacts); + + ResolvePathResult resolvePathResult = mock(ResolvePathResult.class); + JavaModuleDescriptor desc = mock(JavaModuleDescriptor.class); + when(desc.name()).thenReturn(""); + when(resolvePathResult.getModuleDescriptor()).thenReturn(desc); + ResolvePathResultWrapper wrapper = new ResolvePathResultWrapper(resolvePathResult, true); // ### END - StartupConfiguration actualConfig = invokeMethod( mojo, "createStartupConfiguration", - new Class[] {ProviderInfo.class, boolean.class, ClassLoaderConfiguration.class, DefaultScanResult.class, - TestClassPath.class, Platform.class, ResolvePathResultWrapper.class}, - providerInfo, true, mock( ClassLoaderConfiguration.class ), defaultScanResult, - testClassPath, platform, wrapper ); - - assertThat( actualConfig ) - .isNotNull(); - - assertThat( actualConfig.getClasspathConfiguration() ) - .isInstanceOf( ModularClasspathConfiguration.class ); + StartupConfiguration actualConfig = invokeMethod( + mojo, + "createStartupConfiguration", + new Class[] { + ProviderInfo.class, + boolean.class, + ClassLoaderConfiguration.class, + DefaultScanResult.class, + TestClassPath.class, + Platform.class, + ResolvePathResultWrapper.class + }, + providerInfo, + true, + mock(ClassLoaderConfiguration.class), + defaultScanResult, + testClassPath, + platform, + wrapper); + + assertThat(actualConfig).isNotNull(); + + assertThat(actualConfig.getClasspathConfiguration()).isInstanceOf(ModularClasspathConfiguration.class); } @Test - public void shouldExistTmpDirectory() throws IOException - { - String systemTmpDir = System.getProperty( "java.io.tmpdir" ); - String usrDir = new File( System.getProperty( "user.dir" ) ).getCanonicalPath(); + public void shouldExistTmpDirectory() throws IOException { + String systemTmpDir = System.getProperty("java.io.tmpdir"); + String usrDir = new File(System.getProperty("user.dir")).getCanonicalPath(); String tmpDir = "surefireX" + System.currentTimeMillis(); //noinspection ResultOfMethodCallIgnored - new File( systemTmpDir, tmpDir ).delete(); + new File(systemTmpDir, tmpDir).delete(); - File targetDir = new File( usrDir, "target" ); + File targetDir = new File(usrDir, "target"); //noinspection ResultOfMethodCallIgnored - new File( targetDir, tmpDir ).delete(); - - AbstractSurefireMojo mojo = mock( AbstractSurefireMojo.class ); - Logger logger = mock( Logger.class ); - when( logger.isDebugEnabled() ).thenReturn( false ); - when( logger.isErrorEnabled() ).thenReturn( false ); - doNothing().when( logger ).debug( anyString() ); - doNothing().when( logger ).error( anyString(), any( Throwable.class ) ); - when( mojo.getConsoleLogger() ).thenReturn( new PluginConsoleLogger( logger ) ); - when( mojo.getTempDir() ).thenReturn( tmpDir ); - when( mojo.getProjectBuildDirectory() ).thenReturn( targetDir ); - when( mojo.createSurefireBootDirectoryInTemp() ).thenCallRealMethod(); - when( mojo.createSurefireBootDirectoryInBuild() ).thenCallRealMethod(); - when( mojo.getSurefireTempDir() ).thenCallRealMethod(); + new File(targetDir, tmpDir).delete(); + + AbstractSurefireMojo mojo = mock(AbstractSurefireMojo.class); + Logger logger = mock(Logger.class); + when(logger.isDebugEnabled()).thenReturn(false); + when(logger.isErrorEnabled()).thenReturn(false); + doNothing().when(logger).debug(anyString()); + doNothing().when(logger).error(anyString(), any(Throwable.class)); + when(mojo.getConsoleLogger()).thenReturn(new PluginConsoleLogger(logger)); + when(mojo.getTempDir()).thenReturn(tmpDir); + when(mojo.getProjectBuildDirectory()).thenReturn(targetDir); + when(mojo.createSurefireBootDirectoryInTemp()).thenCallRealMethod(); + when(mojo.createSurefireBootDirectoryInBuild()).thenCallRealMethod(); + when(mojo.getSurefireTempDir()).thenCallRealMethod(); File bootDir = mojo.createSurefireBootDirectoryInTemp(); - assertThat( bootDir ).isNotNull(); - assertThat( bootDir ).isDirectory(); + assertThat(bootDir).isNotNull(); + assertThat(bootDir).isDirectory(); - assertThat( new File( systemTmpDir, bootDir.getName() ) ).isDirectory(); - assertThat( bootDir.getName() ) - .startsWith( tmpDir ); + assertThat(new File(systemTmpDir, bootDir.getName())).isDirectory(); + assertThat(bootDir.getName()).startsWith(tmpDir); File buildTmp = mojo.createSurefireBootDirectoryInBuild(); - assertThat( buildTmp ).isNotNull(); - assertThat( buildTmp ).isDirectory(); - assertThat( buildTmp.getParentFile().getCanonicalFile().getParent() ).isEqualTo( usrDir ); - assertThat( buildTmp.getName() ).isEqualTo( tmpDir ); + assertThat(buildTmp).isNotNull(); + assertThat(buildTmp).isDirectory(); + assertThat(buildTmp.getParentFile().getCanonicalFile().getParent()).isEqualTo(usrDir); + assertThat(buildTmp.getName()).isEqualTo(tmpDir); File tmp = mojo.getSurefireTempDir(); - assertThat( tmp ).isNotNull(); - assertThat( tmp ).isDirectory(); - assertThat( IS_OS_WINDOWS ? new File( systemTmpDir, bootDir.getName() ) : new File( targetDir, tmpDir ) ) - .isDirectory(); + assertThat(tmp).isNotNull(); + assertThat(tmp).isDirectory(); + assertThat(IS_OS_WINDOWS ? new File(systemTmpDir, bootDir.getName()) : new File(targetDir, tmpDir)) + .isDirectory(); } @Test - public void shouldSmartlyResolveJUnit5ProviderWithJUnit4() throws Exception - { + public void shouldSmartlyResolveJUnit5ProviderWithJUnit4() throws Exception { MavenProject mavenProject = new MavenProject(); - mavenProject.setArtifact( new DefaultArtifact( "dummy", "pom", createFromVersion( "1.0.0" ), - null, "jar", null, mock( ArtifactHandler.class ) ) ); - mojo.setProject( mavenProject ); + mavenProject.setArtifact(new DefaultArtifact( + "dummy", "pom", createFromVersion("1.0.0"), null, "jar", null, mock(ArtifactHandler.class))); + mojo.setProject(mavenProject); - final VersionRange surefireVersion = createFromVersion( "1" ); + final VersionRange surefireVersion = createFromVersion("1"); - Artifact testClasspathJUnit = new DefaultArtifact( "junit", "junit", - createFromVersion( "4.12" ), null, "jar", null, mock( ArtifactHandler.class ) ); + Artifact testClasspathJUnit = new DefaultArtifact( + "junit", "junit", createFromVersion("4.12"), null, "jar", null, mock(ArtifactHandler.class)); - Artifact testClasspathHamcrest = new DefaultArtifact( "org.hamcrest", "hamcrest-core", - createFromVersion( "1.3" ), null, "jar", null, mock( ArtifactHandler.class ) ); + Artifact testClasspathHamcrest = new DefaultArtifact( + "org.hamcrest", + "hamcrest-core", + createFromVersion("1.3"), + null, + "jar", + null, + mock(ArtifactHandler.class)); - setProjectDepedenciesToMojo( testClasspathJUnit, testClasspathHamcrest ); + setProjectDepedenciesToMojo(testClasspathJUnit, testClasspathHamcrest); Collection testArtifacts = new ArrayList<>(); - testArtifacts.add( testClasspathJUnit ); - testArtifacts.add( testClasspathHamcrest ); + testArtifacts.add(testClasspathJUnit); + testArtifacts.add(testClasspathHamcrest); - File classesDirectory = new File( "target/classes" ); + File classesDirectory = new File("target/classes"); - File testClassesDirectory = new File( "target/test-classes" ); + File testClassesDirectory = new File("target/test-classes"); TestClassPath testClasspathWrapper = - new TestClassPath( testArtifacts, classesDirectory, testClassesDirectory, null ); - - mojo.setRemoteRepositories( Collections.emptyList() ); - mojo.setProjectRemoteRepositories( Collections.emptyList() ); - RepositorySystem repositorySystem = mock( RepositorySystem.class ); - - final Artifact surefireProvider = new DefaultArtifact( "org.apache.maven.surefire", - "surefire-junit-platform", surefireVersion, null, "jar", null, mock( ArtifactHandler.class ) ); - - final Artifact pluginDependency = new DefaultArtifact( "org.junit.vintage", "junit-vintage-engine", - createFromVersion( "5.4.0" ), null, "jar", null, mock( ArtifactHandler.class ) ); - - when( repositorySystem.createDependencyArtifact( any( Dependency.class ) ) ).thenAnswer( new Answer() - { + new TestClassPath(testArtifacts, classesDirectory, testClassesDirectory, null); + + mojo.setRemoteRepositories(Collections.emptyList()); + mojo.setProjectRemoteRepositories(Collections.emptyList()); + RepositorySystem repositorySystem = mock(RepositorySystem.class); + + final Artifact surefireProvider = new DefaultArtifact( + "org.apache.maven.surefire", + "surefire-junit-platform", + surefireVersion, + null, + "jar", + null, + mock(ArtifactHandler.class)); + + final Artifact pluginDependency = new DefaultArtifact( + "org.junit.vintage", + "junit-vintage-engine", + createFromVersion("5.4.0"), + null, + "jar", + null, + mock(ArtifactHandler.class)); + + when(repositorySystem.createDependencyArtifact(any(Dependency.class))).thenAnswer(new Answer() { @Override - public Artifact answer( InvocationOnMock invocation ) - { + public Artifact answer(InvocationOnMock invocation) { Dependency dependency = (Dependency) invocation.getArguments()[0]; - if ( dependency.getArtifactId().equals( "surefire-junit-platform" ) ) - { + if (dependency.getArtifactId().equals("surefire-junit-platform")) { return surefireProvider; - } - else if ( dependency.getArtifactId().equals( "junit-vintage-engine" ) ) - { + } else if (dependency.getArtifactId().equals("junit-vintage-engine")) { return pluginDependency; - } - else - { - fail( dependency.getGroupId() + ":" + dependency.getArtifactId() ); + } else { + fail(dependency.getGroupId() + ":" + dependency.getArtifactId()); return null; } } - } ); - - final ArtifactResolutionResult surefireProviderResolutionResult = mock( ArtifactResolutionResult.class ); - final ArtifactResolutionResult pluginDependencyResolutionResult = mock( ArtifactResolutionResult.class ); - when( repositorySystem.resolve( any( ArtifactResolutionRequest.class ) ) ) - .thenAnswer( new Answer() - { - @Override - public ArtifactResolutionResult answer( InvocationOnMock invocation ) - { - ArtifactResolutionRequest req = (ArtifactResolutionRequest) invocation.getArguments()[0]; - Artifact artifact = req.getArtifact(); - if ( artifact == surefireProvider ) - { - return surefireProviderResolutionResult; - } - else if ( artifact == pluginDependency ) - { - return pluginDependencyResolutionResult; + }); + + final ArtifactResolutionResult surefireProviderResolutionResult = mock(ArtifactResolutionResult.class); + final ArtifactResolutionResult pluginDependencyResolutionResult = mock(ArtifactResolutionResult.class); + when(repositorySystem.resolve(any(ArtifactResolutionRequest.class))) + .thenAnswer(new Answer() { + @Override + public ArtifactResolutionResult answer(InvocationOnMock invocation) { + ArtifactResolutionRequest req = + (ArtifactResolutionRequest) invocation.getArguments()[0]; + Artifact artifact = req.getArtifact(); + if (artifact == surefireProvider) { + return surefireProviderResolutionResult; + } else if (artifact == pluginDependency) { + return pluginDependencyResolutionResult; + } else if ("org.junit.platform".equals(artifact.getGroupId()) + && "junit-platform-launcher".equals(artifact.getArtifactId()) + && "1.4.0".equals(artifact.getVersion())) { + return createExpectedJUnitPlatformLauncherResolutionResult(); + } else { + fail(artifact.getGroupId() + ":" + artifact.getArtifactId()); + return null; + } } - else if ( "org.junit.platform".equals( artifact.getGroupId() ) - && "junit-platform-launcher".equals( artifact.getArtifactId() ) - && "1.4.0".equals( artifact.getVersion() ) ) - { - return createExpectedJUnitPlatformLauncherResolutionResult(); - } - else - { - fail( artifact.getGroupId() + ":" + artifact.getArtifactId() ); - return null; - } - } - } ); - - Artifact java5 = new DefaultArtifact( "org.apache.maven.surefire", "common-java5", - surefireVersion, null, "jar", null, mock( ArtifactHandler.class ) ); - Artifact launcher = new DefaultArtifact( "org.junit.platform", "junit-platform-launcher", - createFromVersion( "1.3.2" ), null, "jar", null, mock( ArtifactHandler.class ) ); - Artifact apiguardian = new DefaultArtifact( "org.apiguardian", "apiguardian-api", - createFromVersion( "1.0.0" ), null, "jar", null, mock( ArtifactHandler.class ) ); - Artifact engine = new DefaultArtifact( "org.junit.platform", "junit-platform-engine", - createFromVersion( "1.3.2" ), null, "jar", null, mock( ArtifactHandler.class ) ); - Artifact commons = new DefaultArtifact( "org.junit.platform", "junit-platform-commons", - createFromVersion( "1.3.2" ), null, "jar", null, mock( ArtifactHandler.class ) ); - Artifact opentest4j = new DefaultArtifact( "org.opentest4j", "opentest4j", - createFromVersion( "1.1.1" ), null, "jar", null, mock( ArtifactHandler.class ) ); + }); + + Artifact java5 = new DefaultArtifact( + "org.apache.maven.surefire", + "common-java5", + surefireVersion, + null, + "jar", + null, + mock(ArtifactHandler.class)); + Artifact launcher = new DefaultArtifact( + "org.junit.platform", + "junit-platform-launcher", + createFromVersion("1.3.2"), + null, + "jar", + null, + mock(ArtifactHandler.class)); + Artifact apiguardian = new DefaultArtifact( + "org.apiguardian", + "apiguardian-api", + createFromVersion("1.0.0"), + null, + "jar", + null, + mock(ArtifactHandler.class)); + Artifact engine = new DefaultArtifact( + "org.junit.platform", + "junit-platform-engine", + createFromVersion("1.3.2"), + null, + "jar", + null, + mock(ArtifactHandler.class)); + Artifact commons = new DefaultArtifact( + "org.junit.platform", + "junit-platform-commons", + createFromVersion("1.3.2"), + null, + "jar", + null, + mock(ArtifactHandler.class)); + Artifact opentest4j = new DefaultArtifact( + "org.opentest4j", + "opentest4j", + createFromVersion("1.1.1"), + null, + "jar", + null, + mock(ArtifactHandler.class)); Set providerArtifacts = new HashSet<>(); - providerArtifacts.add( surefireProvider ); - providerArtifacts.add( java5 ); - providerArtifacts.add( launcher ); - providerArtifacts.add( apiguardian ); - providerArtifacts.add( engine ); - providerArtifacts.add( commons ); - providerArtifacts.add( opentest4j ); - - when( surefireProviderResolutionResult.getArtifacts() ) - .thenReturn( providerArtifacts ); - - final Artifact pluginDep1 = new DefaultArtifact( "org.junit.vintage", "junit-vintage-engine", - createFromVersion( "5.4.0" ), null, "jar", null, mock( ArtifactHandler.class ) ); - - final Artifact pluginDep2 = new DefaultArtifact( "org.apiguardian", "apiguardian-api", - createFromVersion( "1.0.0" ), null, "jar", null, mock( ArtifactHandler.class ) ); - - final Artifact pluginDep3 = new DefaultArtifact( "org.junit.platform", "junit-platform-engine", - createFromVersion( "1.4.0" ), null, "jar", null, mock( ArtifactHandler.class ) ); - - final Artifact pluginDep4 = new DefaultArtifact( "junit", "junit", - createFromVersion( "4.12" ), null, "jar", null, mock( ArtifactHandler.class ) ); - - final Artifact pluginDep5 = new DefaultArtifact( "org.hamcrest", "hamcrest-core", - createFromVersion( "1.3" ), null, "jar", null, mock( ArtifactHandler.class ) ); - - final Artifact pluginDep6 = new DefaultArtifact( "org.opentest4j", "opentest4j", - createFromVersion( "1.1.1" ), null, "jar", null, mock( ArtifactHandler.class ) ); - - final Artifact pluginDep7 = new DefaultArtifact( "org.junit.platform", "junit-platform-commons", - createFromVersion( "1.4.0" ), null, "jar", null, mock( ArtifactHandler.class ) ); - - addPluginDependencies( pluginDep1, pluginDep2, pluginDep3, pluginDep4, pluginDep5, pluginDep6, pluginDep7 ); - - mojo.setRepositorySystem( repositorySystem ); - mojo.setLogger( mock( Logger.class ) ); + providerArtifacts.add(surefireProvider); + providerArtifacts.add(java5); + providerArtifacts.add(launcher); + providerArtifacts.add(apiguardian); + providerArtifacts.add(engine); + providerArtifacts.add(commons); + providerArtifacts.add(opentest4j); + + when(surefireProviderResolutionResult.getArtifacts()).thenReturn(providerArtifacts); + + final Artifact pluginDep1 = new DefaultArtifact( + "org.junit.vintage", + "junit-vintage-engine", + createFromVersion("5.4.0"), + null, + "jar", + null, + mock(ArtifactHandler.class)); + + final Artifact pluginDep2 = new DefaultArtifact( + "org.apiguardian", + "apiguardian-api", + createFromVersion("1.0.0"), + null, + "jar", + null, + mock(ArtifactHandler.class)); + + final Artifact pluginDep3 = new DefaultArtifact( + "org.junit.platform", + "junit-platform-engine", + createFromVersion("1.4.0"), + null, + "jar", + null, + mock(ArtifactHandler.class)); + + final Artifact pluginDep4 = new DefaultArtifact( + "junit", "junit", createFromVersion("4.12"), null, "jar", null, mock(ArtifactHandler.class)); + + final Artifact pluginDep5 = new DefaultArtifact( + "org.hamcrest", + "hamcrest-core", + createFromVersion("1.3"), + null, + "jar", + null, + mock(ArtifactHandler.class)); + + final Artifact pluginDep6 = new DefaultArtifact( + "org.opentest4j", + "opentest4j", + createFromVersion("1.1.1"), + null, + "jar", + null, + mock(ArtifactHandler.class)); + + final Artifact pluginDep7 = new DefaultArtifact( + "org.junit.platform", + "junit-platform-commons", + createFromVersion("1.4.0"), + null, + "jar", + null, + mock(ArtifactHandler.class)); + + addPluginDependencies(pluginDep1, pluginDep2, pluginDep3, pluginDep4, pluginDep5, pluginDep6, pluginDep7); + + mojo.setRepositorySystem(repositorySystem); + mojo.setLogger(mock(Logger.class)); Set pluginDependencyArtifacts = new HashSet<>(); - pluginDependencyArtifacts.add( pluginDep1 ); - pluginDependencyArtifacts.add( pluginDep2 ); - pluginDependencyArtifacts.add( pluginDep3 ); - pluginDependencyArtifacts.add( pluginDep4 ); - pluginDependencyArtifacts.add( pluginDep5 ); - pluginDependencyArtifacts.add( pluginDep6 ); - pluginDependencyArtifacts.add( pluginDep7 ); - when( pluginDependencyResolutionResult.getArtifacts() ).thenReturn( pluginDependencyArtifacts ); - - invokeMethod( mojo, "setupStuff" ); - - when( mojo.getSession().getProjectBuildingRequest() ) - .thenReturn( mock( ProjectBuildingRequest.class ) ); - - PluginDescriptor pluginDescriptor = mock( PluginDescriptor.class ); - mojo.setPluginDescriptor( pluginDescriptor ); - Plugin p = mock( Plugin.class ); - when( pluginDescriptor.getPlugin() ) - .thenReturn( p ); - when( p.getDependencies() ) - .thenReturn( singletonList( toDependency( pluginDependency ) ) ); - - Artifact junitPlatformArtifact = invokeMethod( mojo, "getJUnit5Artifact" ); - assertThat( junitPlatformArtifact.getGroupId() ).isEqualTo( "org.junit.platform" ); - assertThat( junitPlatformArtifact.getArtifactId() ).isEqualTo( "junit-platform-engine" ); - assertThat( junitPlatformArtifact.getVersion() ).isEqualTo( "1.4.0" ); + pluginDependencyArtifacts.add(pluginDep1); + pluginDependencyArtifacts.add(pluginDep2); + pluginDependencyArtifacts.add(pluginDep3); + pluginDependencyArtifacts.add(pluginDep4); + pluginDependencyArtifacts.add(pluginDep5); + pluginDependencyArtifacts.add(pluginDep6); + pluginDependencyArtifacts.add(pluginDep7); + when(pluginDependencyResolutionResult.getArtifacts()).thenReturn(pluginDependencyArtifacts); + + invokeMethod(mojo, "setupStuff"); + + when(mojo.getSession().getProjectBuildingRequest()).thenReturn(mock(ProjectBuildingRequest.class)); + + PluginDescriptor pluginDescriptor = mock(PluginDescriptor.class); + mojo.setPluginDescriptor(pluginDescriptor); + Plugin p = mock(Plugin.class); + when(pluginDescriptor.getPlugin()).thenReturn(p); + when(p.getDependencies()).thenReturn(singletonList(toDependency(pluginDependency))); + + Artifact junitPlatformArtifact = invokeMethod(mojo, "getJUnit5Artifact"); + assertThat(junitPlatformArtifact.getGroupId()).isEqualTo("org.junit.platform"); + assertThat(junitPlatformArtifact.getArtifactId()).isEqualTo("junit-platform-engine"); + assertThat(junitPlatformArtifact.getVersion()).isEqualTo("1.4.0"); JUnitPlatformProviderInfo prov = - mojo.createJUnitPlatformProviderInfo( junitPlatformArtifact, testClasspathWrapper ); - - assertThat( prov.isApplicable() ) - .isTrue(); - - Artifact expectedProvider = new DefaultArtifact( "org.apache.maven.surefire", "surefire-junit-platform", - surefireVersion, null, "jar", null, mock( ArtifactHandler.class ) ); - Artifact expectedCommonJava5 = new DefaultArtifact( "org.apache.maven.surefire", "common-java5", - surefireVersion, null, "jar", null, mock( ArtifactHandler.class ) ); - Artifact expectedLauncher = new DefaultArtifact( "org.junit.platform", "junit-platform-launcher", - createFromVersion( "1.4.0" ), null, "jar", null, mock( ArtifactHandler.class ) ); - Artifact expectedApiguardian = new DefaultArtifact( "org.apiguardian", "apiguardian-api", - createFromVersion( "1.0.0" ), null, "jar", null, mock( ArtifactHandler.class ) ); - Artifact expectedJUnit5Engine = new DefaultArtifact( "org.junit.platform", "junit-platform-engine", - createFromVersion( "1.4.0" ), null, "jar", null, mock( ArtifactHandler.class ) ); - Artifact expectedOpentest4j = new DefaultArtifact( "org.opentest4j", "opentest4j", - createFromVersion( "1.1.1" ), null, "jar", null, mock( ArtifactHandler.class ) ); - Artifact expectedPlatformCommons = new DefaultArtifact( "org.junit.platform", "junit-platform-commons", - createFromVersion( "1.4.0" ), null, "jar", null, mock( ArtifactHandler.class ) ); - Artifact expectedEngine = new DefaultArtifact( "org.junit.vintage", "junit-vintage-engine", - createFromVersion( "5.4.0" ), null, "jar", null, mock( ArtifactHandler.class ) ); - assertThat( prov.getProviderClasspath() ) - .hasSize( 8 ) - .containsOnly( expectedProvider, expectedCommonJava5, expectedLauncher, expectedApiguardian, - expectedJUnit5Engine, expectedOpentest4j, expectedPlatformCommons, expectedEngine ); - - assertThat( testClasspathWrapper.getTestDependencies() ) - .hasSize( 2 ) - .containsEntry( "junit:junit", testClasspathJUnit ) - .containsEntry( "org.hamcrest:hamcrest-core", testClasspathHamcrest ); + mojo.createJUnitPlatformProviderInfo(junitPlatformArtifact, testClasspathWrapper); + + assertThat(prov.isApplicable()).isTrue(); + + Artifact expectedProvider = new DefaultArtifact( + "org.apache.maven.surefire", + "surefire-junit-platform", + surefireVersion, + null, + "jar", + null, + mock(ArtifactHandler.class)); + Artifact expectedCommonJava5 = new DefaultArtifact( + "org.apache.maven.surefire", + "common-java5", + surefireVersion, + null, + "jar", + null, + mock(ArtifactHandler.class)); + Artifact expectedLauncher = new DefaultArtifact( + "org.junit.platform", + "junit-platform-launcher", + createFromVersion("1.4.0"), + null, + "jar", + null, + mock(ArtifactHandler.class)); + Artifact expectedApiguardian = new DefaultArtifact( + "org.apiguardian", + "apiguardian-api", + createFromVersion("1.0.0"), + null, + "jar", + null, + mock(ArtifactHandler.class)); + Artifact expectedJUnit5Engine = new DefaultArtifact( + "org.junit.platform", + "junit-platform-engine", + createFromVersion("1.4.0"), + null, + "jar", + null, + mock(ArtifactHandler.class)); + Artifact expectedOpentest4j = new DefaultArtifact( + "org.opentest4j", + "opentest4j", + createFromVersion("1.1.1"), + null, + "jar", + null, + mock(ArtifactHandler.class)); + Artifact expectedPlatformCommons = new DefaultArtifact( + "org.junit.platform", + "junit-platform-commons", + createFromVersion("1.4.0"), + null, + "jar", + null, + mock(ArtifactHandler.class)); + Artifact expectedEngine = new DefaultArtifact( + "org.junit.vintage", + "junit-vintage-engine", + createFromVersion("5.4.0"), + null, + "jar", + null, + mock(ArtifactHandler.class)); + assertThat(prov.getProviderClasspath()) + .hasSize(8) + .containsOnly( + expectedProvider, + expectedCommonJava5, + expectedLauncher, + expectedApiguardian, + expectedJUnit5Engine, + expectedOpentest4j, + expectedPlatformCommons, + expectedEngine); + + assertThat(testClasspathWrapper.getTestDependencies()) + .hasSize(2) + .containsEntry("junit:junit", testClasspathJUnit) + .containsEntry("org.hamcrest:hamcrest-core", testClasspathHamcrest); } @Test - public void shouldSmartlyResolveJUnit5ProviderWithVintage() throws Exception - { + public void shouldSmartlyResolveJUnit5ProviderWithVintage() throws Exception { MavenProject mavenProject = new MavenProject(); - mavenProject.setArtifact( new DefaultArtifact( "dummy", "pom", createFromVersion( "1.0.0" ), - null, "jar", null, mock( ArtifactHandler.class ) ) ); - mojo.setProject( mavenProject ); - - VersionRange surefireVersion = createFromVersion( "1" ); - - Artifact testClasspathSomeTestArtifact = new DefaultArtifact( "third.party", "artifact", - createFromVersion( "1.0" ), null, "jar", null, mock( ArtifactHandler.class ) ); - - Artifact testClasspathVintage = new DefaultArtifact( "org.junit.vintage", "junit-vintage-engine", - createFromVersion( "5.4.0" ), null, "jar", null, mock( ArtifactHandler.class ) ); - - Artifact testClasspathApiguardian = new DefaultArtifact( "org.apiguardian", "apiguardian-api", - createFromVersion( "1.0.0" ), null, "jar", null, mock( ArtifactHandler.class ) ); - - Artifact testClasspathPlatformEng = new DefaultArtifact( "org.junit.platform", "junit-platform-engine", - createFromVersion( "1.4.0" ), null, "jar", null, mock( ArtifactHandler.class ) ); - - Artifact testClasspathJUnit4 = new DefaultArtifact( "junit", "junit", - createFromVersion( "4.12" ), null, "jar", null, mock( ArtifactHandler.class ) ); - - Artifact testClasspathHamcrest = new DefaultArtifact( "org.hamcrest", "hamcrest-core", - createFromVersion( "1.3" ), null, "jar", null, mock( ArtifactHandler.class ) ); - - Artifact testClasspathOpentest4j = new DefaultArtifact( "org.opentest4j", "opentest4j", - createFromVersion( "1.1.1" ), null, "jar", null, mock( ArtifactHandler.class ) ); - - Artifact testClasspathCommons = new DefaultArtifact( "org.junit.platform", "junit-platform-commons", - createFromVersion( "1.4.0" ), null, "jar", null, mock( ArtifactHandler.class ) ); - - Collection testArtifacts = asList( testClasspathSomeTestArtifact, testClasspathVintage, - testClasspathApiguardian, testClasspathPlatformEng, testClasspathJUnit4, testClasspathHamcrest, - testClasspathOpentest4j, testClasspathCommons ); - - setProjectDepedenciesToMojo( testArtifacts.toArray( new Artifact[testArtifacts.size()] ) ); - - File classesDirectory = new File( "target/classes" ); - - File testClassesDirectory = new File( "target/test-classes" ); + mavenProject.setArtifact(new DefaultArtifact( + "dummy", "pom", createFromVersion("1.0.0"), null, "jar", null, mock(ArtifactHandler.class))); + mojo.setProject(mavenProject); + + VersionRange surefireVersion = createFromVersion("1"); + + Artifact testClasspathSomeTestArtifact = new DefaultArtifact( + "third.party", "artifact", createFromVersion("1.0"), null, "jar", null, mock(ArtifactHandler.class)); + + Artifact testClasspathVintage = new DefaultArtifact( + "org.junit.vintage", + "junit-vintage-engine", + createFromVersion("5.4.0"), + null, + "jar", + null, + mock(ArtifactHandler.class)); + + Artifact testClasspathApiguardian = new DefaultArtifact( + "org.apiguardian", + "apiguardian-api", + createFromVersion("1.0.0"), + null, + "jar", + null, + mock(ArtifactHandler.class)); + + Artifact testClasspathPlatformEng = new DefaultArtifact( + "org.junit.platform", + "junit-platform-engine", + createFromVersion("1.4.0"), + null, + "jar", + null, + mock(ArtifactHandler.class)); + + Artifact testClasspathJUnit4 = new DefaultArtifact( + "junit", "junit", createFromVersion("4.12"), null, "jar", null, mock(ArtifactHandler.class)); + + Artifact testClasspathHamcrest = new DefaultArtifact( + "org.hamcrest", + "hamcrest-core", + createFromVersion("1.3"), + null, + "jar", + null, + mock(ArtifactHandler.class)); + + Artifact testClasspathOpentest4j = new DefaultArtifact( + "org.opentest4j", + "opentest4j", + createFromVersion("1.1.1"), + null, + "jar", + null, + mock(ArtifactHandler.class)); + + Artifact testClasspathCommons = new DefaultArtifact( + "org.junit.platform", + "junit-platform-commons", + createFromVersion("1.4.0"), + null, + "jar", + null, + mock(ArtifactHandler.class)); + + Collection testArtifacts = asList( + testClasspathSomeTestArtifact, + testClasspathVintage, + testClasspathApiguardian, + testClasspathPlatformEng, + testClasspathJUnit4, + testClasspathHamcrest, + testClasspathOpentest4j, + testClasspathCommons); + + setProjectDepedenciesToMojo(testArtifacts.toArray(new Artifact[testArtifacts.size()])); + + File classesDirectory = new File("target/classes"); + + File testClassesDirectory = new File("target/test-classes"); TestClassPath testClasspathWrapper = - new TestClassPath( testArtifacts, classesDirectory, testClassesDirectory, null ); - - mojo.setRemoteRepositories( Collections.emptyList() ); - mojo.setProjectRemoteRepositories( Collections.emptyList() ); - RepositorySystem repositorySystem = mock( RepositorySystem.class ); - final Artifact surefireProvider = new DefaultArtifact( "org.apache.maven.surefire", - "surefire-junit-platform", surefireVersion, null, "jar", null, mock( ArtifactHandler.class ) ); - when( repositorySystem.createDependencyArtifact( any( Dependency.class ) ) ).thenAnswer( new Answer() - { + new TestClassPath(testArtifacts, classesDirectory, testClassesDirectory, null); + + mojo.setRemoteRepositories(Collections.emptyList()); + mojo.setProjectRemoteRepositories(Collections.emptyList()); + RepositorySystem repositorySystem = mock(RepositorySystem.class); + final Artifact surefireProvider = new DefaultArtifact( + "org.apache.maven.surefire", + "surefire-junit-platform", + surefireVersion, + null, + "jar", + null, + mock(ArtifactHandler.class)); + when(repositorySystem.createDependencyArtifact(any(Dependency.class))).thenAnswer(new Answer() { @Override - public Artifact answer( InvocationOnMock invocation ) - { + public Artifact answer(InvocationOnMock invocation) { Dependency provider = (Dependency) invocation.getArguments()[0]; - assertThat( provider.getGroupId() ).isEqualTo( "org.apache.maven.surefire" ); - assertThat( provider.getArtifactId() ).isEqualTo( "surefire-junit-platform" ); + assertThat(provider.getGroupId()).isEqualTo("org.apache.maven.surefire"); + assertThat(provider.getArtifactId()).isEqualTo("surefire-junit-platform"); return surefireProvider; } - } ); - final ArtifactResolutionResult surefireProviderResolutionResult = mock( ArtifactResolutionResult.class ); - when( repositorySystem.resolve( any( ArtifactResolutionRequest.class ) ) ) - .thenAnswer( new Answer() - { - @Override - public ArtifactResolutionResult answer( InvocationOnMock invocation ) - { - ArtifactResolutionRequest req = (ArtifactResolutionRequest) invocation.getArguments()[0]; - Artifact resolvable = req.getArtifact(); - if ( resolvable == surefireProvider ) - { - return surefireProviderResolutionResult; - } - else if ( "org.junit.platform".equals( resolvable.getGroupId() ) - && "junit-platform-launcher".equals( resolvable.getArtifactId() ) - && "1.4.0".equals( resolvable.getVersion() ) ) - { - return createExpectedJUnitPlatformLauncherResolutionResult(); + }); + final ArtifactResolutionResult surefireProviderResolutionResult = mock(ArtifactResolutionResult.class); + when(repositorySystem.resolve(any(ArtifactResolutionRequest.class))) + .thenAnswer(new Answer() { + @Override + public ArtifactResolutionResult answer(InvocationOnMock invocation) { + ArtifactResolutionRequest req = + (ArtifactResolutionRequest) invocation.getArguments()[0]; + Artifact resolvable = req.getArtifact(); + if (resolvable == surefireProvider) { + return surefireProviderResolutionResult; + } else if ("org.junit.platform".equals(resolvable.getGroupId()) + && "junit-platform-launcher".equals(resolvable.getArtifactId()) + && "1.4.0".equals(resolvable.getVersion())) { + return createExpectedJUnitPlatformLauncherResolutionResult(); + } else { + fail(resolvable.getGroupId() + ":" + resolvable.getArtifactId()); + return null; + } } - else - { - fail( resolvable.getGroupId() + ":" + resolvable.getArtifactId() ); - return null; - } - } - } ); - - Artifact java5 = new DefaultArtifact( "org.apache.maven.surefire", "common-java5", - surefireVersion, null, "jar", null, mock( ArtifactHandler.class ) ); - Artifact launcher = new DefaultArtifact( "org.junit.platform", "junit-platform-launcher", - createFromVersion( "1.3.2" ), null, "jar", null, mock( ArtifactHandler.class ) ); - Artifact apiguardian = new DefaultArtifact( "org.apiguardian", "apiguardian-api", - createFromVersion( "1.0.0" ), null, "jar", null, mock( ArtifactHandler.class ) ); - Artifact engine = new DefaultArtifact( "org.junit.platform", "junit-platform-engine", - createFromVersion( "1.3.2" ), null, "jar", null, mock( ArtifactHandler.class ) ); - Artifact commons = new DefaultArtifact( "org.junit.platform", "junit-platform-commons", - createFromVersion( "1.3.2" ), null, "jar", null, mock( ArtifactHandler.class ) ); - Artifact opentest4j = new DefaultArtifact( "org.opentest4j", "opentest4j", - createFromVersion( "1.1.1" ), null, "jar", null, mock( ArtifactHandler.class ) ); + }); + + Artifact java5 = new DefaultArtifact( + "org.apache.maven.surefire", + "common-java5", + surefireVersion, + null, + "jar", + null, + mock(ArtifactHandler.class)); + Artifact launcher = new DefaultArtifact( + "org.junit.platform", + "junit-platform-launcher", + createFromVersion("1.3.2"), + null, + "jar", + null, + mock(ArtifactHandler.class)); + Artifact apiguardian = new DefaultArtifact( + "org.apiguardian", + "apiguardian-api", + createFromVersion("1.0.0"), + null, + "jar", + null, + mock(ArtifactHandler.class)); + Artifact engine = new DefaultArtifact( + "org.junit.platform", + "junit-platform-engine", + createFromVersion("1.3.2"), + null, + "jar", + null, + mock(ArtifactHandler.class)); + Artifact commons = new DefaultArtifact( + "org.junit.platform", + "junit-platform-commons", + createFromVersion("1.3.2"), + null, + "jar", + null, + mock(ArtifactHandler.class)); + Artifact opentest4j = new DefaultArtifact( + "org.opentest4j", + "opentest4j", + createFromVersion("1.1.1"), + null, + "jar", + null, + mock(ArtifactHandler.class)); Set providerArtifacts = new HashSet<>(); - providerArtifacts.add( surefireProvider ); - providerArtifacts.add( java5 ); - providerArtifacts.add( launcher ); - providerArtifacts.add( apiguardian ); - providerArtifacts.add( engine ); - providerArtifacts.add( commons ); - providerArtifacts.add( opentest4j ); - when( surefireProviderResolutionResult.getArtifacts() ) - .thenReturn( providerArtifacts ); - - mojo.setRepositorySystem( repositorySystem ); - mojo.setLogger( mock( Logger.class ) ); - - invokeMethod( mojo, "setupStuff" ); - - PluginDescriptor pluginDescriptor = mock( PluginDescriptor.class ); - mojo.setPluginDescriptor( pluginDescriptor ); - Plugin p = mock( Plugin.class ); - when( pluginDescriptor.getPlugin() ) - .thenReturn( p ); - when( p.getDependencies() ) - .thenReturn( Collections.emptyList() ); - - Artifact junitPlatformArtifact = invokeMethod( mojo, "getJUnit5Artifact" ); - assertThat( junitPlatformArtifact.getGroupId() ).isEqualTo( "org.junit.platform" ); - assertThat( junitPlatformArtifact.getArtifactId() ).isEqualTo( "junit-platform-commons" ); - assertThat( junitPlatformArtifact.getVersion() ).isEqualTo( "1.4.0" ); + providerArtifacts.add(surefireProvider); + providerArtifacts.add(java5); + providerArtifacts.add(launcher); + providerArtifacts.add(apiguardian); + providerArtifacts.add(engine); + providerArtifacts.add(commons); + providerArtifacts.add(opentest4j); + when(surefireProviderResolutionResult.getArtifacts()).thenReturn(providerArtifacts); + + mojo.setRepositorySystem(repositorySystem); + mojo.setLogger(mock(Logger.class)); + + invokeMethod(mojo, "setupStuff"); + + PluginDescriptor pluginDescriptor = mock(PluginDescriptor.class); + mojo.setPluginDescriptor(pluginDescriptor); + Plugin p = mock(Plugin.class); + when(pluginDescriptor.getPlugin()).thenReturn(p); + when(p.getDependencies()).thenReturn(Collections.emptyList()); + + Artifact junitPlatformArtifact = invokeMethod(mojo, "getJUnit5Artifact"); + assertThat(junitPlatformArtifact.getGroupId()).isEqualTo("org.junit.platform"); + assertThat(junitPlatformArtifact.getArtifactId()).isEqualTo("junit-platform-commons"); + assertThat(junitPlatformArtifact.getVersion()).isEqualTo("1.4.0"); JUnitPlatformProviderInfo prov = - mojo.createJUnitPlatformProviderInfo( junitPlatformArtifact, testClasspathWrapper ); - - assertThat( prov.isApplicable() ) - .isTrue(); - - Artifact expectedProvider = new DefaultArtifact( "org.apache.maven.surefire", "surefire-junit-platform", - surefireVersion, null, "jar", null, mock( ArtifactHandler.class ) ); - Artifact expectedCommonJava5 = new DefaultArtifact( "org.apache.maven.surefire", "common-java5", - surefireVersion, null, "jar", null, mock( ArtifactHandler.class ) ); - Artifact expectedLauncher = new DefaultArtifact( "org.junit.platform", "junit-platform-launcher", - createFromVersion( "1.4.0" ), null, "jar", null, mock( ArtifactHandler.class ) ); - assertThat( prov.getProviderClasspath() ) - .hasSize( 3 ) - .containsOnly( expectedProvider, expectedCommonJava5, expectedLauncher ); - - assertThat( testClasspathWrapper.getTestDependencies() ) - .hasSize( 8 ) - .containsEntry( "third.party:artifact", testClasspathSomeTestArtifact ) - .containsEntry( "org.junit.vintage:junit-vintage-engine", testClasspathVintage ) - .containsEntry( "org.apiguardian:apiguardian-api", testClasspathApiguardian ) - .containsEntry( "org.junit.platform:junit-platform-engine", testClasspathPlatformEng ) - .containsEntry( "junit:junit", testClasspathJUnit4 ) - .containsEntry( "org.hamcrest:hamcrest-core", testClasspathHamcrest ) - .containsEntry( "org.opentest4j:opentest4j", testClasspathOpentest4j ) - .containsEntry( "org.junit.platform:junit-platform-commons", testClasspathCommons ); + mojo.createJUnitPlatformProviderInfo(junitPlatformArtifact, testClasspathWrapper); + + assertThat(prov.isApplicable()).isTrue(); + + Artifact expectedProvider = new DefaultArtifact( + "org.apache.maven.surefire", + "surefire-junit-platform", + surefireVersion, + null, + "jar", + null, + mock(ArtifactHandler.class)); + Artifact expectedCommonJava5 = new DefaultArtifact( + "org.apache.maven.surefire", + "common-java5", + surefireVersion, + null, + "jar", + null, + mock(ArtifactHandler.class)); + Artifact expectedLauncher = new DefaultArtifact( + "org.junit.platform", + "junit-platform-launcher", + createFromVersion("1.4.0"), + null, + "jar", + null, + mock(ArtifactHandler.class)); + assertThat(prov.getProviderClasspath()) + .hasSize(3) + .containsOnly(expectedProvider, expectedCommonJava5, expectedLauncher); + + assertThat(testClasspathWrapper.getTestDependencies()) + .hasSize(8) + .containsEntry("third.party:artifact", testClasspathSomeTestArtifact) + .containsEntry("org.junit.vintage:junit-vintage-engine", testClasspathVintage) + .containsEntry("org.apiguardian:apiguardian-api", testClasspathApiguardian) + .containsEntry("org.junit.platform:junit-platform-engine", testClasspathPlatformEng) + .containsEntry("junit:junit", testClasspathJUnit4) + .containsEntry("org.hamcrest:hamcrest-core", testClasspathHamcrest) + .containsEntry("org.opentest4j:opentest4j", testClasspathOpentest4j) + .containsEntry("org.junit.platform:junit-platform-commons", testClasspathCommons); } @Test - public void shouldSmartlyResolveJUnit5ProviderWithJUnit5Commons() throws Exception - { + public void shouldSmartlyResolveJUnit5ProviderWithJUnit5Commons() throws Exception { MavenProject mavenProject = new MavenProject(); - mavenProject.setArtifact( new DefaultArtifact( "dummy", "pom", createFromVersion( "1.0.0" ), - null, "jar", null, mock( ArtifactHandler.class ) ) ); - mojo.setProject( mavenProject ); - - final VersionRange surefireVersion = createFromVersion( "1" ); - - Artifact testClasspathSomeTestArtifact = new DefaultArtifact( "third.party", "artifact", - createFromVersion( "1.0" ), null, "jar", null, mock( ArtifactHandler.class ) ); - - Artifact testClasspathCommons = new DefaultArtifact( "org.junit.platform", "junit-platform-commons", - createFromVersion( "1.4.0" ), null, "jar", null, mock( ArtifactHandler.class ) ); - - Artifact testClasspathApiguardian = new DefaultArtifact( "org.apiguardian", "apiguardian-api", - createFromVersion( "1.0.0" ), null, "jar", null, mock( ArtifactHandler.class ) ); + mavenProject.setArtifact(new DefaultArtifact( + "dummy", "pom", createFromVersion("1.0.0"), null, "jar", null, mock(ArtifactHandler.class))); + mojo.setProject(mavenProject); + + final VersionRange surefireVersion = createFromVersion("1"); + + Artifact testClasspathSomeTestArtifact = new DefaultArtifact( + "third.party", "artifact", createFromVersion("1.0"), null, "jar", null, mock(ArtifactHandler.class)); + + Artifact testClasspathCommons = new DefaultArtifact( + "org.junit.platform", + "junit-platform-commons", + createFromVersion("1.4.0"), + null, + "jar", + null, + mock(ArtifactHandler.class)); + + Artifact testClasspathApiguardian = new DefaultArtifact( + "org.apiguardian", + "apiguardian-api", + createFromVersion("1.0.0"), + null, + "jar", + null, + mock(ArtifactHandler.class)); Collection testArtifacts = - asList( testClasspathSomeTestArtifact, testClasspathApiguardian, testClasspathCommons ); + asList(testClasspathSomeTestArtifact, testClasspathApiguardian, testClasspathCommons); - setProjectDepedenciesToMojo( testArtifacts.toArray( new Artifact[testArtifacts.size()] ) ); + setProjectDepedenciesToMojo(testArtifacts.toArray(new Artifact[testArtifacts.size()])); - File classesDirectory = new File( "target/classes" ); + File classesDirectory = new File("target/classes"); - File testClassesDirectory = new File( "target/test-classes" ); + File testClassesDirectory = new File("target/test-classes"); TestClassPath testClasspathWrapper = - new TestClassPath( testArtifacts, classesDirectory, testClassesDirectory, null ); - - mojo.setRemoteRepositories( Collections.emptyList() ); - mojo.setProjectRemoteRepositories( Collections.emptyList() ); - RepositorySystem repositorySystem = mock( RepositorySystem.class ); - final Artifact surefireProvider = new DefaultArtifact( "org.apache.maven.surefire", - "surefire-junit-platform", surefireVersion, null, "jar", null, mock( ArtifactHandler.class ) ); - when( repositorySystem.createDependencyArtifact( any( Dependency.class ) ) ).thenAnswer( new Answer() - { + new TestClassPath(testArtifacts, classesDirectory, testClassesDirectory, null); + + mojo.setRemoteRepositories(Collections.emptyList()); + mojo.setProjectRemoteRepositories(Collections.emptyList()); + RepositorySystem repositorySystem = mock(RepositorySystem.class); + final Artifact surefireProvider = new DefaultArtifact( + "org.apache.maven.surefire", + "surefire-junit-platform", + surefireVersion, + null, + "jar", + null, + mock(ArtifactHandler.class)); + when(repositorySystem.createDependencyArtifact(any(Dependency.class))).thenAnswer(new Answer() { @Override - public Artifact answer( InvocationOnMock invocation ) - { + public Artifact answer(InvocationOnMock invocation) { Dependency provider = (Dependency) invocation.getArguments()[0]; - assertThat( provider.getGroupId() ).isEqualTo( "org.apache.maven.surefire" ); - assertThat( provider.getArtifactId() ).isEqualTo( "surefire-junit-platform" ); + assertThat(provider.getGroupId()).isEqualTo("org.apache.maven.surefire"); + assertThat(provider.getArtifactId()).isEqualTo("surefire-junit-platform"); return surefireProvider; } - } ); - - when( repositorySystem.resolve( any( ArtifactResolutionRequest.class ) ) ) - .thenAnswer( new Answer() - { - @Override - public ArtifactResolutionResult answer( InvocationOnMock invocation ) - { - ArtifactResolutionRequest req = (ArtifactResolutionRequest) invocation.getArguments()[0]; - Artifact resolvable = req.getArtifact(); - if ( resolvable == surefireProvider ) - { - return createSurefireProviderResolutionResult( surefireVersion ); + }); + + when(repositorySystem.resolve(any(ArtifactResolutionRequest.class))) + .thenAnswer(new Answer() { + @Override + public ArtifactResolutionResult answer(InvocationOnMock invocation) { + ArtifactResolutionRequest req = + (ArtifactResolutionRequest) invocation.getArguments()[0]; + Artifact resolvable = req.getArtifact(); + if (resolvable == surefireProvider) { + return createSurefireProviderResolutionResult(surefireVersion); + } else if ("org.junit.platform".equals(resolvable.getGroupId()) + && "junit-platform-launcher".equals(resolvable.getArtifactId()) + && "1.4.0".equals(resolvable.getVersion())) { + return createExpectedJUnitPlatformLauncherResolutionResult(); + } else { + fail(resolvable.getGroupId() + ":" + resolvable.getArtifactId()); + return null; + } } - else if ( "org.junit.platform".equals( resolvable.getGroupId() ) - && "junit-platform-launcher".equals( resolvable.getArtifactId() ) - && "1.4.0".equals( resolvable.getVersion() ) ) - { - return createExpectedJUnitPlatformLauncherResolutionResult(); - } - else - { - fail( resolvable.getGroupId() + ":" + resolvable.getArtifactId() ); - return null; - } - } - } ); + }); - mojo.setRepositorySystem( repositorySystem ); - mojo.setLogger( mock( Logger.class ) ); + mojo.setRepositorySystem(repositorySystem); + mojo.setLogger(mock(Logger.class)); - invokeMethod( mojo, "setupStuff" ); + invokeMethod(mojo, "setupStuff"); - when( mojo.getSession().getProjectBuildingRequest() ) - .thenReturn( mock( ProjectBuildingRequest.class ) ); + when(mojo.getSession().getProjectBuildingRequest()).thenReturn(mock(ProjectBuildingRequest.class)); - PluginDescriptor pluginDescriptor = mock( PluginDescriptor.class ); - mojo.setPluginDescriptor( pluginDescriptor ); - Plugin p = mock( Plugin.class ); - when( pluginDescriptor.getPlugin() ) - .thenReturn( p ); - when( p.getDependencies() ) - .thenReturn( Collections.emptyList() ); + PluginDescriptor pluginDescriptor = mock(PluginDescriptor.class); + mojo.setPluginDescriptor(pluginDescriptor); + Plugin p = mock(Plugin.class); + when(pluginDescriptor.getPlugin()).thenReturn(p); + when(p.getDependencies()).thenReturn(Collections.emptyList()); - Artifact junitPlatformArtifact = invokeMethod( mojo, "getJUnit5Artifact" ); - assertThat( junitPlatformArtifact.getGroupId() ).isEqualTo( "org.junit.platform" ); - assertThat( junitPlatformArtifact.getArtifactId() ).isEqualTo( "junit-platform-commons" ); - assertThat( junitPlatformArtifact.getVersion() ).isEqualTo( "1.4.0" ); + Artifact junitPlatformArtifact = invokeMethod(mojo, "getJUnit5Artifact"); + assertThat(junitPlatformArtifact.getGroupId()).isEqualTo("org.junit.platform"); + assertThat(junitPlatformArtifact.getArtifactId()).isEqualTo("junit-platform-commons"); + assertThat(junitPlatformArtifact.getVersion()).isEqualTo("1.4.0"); JUnitPlatformProviderInfo prov = - mojo.createJUnitPlatformProviderInfo( junitPlatformArtifact, testClasspathWrapper ); + mojo.createJUnitPlatformProviderInfo(junitPlatformArtifact, testClasspathWrapper); - assertThat( prov.isApplicable() ) - .isTrue(); + assertThat(prov.isApplicable()).isTrue(); Set resolvedProviderArtifacts = prov.getProviderClasspath(); - Artifact provider = new DefaultArtifact( "org.apache.maven.surefire", "surefire-junit-platform", - surefireVersion, null, "jar", null, mock( ArtifactHandler.class ) ); - Artifact java5 = new DefaultArtifact( "org.apache.maven.surefire", "common-java5", - surefireVersion, null, "jar", null, mock( ArtifactHandler.class ) ); - Artifact launcher = new DefaultArtifact( "org.junit.platform", "junit-platform-launcher", - createFromVersion( "1.4.0" ), null, "jar", null, mock( ArtifactHandler.class ) ); - Artifact engine = new DefaultArtifact( "org.junit.platform", "junit-platform-engine", - createFromVersion( "1.4.0" ), null, "jar", null, mock( ArtifactHandler.class ) ); - Artifact opentest4j = new DefaultArtifact( "org.opentest4j", "opentest4j", - createFromVersion( "1.1.1" ), null, "jar", null, mock( ArtifactHandler.class ) ); - assertThat( resolvedProviderArtifacts ) - .hasSize( 5 ) - .containsOnly( provider, java5, launcher, engine, opentest4j ); - - assertThat( testClasspathWrapper.getTestDependencies() ) - .hasSize( 3 ) - .containsEntry( "third.party:artifact", testClasspathSomeTestArtifact ) - .containsEntry( "org.junit.platform:junit-platform-commons", testClasspathCommons ) - .containsEntry( "org.apiguardian:apiguardian-api", testClasspathApiguardian ); + Artifact provider = new DefaultArtifact( + "org.apache.maven.surefire", + "surefire-junit-platform", + surefireVersion, + null, + "jar", + null, + mock(ArtifactHandler.class)); + Artifact java5 = new DefaultArtifact( + "org.apache.maven.surefire", + "common-java5", + surefireVersion, + null, + "jar", + null, + mock(ArtifactHandler.class)); + Artifact launcher = new DefaultArtifact( + "org.junit.platform", + "junit-platform-launcher", + createFromVersion("1.4.0"), + null, + "jar", + null, + mock(ArtifactHandler.class)); + Artifact engine = new DefaultArtifact( + "org.junit.platform", + "junit-platform-engine", + createFromVersion("1.4.0"), + null, + "jar", + null, + mock(ArtifactHandler.class)); + Artifact opentest4j = new DefaultArtifact( + "org.opentest4j", + "opentest4j", + createFromVersion("1.1.1"), + null, + "jar", + null, + mock(ArtifactHandler.class)); + assertThat(resolvedProviderArtifacts).hasSize(5).containsOnly(provider, java5, launcher, engine, opentest4j); + + assertThat(testClasspathWrapper.getTestDependencies()) + .hasSize(3) + .containsEntry("third.party:artifact", testClasspathSomeTestArtifact) + .containsEntry("org.junit.platform:junit-platform-commons", testClasspathCommons) + .containsEntry("org.apiguardian:apiguardian-api", testClasspathApiguardian); } @Test - public void shouldSmartlyResolveJUnit5ProviderWithJUnit5Engine() throws Exception - { + public void shouldSmartlyResolveJUnit5ProviderWithJUnit5Engine() throws Exception { MavenProject mavenProject = new MavenProject(); - mavenProject.setArtifact( new DefaultArtifact( "dummy", "pom", createFromVersion( "1.0.0" ), - null, "jar", null, mock( ArtifactHandler.class ) ) ); - mojo.setProject( mavenProject ); - - final VersionRange surefireVersion = createFromVersion( "1" ); - - final Artifact testClasspathSomeTestArtifact = new DefaultArtifact( "third.party", "artifact", - createFromVersion( "1.0" ), null, "jar", null, mock( ArtifactHandler.class ) ); - - final Artifact testClasspathJUnit5 = new DefaultArtifact( "org.junit.platform", "junit-platform-engine", - createFromVersion( "1.4.0" ), null, "jar", null, mock( ArtifactHandler.class ) ); - - final Artifact testClasspathApiguardian = new DefaultArtifact( "org.apiguardian", "apiguardian-api", - createFromVersion( "1.0.0" ), null, "jar", null, mock( ArtifactHandler.class ) ); - - final Artifact testClasspathCommons = new DefaultArtifact( "org.junit.platform", "junit-platform-commons", - createFromVersion( "1.4.0" ), null, "jar", null, mock( ArtifactHandler.class ) ); - - final Artifact testClasspathOpentest4j = new DefaultArtifact( "org.opentest4j", "opentest4j", - createFromVersion( "1.1.1" ), null, "jar", null, mock( ArtifactHandler.class ) ); - - Collection testArtifacts = asList( testClasspathSomeTestArtifact, testClasspathJUnit5, - testClasspathApiguardian, testClasspathCommons, testClasspathOpentest4j ); - - setProjectDepedenciesToMojo( testArtifacts.toArray( new Artifact[testArtifacts.size()] ) ); - - File classesDirectory = new File( "target/classes" ); - - File testClassesDirectory = new File( "target/test-classes" ); + mavenProject.setArtifact(new DefaultArtifact( + "dummy", "pom", createFromVersion("1.0.0"), null, "jar", null, mock(ArtifactHandler.class))); + mojo.setProject(mavenProject); + + final VersionRange surefireVersion = createFromVersion("1"); + + final Artifact testClasspathSomeTestArtifact = new DefaultArtifact( + "third.party", "artifact", createFromVersion("1.0"), null, "jar", null, mock(ArtifactHandler.class)); + + final Artifact testClasspathJUnit5 = new DefaultArtifact( + "org.junit.platform", + "junit-platform-engine", + createFromVersion("1.4.0"), + null, + "jar", + null, + mock(ArtifactHandler.class)); + + final Artifact testClasspathApiguardian = new DefaultArtifact( + "org.apiguardian", + "apiguardian-api", + createFromVersion("1.0.0"), + null, + "jar", + null, + mock(ArtifactHandler.class)); + + final Artifact testClasspathCommons = new DefaultArtifact( + "org.junit.platform", + "junit-platform-commons", + createFromVersion("1.4.0"), + null, + "jar", + null, + mock(ArtifactHandler.class)); + + final Artifact testClasspathOpentest4j = new DefaultArtifact( + "org.opentest4j", + "opentest4j", + createFromVersion("1.1.1"), + null, + "jar", + null, + mock(ArtifactHandler.class)); + + Collection testArtifacts = asList( + testClasspathSomeTestArtifact, + testClasspathJUnit5, + testClasspathApiguardian, + testClasspathCommons, + testClasspathOpentest4j); + + setProjectDepedenciesToMojo(testArtifacts.toArray(new Artifact[testArtifacts.size()])); + + File classesDirectory = new File("target/classes"); + + File testClassesDirectory = new File("target/test-classes"); TestClassPath testClasspathWrapper = - new TestClassPath( testArtifacts, classesDirectory, testClassesDirectory, null ); - - mojo.setRemoteRepositories( Collections.emptyList() ); - mojo.setProjectRemoteRepositories( Collections.emptyList() ); - RepositorySystem repositorySystem = mock( RepositorySystem.class ); - final Artifact surefireProvider = new DefaultArtifact( "org.apache.maven.surefire", - "surefire-junit-platform", surefireVersion, null, "jar", null, mock( ArtifactHandler.class ) ); - when( repositorySystem.createDependencyArtifact( any( Dependency.class ) ) ).thenAnswer( new Answer() - { + new TestClassPath(testArtifacts, classesDirectory, testClassesDirectory, null); + + mojo.setRemoteRepositories(Collections.emptyList()); + mojo.setProjectRemoteRepositories(Collections.emptyList()); + RepositorySystem repositorySystem = mock(RepositorySystem.class); + final Artifact surefireProvider = new DefaultArtifact( + "org.apache.maven.surefire", + "surefire-junit-platform", + surefireVersion, + null, + "jar", + null, + mock(ArtifactHandler.class)); + when(repositorySystem.createDependencyArtifact(any(Dependency.class))).thenAnswer(new Answer() { @Override - public Artifact answer( InvocationOnMock invocation ) - { + public Artifact answer(InvocationOnMock invocation) { Dependency provider = (Dependency) invocation.getArguments()[0]; - assertThat( provider.getGroupId() ).isEqualTo( "org.apache.maven.surefire" ); - assertThat( provider.getArtifactId() ).isEqualTo( "surefire-junit-platform" ); + assertThat(provider.getGroupId()).isEqualTo("org.apache.maven.surefire"); + assertThat(provider.getArtifactId()).isEqualTo("surefire-junit-platform"); return surefireProvider; } - } ); - - when( repositorySystem.resolve( any( ArtifactResolutionRequest.class ) ) ) - .thenAnswer( new Answer() - { - @Override - public ArtifactResolutionResult answer( InvocationOnMock invocation ) - { - ArtifactResolutionRequest req = (ArtifactResolutionRequest) invocation.getArguments()[0]; - Artifact resolvable = req.getArtifact(); - if ( resolvable == surefireProvider ) - { - return createSurefireProviderResolutionResult( surefireVersion ); - } - else if ( "org.junit.platform".equals( resolvable.getGroupId() ) - && "junit-platform-launcher".equals( resolvable.getArtifactId() ) - && "1.4.0".equals( resolvable.getVersion() ) ) - { - return createExpectedJUnitPlatformLauncherResolutionResult(); + }); + + when(repositorySystem.resolve(any(ArtifactResolutionRequest.class))) + .thenAnswer(new Answer() { + @Override + public ArtifactResolutionResult answer(InvocationOnMock invocation) { + ArtifactResolutionRequest req = + (ArtifactResolutionRequest) invocation.getArguments()[0]; + Artifact resolvable = req.getArtifact(); + if (resolvable == surefireProvider) { + return createSurefireProviderResolutionResult(surefireVersion); + } else if ("org.junit.platform".equals(resolvable.getGroupId()) + && "junit-platform-launcher".equals(resolvable.getArtifactId()) + && "1.4.0".equals(resolvable.getVersion())) { + return createExpectedJUnitPlatformLauncherResolutionResult(); + } else { + fail(resolvable.getGroupId() + ":" + resolvable.getArtifactId()); + return null; + } } - else - { - fail( resolvable.getGroupId() + ":" + resolvable.getArtifactId() ); - return null; - } - } - } ); + }); - mojo.setRepositorySystem( repositorySystem ); - mojo.setLogger( mock( Logger.class ) ); + mojo.setRepositorySystem(repositorySystem); + mojo.setLogger(mock(Logger.class)); - invokeMethod( mojo, "setupStuff" ); + invokeMethod(mojo, "setupStuff"); - Artifact junitPlatformArtifact = invokeMethod( mojo, "getJUnit5Artifact" ); - assertThat( junitPlatformArtifact.getGroupId() ).isEqualTo( "org.junit.platform" ); - assertThat( junitPlatformArtifact.getArtifactId() ).isEqualTo( "junit-platform-commons" ); - assertThat( junitPlatformArtifact.getVersion() ).isEqualTo( "1.4.0" ); + Artifact junitPlatformArtifact = invokeMethod(mojo, "getJUnit5Artifact"); + assertThat(junitPlatformArtifact.getGroupId()).isEqualTo("org.junit.platform"); + assertThat(junitPlatformArtifact.getArtifactId()).isEqualTo("junit-platform-commons"); + assertThat(junitPlatformArtifact.getVersion()).isEqualTo("1.4.0"); JUnitPlatformProviderInfo prov = - mojo.createJUnitPlatformProviderInfo( junitPlatformArtifact, testClasspathWrapper ); + mojo.createJUnitPlatformProviderInfo(junitPlatformArtifact, testClasspathWrapper); - assertThat( prov.isApplicable() ) - .isTrue(); + assertThat(prov.isApplicable()).isTrue(); Set resolvedProviderArtifacts = prov.getProviderClasspath(); - Artifact java5 = new DefaultArtifact( "org.apache.maven.surefire", "common-java5", - surefireVersion, null, "jar", null, mock( ArtifactHandler.class ) ); - Artifact launcher = new DefaultArtifact( "org.junit.platform", "junit-platform-launcher", - createFromVersion( "1.4.0" ), null, "jar", null, mock( ArtifactHandler.class ) ); - assertThat( resolvedProviderArtifacts ) - .hasSize( 3 ) - .containsOnly( surefireProvider, java5, launcher ); - - assertThat( testClasspathWrapper.getTestDependencies() ) - .hasSize( 5 ) - .containsEntry( "third.party:artifact", testClasspathSomeTestArtifact ) - .containsEntry( "org.junit.platform:junit-platform-engine", testClasspathJUnit5 ) - .containsEntry( "org.apiguardian:apiguardian-api", testClasspathApiguardian ) - .containsEntry( "org.junit.platform:junit-platform-commons", testClasspathCommons ) - .containsEntry( "org.opentest4j:opentest4j", testClasspathOpentest4j ); + Artifact java5 = new DefaultArtifact( + "org.apache.maven.surefire", + "common-java5", + surefireVersion, + null, + "jar", + null, + mock(ArtifactHandler.class)); + Artifact launcher = new DefaultArtifact( + "org.junit.platform", + "junit-platform-launcher", + createFromVersion("1.4.0"), + null, + "jar", + null, + mock(ArtifactHandler.class)); + assertThat(resolvedProviderArtifacts).hasSize(3).containsOnly(surefireProvider, java5, launcher); + + assertThat(testClasspathWrapper.getTestDependencies()) + .hasSize(5) + .containsEntry("third.party:artifact", testClasspathSomeTestArtifact) + .containsEntry("org.junit.platform:junit-platform-engine", testClasspathJUnit5) + .containsEntry("org.apiguardian:apiguardian-api", testClasspathApiguardian) + .containsEntry("org.junit.platform:junit-platform-commons", testClasspathCommons) + .containsEntry("org.opentest4j:opentest4j", testClasspathOpentest4j); } @Test - public void shouldSmartlyResolveJUnit5ProviderWithJupiterApi() throws Exception - { + public void shouldSmartlyResolveJUnit5ProviderWithJupiterApi() throws Exception { MavenProject mavenProject = new MavenProject(); - mavenProject.setArtifact( new DefaultArtifact( "dummy", "pom", createFromVersion( "1.0.0" ), - null, "jar", null, mock( ArtifactHandler.class ) ) ); - mojo.setProject( mavenProject ); - - final VersionRange surefireVersion = createFromVersion( "1" ); - - final Artifact testClasspathSomeTestArtifact = new DefaultArtifact( "third.party", "artifact", - createFromVersion( "1.0" ), null, "jar", null, mock( ArtifactHandler.class ) ); - - final Artifact testClasspathJupiterApi = new DefaultArtifact( "org.junit.jupiter", "junit-jupiter-api", - createFromVersion( "5.4.0" ), null, "jar", null, mock( ArtifactHandler.class ) ); - - final Artifact testClasspathApiguardian = new DefaultArtifact( "org.apiguardian", "apiguardian-api", - createFromVersion( "1.0.0" ), null, "jar", null, mock( ArtifactHandler.class ) ); - - final Artifact testClasspathCommons = new DefaultArtifact( "org.junit.platform", "junit-platform-commons", - createFromVersion( "1.4.0" ), null, "jar", null, mock( ArtifactHandler.class ) ); - - final Artifact testClasspathOpentest4j = new DefaultArtifact( "org.opentest4j", "opentest4j", - createFromVersion( "1.1.1" ), null, "jar", null, mock( ArtifactHandler.class ) ); - - Collection testArtifacts = asList( testClasspathSomeTestArtifact, testClasspathJupiterApi, - testClasspathApiguardian, testClasspathCommons, testClasspathOpentest4j ); - - setProjectDepedenciesToMojo( testArtifacts.toArray( new Artifact[testArtifacts.size()] ) ); - - File classesDirectory = new File( "target/classes" ); - - File testClassesDirectory = new File( "target/test-classes" ); + mavenProject.setArtifact(new DefaultArtifact( + "dummy", "pom", createFromVersion("1.0.0"), null, "jar", null, mock(ArtifactHandler.class))); + mojo.setProject(mavenProject); + + final VersionRange surefireVersion = createFromVersion("1"); + + final Artifact testClasspathSomeTestArtifact = new DefaultArtifact( + "third.party", "artifact", createFromVersion("1.0"), null, "jar", null, mock(ArtifactHandler.class)); + + final Artifact testClasspathJupiterApi = new DefaultArtifact( + "org.junit.jupiter", + "junit-jupiter-api", + createFromVersion("5.4.0"), + null, + "jar", + null, + mock(ArtifactHandler.class)); + + final Artifact testClasspathApiguardian = new DefaultArtifact( + "org.apiguardian", + "apiguardian-api", + createFromVersion("1.0.0"), + null, + "jar", + null, + mock(ArtifactHandler.class)); + + final Artifact testClasspathCommons = new DefaultArtifact( + "org.junit.platform", + "junit-platform-commons", + createFromVersion("1.4.0"), + null, + "jar", + null, + mock(ArtifactHandler.class)); + + final Artifact testClasspathOpentest4j = new DefaultArtifact( + "org.opentest4j", + "opentest4j", + createFromVersion("1.1.1"), + null, + "jar", + null, + mock(ArtifactHandler.class)); + + Collection testArtifacts = asList( + testClasspathSomeTestArtifact, + testClasspathJupiterApi, + testClasspathApiguardian, + testClasspathCommons, + testClasspathOpentest4j); + + setProjectDepedenciesToMojo(testArtifacts.toArray(new Artifact[testArtifacts.size()])); + + File classesDirectory = new File("target/classes"); + + File testClassesDirectory = new File("target/test-classes"); TestClassPath testClasspathWrapper = - new TestClassPath( testArtifacts, classesDirectory, testClassesDirectory, null ); - - mojo.setRemoteRepositories( Collections.emptyList() ); - mojo.setProjectRemoteRepositories( Collections.emptyList() ); - RepositorySystem repositorySystem = mock( RepositorySystem.class ); - final Artifact surefireProvider = new DefaultArtifact( "org.apache.maven.surefire", - "surefire-junit-platform", surefireVersion, null, "jar", null, mock( ArtifactHandler.class ) ); - when( repositorySystem.createDependencyArtifact( any( Dependency.class ) ) ).thenAnswer( new Answer() - { + new TestClassPath(testArtifacts, classesDirectory, testClassesDirectory, null); + + mojo.setRemoteRepositories(Collections.emptyList()); + mojo.setProjectRemoteRepositories(Collections.emptyList()); + RepositorySystem repositorySystem = mock(RepositorySystem.class); + final Artifact surefireProvider = new DefaultArtifact( + "org.apache.maven.surefire", + "surefire-junit-platform", + surefireVersion, + null, + "jar", + null, + mock(ArtifactHandler.class)); + when(repositorySystem.createDependencyArtifact(any(Dependency.class))).thenAnswer(new Answer() { @Override - public Artifact answer( InvocationOnMock invocation ) - { + public Artifact answer(InvocationOnMock invocation) { Dependency provider = (Dependency) invocation.getArguments()[0]; - assertThat( provider.getGroupId() ).isEqualTo( "org.apache.maven.surefire" ); - assertThat( provider.getArtifactId() ).isEqualTo( "surefire-junit-platform" ); + assertThat(provider.getGroupId()).isEqualTo("org.apache.maven.surefire"); + assertThat(provider.getArtifactId()).isEqualTo("surefire-junit-platform"); return surefireProvider; } - } ); - - when( repositorySystem.resolve( any( ArtifactResolutionRequest.class ) ) ) - .thenAnswer( new Answer() - { - @Override - public ArtifactResolutionResult answer( InvocationOnMock invocation ) - { - ArtifactResolutionRequest req = (ArtifactResolutionRequest) invocation.getArguments()[0]; - Artifact resolvable = req.getArtifact(); - if ( resolvable == surefireProvider ) - { - return createSurefireProviderResolutionResult( surefireVersion ); - } - else if ( "org.junit.platform".equals( resolvable.getGroupId() ) - && "junit-platform-launcher".equals( resolvable.getArtifactId() ) - && "1.4.0".equals( resolvable.getVersion() ) ) - { - return createExpectedJUnitPlatformLauncherResolutionResult(); + }); + + when(repositorySystem.resolve(any(ArtifactResolutionRequest.class))) + .thenAnswer(new Answer() { + @Override + public ArtifactResolutionResult answer(InvocationOnMock invocation) { + ArtifactResolutionRequest req = + (ArtifactResolutionRequest) invocation.getArguments()[0]; + Artifact resolvable = req.getArtifact(); + if (resolvable == surefireProvider) { + return createSurefireProviderResolutionResult(surefireVersion); + } else if ("org.junit.platform".equals(resolvable.getGroupId()) + && "junit-platform-launcher".equals(resolvable.getArtifactId()) + && "1.4.0".equals(resolvable.getVersion())) { + return createExpectedJUnitPlatformLauncherResolutionResult(); + } else if ("org.junit.jupiter".equals(resolvable.getGroupId()) + && "junit-jupiter-engine".equals(resolvable.getArtifactId()) + && "5.4.0".equals(resolvable.getVersion())) { + return createJupiterEngineResolutionResult(); + } else { + fail(resolvable.getGroupId() + ":" + resolvable.getArtifactId()); + return null; + } } - else if ( "org.junit.jupiter".equals( resolvable.getGroupId() ) - && "junit-jupiter-engine".equals( resolvable.getArtifactId() ) - && "5.4.0".equals( resolvable.getVersion() ) ) - { - return createJupiterEngineResolutionResult(); - } - else - { - fail( resolvable.getGroupId() + ":" + resolvable.getArtifactId() ); - return null; - } - } - } ); + }); - mojo.setRepositorySystem( repositorySystem ); - mojo.setLogger( mock( Logger.class ) ); + mojo.setRepositorySystem(repositorySystem); + mojo.setLogger(mock(Logger.class)); - invokeMethod( mojo, "setupStuff" ); + invokeMethod(mojo, "setupStuff"); - when( mojo.getSession().getProjectBuildingRequest() ) - .thenReturn( mock( ProjectBuildingRequest.class ) ); + when(mojo.getSession().getProjectBuildingRequest()).thenReturn(mock(ProjectBuildingRequest.class)); - PluginDescriptor pluginDescriptor = mock( PluginDescriptor.class ); - mojo.setPluginDescriptor( pluginDescriptor ); - Plugin p = mock( Plugin.class ); - when( pluginDescriptor.getPlugin() ) - .thenReturn( p ); - when( p.getDependencies() ) - .thenReturn( Collections.emptyList() ); + PluginDescriptor pluginDescriptor = mock(PluginDescriptor.class); + mojo.setPluginDescriptor(pluginDescriptor); + Plugin p = mock(Plugin.class); + when(pluginDescriptor.getPlugin()).thenReturn(p); + when(p.getDependencies()).thenReturn(Collections.emptyList()); - Artifact junitPlatformArtifact = invokeMethod( mojo, "getJUnit5Artifact" ); - assertThat( junitPlatformArtifact.getGroupId() ).isEqualTo( "org.junit.platform" ); - assertThat( junitPlatformArtifact.getArtifactId() ).isEqualTo( "junit-platform-commons" ); - assertThat( junitPlatformArtifact.getVersion() ).isEqualTo( "1.4.0" ); + Artifact junitPlatformArtifact = invokeMethod(mojo, "getJUnit5Artifact"); + assertThat(junitPlatformArtifact.getGroupId()).isEqualTo("org.junit.platform"); + assertThat(junitPlatformArtifact.getArtifactId()).isEqualTo("junit-platform-commons"); + assertThat(junitPlatformArtifact.getVersion()).isEqualTo("1.4.0"); JUnitPlatformProviderInfo prov = - mojo.createJUnitPlatformProviderInfo( junitPlatformArtifact, testClasspathWrapper ); + mojo.createJUnitPlatformProviderInfo(junitPlatformArtifact, testClasspathWrapper); - assertThat( prov.isApplicable() ) - .isTrue(); + assertThat(prov.isApplicable()).isTrue(); Set resolvedProviderArtifacts = prov.getProviderClasspath(); - Artifact java5 = new DefaultArtifact( "org.apache.maven.surefire", "common-java5", - surefireVersion, null, "jar", null, mock( ArtifactHandler.class ) ); - Artifact launcher = new DefaultArtifact( "org.junit.platform", "junit-platform-launcher", - createFromVersion( "1.4.0" ), null, "jar", null, mock( ArtifactHandler.class ) ); - Artifact jupiterEngine = new DefaultArtifact( "org.junit.jupiter", "junit-jupiter-engine", - createFromVersion( "5.4.0" ), null, "jar", null, mock( ArtifactHandler.class ) ); - Artifact platformEngine = new DefaultArtifact( "org.junit.platform", "junit-platform-engine", - createFromVersion( "1.4.0" ), null, "jar", null, mock( ArtifactHandler.class ) ); - assertThat( resolvedProviderArtifacts ) - .hasSize( 5 ) - .containsOnly( surefireProvider, java5, launcher, jupiterEngine, platformEngine ); - - assertThat( testClasspathWrapper.getTestDependencies() ) - .hasSize( 5 ) - .containsEntry( "third.party:artifact", testClasspathSomeTestArtifact ) - .containsEntry( "org.junit.jupiter:junit-jupiter-api", testClasspathJupiterApi ) - .containsEntry( "org.apiguardian:apiguardian-api", testClasspathApiguardian ) - .containsEntry( "org.junit.platform:junit-platform-commons", testClasspathCommons ) - .containsEntry( "org.opentest4j:opentest4j", testClasspathOpentest4j ); + Artifact java5 = new DefaultArtifact( + "org.apache.maven.surefire", + "common-java5", + surefireVersion, + null, + "jar", + null, + mock(ArtifactHandler.class)); + Artifact launcher = new DefaultArtifact( + "org.junit.platform", + "junit-platform-launcher", + createFromVersion("1.4.0"), + null, + "jar", + null, + mock(ArtifactHandler.class)); + Artifact jupiterEngine = new DefaultArtifact( + "org.junit.jupiter", + "junit-jupiter-engine", + createFromVersion("5.4.0"), + null, + "jar", + null, + mock(ArtifactHandler.class)); + Artifact platformEngine = new DefaultArtifact( + "org.junit.platform", + "junit-platform-engine", + createFromVersion("1.4.0"), + null, + "jar", + null, + mock(ArtifactHandler.class)); + assertThat(resolvedProviderArtifacts) + .hasSize(5) + .containsOnly(surefireProvider, java5, launcher, jupiterEngine, platformEngine); + + assertThat(testClasspathWrapper.getTestDependencies()) + .hasSize(5) + .containsEntry("third.party:artifact", testClasspathSomeTestArtifact) + .containsEntry("org.junit.jupiter:junit-jupiter-api", testClasspathJupiterApi) + .containsEntry("org.apiguardian:apiguardian-api", testClasspathApiguardian) + .containsEntry("org.junit.platform:junit-platform-commons", testClasspathCommons) + .containsEntry("org.opentest4j:opentest4j", testClasspathOpentest4j); } @Test - public void shouldSmartlyResolveJUnit5ProviderWithJupiterEngine() throws Exception - { + public void shouldSmartlyResolveJUnit5ProviderWithJupiterEngine() throws Exception { MavenProject mavenProject = new MavenProject(); - mavenProject.setArtifact( new DefaultArtifact( "dummy", "pom", createFromVersion( "1.0.0" ), - null, "jar", null, mock( ArtifactHandler.class ) ) ); - mojo.setProject( mavenProject ); - - final VersionRange surefireVersion = createFromVersion( "1" ); - - final Artifact testClasspathSomeTestArtifact = new DefaultArtifact( "third.party", "artifact", - createFromVersion( "1.0" ), null, "jar", null, mock( ArtifactHandler.class ) ); - - final Artifact testClasspathJupiterEngine = new DefaultArtifact( "org.junit.jupiter", "junit-jupiter-engine", - createFromVersion( "5.4.0" ), null, "jar", null, mock( ArtifactHandler.class ) ); - - final Artifact testClasspathPlatformEngine = new DefaultArtifact( "org.junit.platform", "junit-platform-engine", - createFromVersion( "1.4.0" ), null, "jar", null, mock( ArtifactHandler.class ) ); - - final Artifact testClasspathJupiterApi = new DefaultArtifact( "org.junit.jupiter", "junit-jupiter-api", - createFromVersion( "5.4.0" ), null, "jar", null, mock( ArtifactHandler.class ) ); - - final Artifact testClasspathApiguardian = new DefaultArtifact( "org.apiguardian", "apiguardian-api", - createFromVersion( "1.0.0" ), null, "jar", null, mock( ArtifactHandler.class ) ); - - final Artifact testClasspathCommons = new DefaultArtifact( "org.junit.platform", "junit-platform-commons", - createFromVersion( "1.4.0" ), null, "jar", null, mock( ArtifactHandler.class ) ); - - final Artifact testClasspathOpentest4j = new DefaultArtifact( "org.opentest4j", "opentest4j", - createFromVersion( "1.1.1" ), null, "jar", null, mock( ArtifactHandler.class ) ); - - Collection testArtifacts = asList( testClasspathSomeTestArtifact, testClasspathJupiterEngine, - testClasspathPlatformEngine, testClasspathJupiterApi, testClasspathApiguardian, testClasspathCommons, - testClasspathOpentest4j ); - - setProjectDepedenciesToMojo( testArtifacts.toArray( new Artifact[testArtifacts.size()] ) ); - - File classesDirectory = new File( "target/classes" ); - - File testClassesDirectory = new File( "target/test-classes" ); + mavenProject.setArtifact(new DefaultArtifact( + "dummy", "pom", createFromVersion("1.0.0"), null, "jar", null, mock(ArtifactHandler.class))); + mojo.setProject(mavenProject); + + final VersionRange surefireVersion = createFromVersion("1"); + + final Artifact testClasspathSomeTestArtifact = new DefaultArtifact( + "third.party", "artifact", createFromVersion("1.0"), null, "jar", null, mock(ArtifactHandler.class)); + + final Artifact testClasspathJupiterEngine = new DefaultArtifact( + "org.junit.jupiter", + "junit-jupiter-engine", + createFromVersion("5.4.0"), + null, + "jar", + null, + mock(ArtifactHandler.class)); + + final Artifact testClasspathPlatformEngine = new DefaultArtifact( + "org.junit.platform", + "junit-platform-engine", + createFromVersion("1.4.0"), + null, + "jar", + null, + mock(ArtifactHandler.class)); + + final Artifact testClasspathJupiterApi = new DefaultArtifact( + "org.junit.jupiter", + "junit-jupiter-api", + createFromVersion("5.4.0"), + null, + "jar", + null, + mock(ArtifactHandler.class)); + + final Artifact testClasspathApiguardian = new DefaultArtifact( + "org.apiguardian", + "apiguardian-api", + createFromVersion("1.0.0"), + null, + "jar", + null, + mock(ArtifactHandler.class)); + + final Artifact testClasspathCommons = new DefaultArtifact( + "org.junit.platform", + "junit-platform-commons", + createFromVersion("1.4.0"), + null, + "jar", + null, + mock(ArtifactHandler.class)); + + final Artifact testClasspathOpentest4j = new DefaultArtifact( + "org.opentest4j", + "opentest4j", + createFromVersion("1.1.1"), + null, + "jar", + null, + mock(ArtifactHandler.class)); + + Collection testArtifacts = asList( + testClasspathSomeTestArtifact, + testClasspathJupiterEngine, + testClasspathPlatformEngine, + testClasspathJupiterApi, + testClasspathApiguardian, + testClasspathCommons, + testClasspathOpentest4j); + + setProjectDepedenciesToMojo(testArtifacts.toArray(new Artifact[testArtifacts.size()])); + + File classesDirectory = new File("target/classes"); + + File testClassesDirectory = new File("target/test-classes"); TestClassPath testClasspathWrapper = - new TestClassPath( testArtifacts, classesDirectory, testClassesDirectory, null ); - - mojo.setRemoteRepositories( Collections.emptyList() ); - mojo.setProjectRemoteRepositories( Collections.emptyList() ); - RepositorySystem repositorySystem = mock( RepositorySystem.class ); - final Artifact surefireProvider = new DefaultArtifact( "org.apache.maven.surefire", - "surefire-junit-platform", surefireVersion, null, "jar", null, mock( ArtifactHandler.class ) ); - when( repositorySystem.createDependencyArtifact( any( Dependency.class ) ) ).thenAnswer( new Answer() - { + new TestClassPath(testArtifacts, classesDirectory, testClassesDirectory, null); + + mojo.setRemoteRepositories(Collections.emptyList()); + mojo.setProjectRemoteRepositories(Collections.emptyList()); + RepositorySystem repositorySystem = mock(RepositorySystem.class); + final Artifact surefireProvider = new DefaultArtifact( + "org.apache.maven.surefire", + "surefire-junit-platform", + surefireVersion, + null, + "jar", + null, + mock(ArtifactHandler.class)); + when(repositorySystem.createDependencyArtifact(any(Dependency.class))).thenAnswer(new Answer() { @Override - public Artifact answer( InvocationOnMock invocation ) - { + public Artifact answer(InvocationOnMock invocation) { Dependency provider = (Dependency) invocation.getArguments()[0]; - assertThat( provider.getGroupId() ).isEqualTo( "org.apache.maven.surefire" ); - assertThat( provider.getArtifactId() ).isEqualTo( "surefire-junit-platform" ); + assertThat(provider.getGroupId()).isEqualTo("org.apache.maven.surefire"); + assertThat(provider.getArtifactId()).isEqualTo("surefire-junit-platform"); return surefireProvider; } - } ); - - when( repositorySystem.resolve( any( ArtifactResolutionRequest.class ) ) ) - .thenAnswer( new Answer() - { - @Override - public ArtifactResolutionResult answer( InvocationOnMock invocation ) - { - ArtifactResolutionRequest req = (ArtifactResolutionRequest) invocation.getArguments()[0]; - Artifact resolvable = req.getArtifact(); - if ( resolvable == surefireProvider ) - { - return createSurefireProviderResolutionResult( surefireVersion ); - } - else if ( "org.junit.platform".equals( resolvable.getGroupId() ) - && "junit-platform-launcher".equals( resolvable.getArtifactId() ) - && "1.4.0".equals( resolvable.getVersion() ) ) - { - return createExpectedJUnitPlatformLauncherResolutionResult(); - } - else - { - fail( resolvable.getGroupId() + ":" + resolvable.getArtifactId() ); - return null; + }); + + when(repositorySystem.resolve(any(ArtifactResolutionRequest.class))) + .thenAnswer(new Answer() { + @Override + public ArtifactResolutionResult answer(InvocationOnMock invocation) { + ArtifactResolutionRequest req = + (ArtifactResolutionRequest) invocation.getArguments()[0]; + Artifact resolvable = req.getArtifact(); + if (resolvable == surefireProvider) { + return createSurefireProviderResolutionResult(surefireVersion); + } else if ("org.junit.platform".equals(resolvable.getGroupId()) + && "junit-platform-launcher".equals(resolvable.getArtifactId()) + && "1.4.0".equals(resolvable.getVersion())) { + return createExpectedJUnitPlatformLauncherResolutionResult(); + } else { + fail(resolvable.getGroupId() + ":" + resolvable.getArtifactId()); + return null; + } } - } - } ); + }); - mojo.setRepositorySystem( repositorySystem ); - mojo.setLogger( mock( Logger.class ) ); + mojo.setRepositorySystem(repositorySystem); + mojo.setLogger(mock(Logger.class)); - invokeMethod( mojo, "setupStuff" ); + invokeMethod(mojo, "setupStuff"); - Artifact junitPlatformArtifact = invokeMethod( mojo, "getJUnit5Artifact" ); - assertThat( junitPlatformArtifact.getGroupId() ).isEqualTo( "org.junit.platform" ); - assertThat( junitPlatformArtifact.getArtifactId() ).isEqualTo( "junit-platform-commons" ); - assertThat( junitPlatformArtifact.getVersion() ).isEqualTo( "1.4.0" ); + Artifact junitPlatformArtifact = invokeMethod(mojo, "getJUnit5Artifact"); + assertThat(junitPlatformArtifact.getGroupId()).isEqualTo("org.junit.platform"); + assertThat(junitPlatformArtifact.getArtifactId()).isEqualTo("junit-platform-commons"); + assertThat(junitPlatformArtifact.getVersion()).isEqualTo("1.4.0"); JUnitPlatformProviderInfo prov = - mojo.createJUnitPlatformProviderInfo( junitPlatformArtifact, testClasspathWrapper ); + mojo.createJUnitPlatformProviderInfo(junitPlatformArtifact, testClasspathWrapper); - assertThat( prov.isApplicable() ) - .isTrue(); + assertThat(prov.isApplicable()).isTrue(); Set resolvedProviderArtifacts = prov.getProviderClasspath(); - Artifact java5 = new DefaultArtifact( "org.apache.maven.surefire", "common-java5", - surefireVersion, null, "jar", null, mock( ArtifactHandler.class ) ); - Artifact launcher = new DefaultArtifact( "org.junit.platform", "junit-platform-launcher", - createFromVersion( "1.4.0" ), null, "jar", null, mock( ArtifactHandler.class ) ); - assertThat( resolvedProviderArtifacts ) - .hasSize( 3 ) - .containsOnly( surefireProvider, java5, launcher ); - - assertThat( testClasspathWrapper.getTestDependencies() ) - .hasSize( 7 ) - .containsEntry( "third.party:artifact", testClasspathSomeTestArtifact ) - .containsEntry( "org.junit.jupiter:junit-jupiter-engine", testClasspathJupiterEngine ) - .containsEntry( "org.junit.platform:junit-platform-engine", testClasspathPlatformEngine ) - .containsEntry( "org.junit.jupiter:junit-jupiter-api", testClasspathJupiterApi ) - .containsEntry( "org.apiguardian:apiguardian-api", testClasspathApiguardian ) - .containsEntry( "org.junit.platform:junit-platform-commons", testClasspathCommons ) - .containsEntry( "org.opentest4j:opentest4j", testClasspathOpentest4j ); + Artifact java5 = new DefaultArtifact( + "org.apache.maven.surefire", + "common-java5", + surefireVersion, + null, + "jar", + null, + mock(ArtifactHandler.class)); + Artifact launcher = new DefaultArtifact( + "org.junit.platform", + "junit-platform-launcher", + createFromVersion("1.4.0"), + null, + "jar", + null, + mock(ArtifactHandler.class)); + assertThat(resolvedProviderArtifacts).hasSize(3).containsOnly(surefireProvider, java5, launcher); + + assertThat(testClasspathWrapper.getTestDependencies()) + .hasSize(7) + .containsEntry("third.party:artifact", testClasspathSomeTestArtifact) + .containsEntry("org.junit.jupiter:junit-jupiter-engine", testClasspathJupiterEngine) + .containsEntry("org.junit.platform:junit-platform-engine", testClasspathPlatformEngine) + .containsEntry("org.junit.jupiter:junit-jupiter-api", testClasspathJupiterApi) + .containsEntry("org.apiguardian:apiguardian-api", testClasspathApiguardian) + .containsEntry("org.junit.platform:junit-platform-commons", testClasspathCommons) + .containsEntry("org.opentest4j:opentest4j", testClasspathOpentest4j); } @Test - public void shouldSmartlyResolveJUnit5ProviderWithJupiterEngineInPluginDependencies() throws Exception - { - final VersionRange surefireVersion = createFromVersion( "1" ); - - final Artifact plugin = new DefaultArtifact( "org.apache.maven.surefire", "maven-surefire-plugin", - surefireVersion, null, "jar", null, mock( ArtifactHandler.class ) ); - - final Artifact forkedBooter = new DefaultArtifact( "org.apache.maven.surefire", - "surefire-booter", surefireVersion, null, "jar", null, mock( ArtifactHandler.class ) ); - - final Artifact pluginDepJupiterEngine = new DefaultArtifact( "org.junit.jupiter", "junit-jupiter-engine", - createFromVersion( "5.4.0" ), null, "jar", null, mock( ArtifactHandler.class ) ); - - final Artifact pluginDepPlatformEngine = new DefaultArtifact( "org.junit.platform", "junit-platform-engine", - createFromVersion( "1.4.0" ), null, "jar", null, mock( ArtifactHandler.class ) ); - - final Artifact pluginDepJupiterApi = new DefaultArtifact( "org.junit.jupiter", "junit-jupiter-api", - createFromVersion( "5.4.0" ), null, "jar", null, mock( ArtifactHandler.class ) ); - - final Artifact pluginDepApiguardian = new DefaultArtifact( "org.apiguardian", "apiguardian-api", - createFromVersion( "1.0.0" ), null, "jar", null, mock( ArtifactHandler.class ) ); - - final Artifact pluginDepCommons = new DefaultArtifact( "org.junit.platform", "junit-platform-commons", - createFromVersion( "1.4.0" ), null, "jar", null, mock( ArtifactHandler.class ) ); - - final Artifact pluginDepOpentest4j = new DefaultArtifact( "org.opentest4j", "opentest4j", - createFromVersion( "1.1.1" ), null, "jar", null, mock( ArtifactHandler.class ) ); - - mojo.getPluginArtifactMap().put( "org.apache.maven.surefire:maven-surefire-plugin", plugin ); - mojo.getPluginArtifactMap().put( "org.apache.maven.surefire:surefire-booter", forkedBooter ); - mojo.getPluginArtifactMap().put( "org.junit.jupiter:junit-jupiter-engine", pluginDepJupiterEngine ); - mojo.getPluginArtifactMap().put( "org.junit.platform:junit-platform-engine", pluginDepPlatformEngine ); - mojo.getPluginArtifactMap().put( "org.junit.jupiter:junit-jupiter-api", pluginDepJupiterApi ); - mojo.getPluginArtifactMap().put( "org.apiguardian:apiguardian-api", pluginDepApiguardian ); - mojo.getPluginArtifactMap().put( "org.junit.platform:junit-platform-commons", pluginDepCommons ); - mojo.getPluginArtifactMap().put( "org.opentest4j:opentest4j", pluginDepOpentest4j ); + public void shouldSmartlyResolveJUnit5ProviderWithJupiterEngineInPluginDependencies() throws Exception { + final VersionRange surefireVersion = createFromVersion("1"); + + final Artifact plugin = new DefaultArtifact( + "org.apache.maven.surefire", + "maven-surefire-plugin", + surefireVersion, + null, + "jar", + null, + mock(ArtifactHandler.class)); + + final Artifact forkedBooter = new DefaultArtifact( + "org.apache.maven.surefire", + "surefire-booter", + surefireVersion, + null, + "jar", + null, + mock(ArtifactHandler.class)); + + final Artifact pluginDepJupiterEngine = new DefaultArtifact( + "org.junit.jupiter", + "junit-jupiter-engine", + createFromVersion("5.4.0"), + null, + "jar", + null, + mock(ArtifactHandler.class)); + + final Artifact pluginDepPlatformEngine = new DefaultArtifact( + "org.junit.platform", + "junit-platform-engine", + createFromVersion("1.4.0"), + null, + "jar", + null, + mock(ArtifactHandler.class)); + + final Artifact pluginDepJupiterApi = new DefaultArtifact( + "org.junit.jupiter", + "junit-jupiter-api", + createFromVersion("5.4.0"), + null, + "jar", + null, + mock(ArtifactHandler.class)); + + final Artifact pluginDepApiguardian = new DefaultArtifact( + "org.apiguardian", + "apiguardian-api", + createFromVersion("1.0.0"), + null, + "jar", + null, + mock(ArtifactHandler.class)); + + final Artifact pluginDepCommons = new DefaultArtifact( + "org.junit.platform", + "junit-platform-commons", + createFromVersion("1.4.0"), + null, + "jar", + null, + mock(ArtifactHandler.class)); + + final Artifact pluginDepOpentest4j = new DefaultArtifact( + "org.opentest4j", + "opentest4j", + createFromVersion("1.1.1"), + null, + "jar", + null, + mock(ArtifactHandler.class)); + + mojo.getPluginArtifactMap().put("org.apache.maven.surefire:maven-surefire-plugin", plugin); + mojo.getPluginArtifactMap().put("org.apache.maven.surefire:surefire-booter", forkedBooter); + mojo.getPluginArtifactMap().put("org.junit.jupiter:junit-jupiter-engine", pluginDepJupiterEngine); + mojo.getPluginArtifactMap().put("org.junit.platform:junit-platform-engine", pluginDepPlatformEngine); + mojo.getPluginArtifactMap().put("org.junit.jupiter:junit-jupiter-api", pluginDepJupiterApi); + mojo.getPluginArtifactMap().put("org.apiguardian:apiguardian-api", pluginDepApiguardian); + mojo.getPluginArtifactMap().put("org.junit.platform:junit-platform-commons", pluginDepCommons); + mojo.getPluginArtifactMap().put("org.opentest4j:opentest4j", pluginDepOpentest4j); MavenProject mavenProject = new MavenProject(); - mavenProject.setArtifact( new DefaultArtifact( "dummy", "pom", createFromVersion( "1.0.0" ), - null, "jar", null, mock( ArtifactHandler.class ) ) ); - mojo.setProject( mavenProject ); - - final Artifact testClasspathSomeTestArtifact = new DefaultArtifact( "third.party", "artifact", - createFromVersion( "1.0" ), null, "jar", null, mock( ArtifactHandler.class ) ); - - final Artifact testClasspathJupiterApi = new DefaultArtifact( "org.junit.jupiter", "junit-jupiter-api", - createFromVersion( "5.3.0" ), null, "jar", null, mock( ArtifactHandler.class ) ); - - final Artifact testClasspathApiguardian = new DefaultArtifact( "org.apiguardian", "apiguardian-api", - createFromVersion( "1.0.0" ), null, "jar", null, mock( ArtifactHandler.class ) ); - - final Artifact testClasspathCommons = new DefaultArtifact( "org.junit.platform", "junit-platform-commons", - createFromVersion( "1.4.0" ), null, "jar", null, mock( ArtifactHandler.class ) ); - - final Artifact testClasspathOpentest4j = new DefaultArtifact( "org.opentest4j", "opentest4j", - createFromVersion( "1.1.1" ), null, "jar", null, mock( ArtifactHandler.class ) ); - - Collection testArtifacts = asList( testClasspathSomeTestArtifact, testClasspathJupiterApi, - testClasspathApiguardian, testClasspathCommons, testClasspathOpentest4j ); - - setProjectDepedenciesToMojo( testArtifacts.toArray( new Artifact[testArtifacts.size()] ) ); - - File classesDirectory = new File( "target/classes" ); - - File testClassesDirectory = new File( "target/test-classes" ); + mavenProject.setArtifact(new DefaultArtifact( + "dummy", "pom", createFromVersion("1.0.0"), null, "jar", null, mock(ArtifactHandler.class))); + mojo.setProject(mavenProject); + + final Artifact testClasspathSomeTestArtifact = new DefaultArtifact( + "third.party", "artifact", createFromVersion("1.0"), null, "jar", null, mock(ArtifactHandler.class)); + + final Artifact testClasspathJupiterApi = new DefaultArtifact( + "org.junit.jupiter", + "junit-jupiter-api", + createFromVersion("5.3.0"), + null, + "jar", + null, + mock(ArtifactHandler.class)); + + final Artifact testClasspathApiguardian = new DefaultArtifact( + "org.apiguardian", + "apiguardian-api", + createFromVersion("1.0.0"), + null, + "jar", + null, + mock(ArtifactHandler.class)); + + final Artifact testClasspathCommons = new DefaultArtifact( + "org.junit.platform", + "junit-platform-commons", + createFromVersion("1.4.0"), + null, + "jar", + null, + mock(ArtifactHandler.class)); + + final Artifact testClasspathOpentest4j = new DefaultArtifact( + "org.opentest4j", + "opentest4j", + createFromVersion("1.1.1"), + null, + "jar", + null, + mock(ArtifactHandler.class)); + + Collection testArtifacts = asList( + testClasspathSomeTestArtifact, + testClasspathJupiterApi, + testClasspathApiguardian, + testClasspathCommons, + testClasspathOpentest4j); + + setProjectDepedenciesToMojo(testArtifacts.toArray(new Artifact[testArtifacts.size()])); + + File classesDirectory = new File("target/classes"); + + File testClassesDirectory = new File("target/test-classes"); TestClassPath testClasspathWrapper = - new TestClassPath( testArtifacts, classesDirectory, testClassesDirectory, null ); - - mojo.setRemoteRepositories( Collections.emptyList() ); - mojo.setProjectRemoteRepositories( Collections.emptyList() ); - RepositorySystem repositorySystem = mock( RepositorySystem.class ); - - final Artifact surefireProvider = new DefaultArtifact( "org.apache.maven.surefire", - "surefire-junit-platform", surefireVersion, null, "jar", null, mock( ArtifactHandler.class ) ); - when( repositorySystem.createDependencyArtifact( any( Dependency.class ) ) ).thenAnswer( new Answer() - { + new TestClassPath(testArtifacts, classesDirectory, testClassesDirectory, null); + + mojo.setRemoteRepositories(Collections.emptyList()); + mojo.setProjectRemoteRepositories(Collections.emptyList()); + RepositorySystem repositorySystem = mock(RepositorySystem.class); + + final Artifact surefireProvider = new DefaultArtifact( + "org.apache.maven.surefire", + "surefire-junit-platform", + surefireVersion, + null, + "jar", + null, + mock(ArtifactHandler.class)); + when(repositorySystem.createDependencyArtifact(any(Dependency.class))).thenAnswer(new Answer() { @Override - public Artifact answer( InvocationOnMock invocation ) - { + public Artifact answer(InvocationOnMock invocation) { Dependency dependency = (Dependency) invocation.getArguments()[0]; - if ( dependency.getArtifactId().equals( "surefire-junit-platform" ) ) - { + if (dependency.getArtifactId().equals("surefire-junit-platform")) { return surefireProvider; - } - else if ( dependency.getArtifactId().equals( "junit-jupiter-engine" ) ) - { + } else if (dependency.getArtifactId().equals("junit-jupiter-engine")) { return pluginDepJupiterEngine; - } - else - { - fail( dependency.getGroupId() + ":" + dependency.getArtifactId() ); + } else { + fail(dependency.getGroupId() + ":" + dependency.getArtifactId()); return null; } } - } ); - - final ArtifactResolutionResult pluginDepJupiterEngineResolutionResult = mock( ArtifactResolutionResult.class ); - - when( repositorySystem.resolve( any( ArtifactResolutionRequest.class ) ) ) - .thenAnswer( new Answer() - { - @Override - public ArtifactResolutionResult answer( InvocationOnMock invocation ) - { - ArtifactResolutionRequest req = (ArtifactResolutionRequest) invocation.getArguments()[0]; - Artifact resolvable = req.getArtifact(); - if ( resolvable == surefireProvider ) - { - return createSurefireProviderResolutionResult( surefireVersion ); - } - else if ( resolvable == pluginDepJupiterEngine ) - { - return pluginDepJupiterEngineResolutionResult; - } - else if ( "org.junit.platform".equals( resolvable.getGroupId() ) - && "junit-platform-launcher".equals( resolvable.getArtifactId() ) - && "1.4.0".equals( resolvable.getVersion() ) ) - { - return createExpectedJUnitPlatformLauncherResolutionResult(); + }); + + final ArtifactResolutionResult pluginDepJupiterEngineResolutionResult = mock(ArtifactResolutionResult.class); + + when(repositorySystem.resolve(any(ArtifactResolutionRequest.class))) + .thenAnswer(new Answer() { + @Override + public ArtifactResolutionResult answer(InvocationOnMock invocation) { + ArtifactResolutionRequest req = + (ArtifactResolutionRequest) invocation.getArguments()[0]; + Artifact resolvable = req.getArtifact(); + if (resolvable == surefireProvider) { + return createSurefireProviderResolutionResult(surefireVersion); + } else if (resolvable == pluginDepJupiterEngine) { + return pluginDepJupiterEngineResolutionResult; + } else if ("org.junit.platform".equals(resolvable.getGroupId()) + && "junit-platform-launcher".equals(resolvable.getArtifactId()) + && "1.4.0".equals(resolvable.getVersion())) { + return createExpectedJUnitPlatformLauncherResolutionResult(); + } else { + fail(resolvable.getGroupId() + ":" + resolvable.getArtifactId()); + return null; + } } - else - { - fail( resolvable.getGroupId() + ":" + resolvable.getArtifactId() ); - return null; - } - } - } ); + }); - mojo.setRepositorySystem( repositorySystem ); - mojo.setLogger( mock( Logger.class ) ); + mojo.setRepositorySystem(repositorySystem); + mojo.setLogger(mock(Logger.class)); Set pluginDepJupiterEngineArtifacts = new HashSet<>(); - pluginDepJupiterEngineArtifacts.add( pluginDepJupiterEngine ); - pluginDepJupiterEngineArtifacts.add( pluginDepPlatformEngine ); - pluginDepJupiterEngineArtifacts.add( pluginDepJupiterApi ); - pluginDepJupiterEngineArtifacts.add( pluginDepApiguardian ); - pluginDepJupiterEngineArtifacts.add( pluginDepCommons ); - pluginDepJupiterEngineArtifacts.add( pluginDepOpentest4j ); + pluginDepJupiterEngineArtifacts.add(pluginDepJupiterEngine); + pluginDepJupiterEngineArtifacts.add(pluginDepPlatformEngine); + pluginDepJupiterEngineArtifacts.add(pluginDepJupiterApi); + pluginDepJupiterEngineArtifacts.add(pluginDepApiguardian); + pluginDepJupiterEngineArtifacts.add(pluginDepCommons); + pluginDepJupiterEngineArtifacts.add(pluginDepOpentest4j); - when( pluginDepJupiterEngineResolutionResult.getArtifacts() ).thenReturn( pluginDepJupiterEngineArtifacts ); + when(pluginDepJupiterEngineResolutionResult.getArtifacts()).thenReturn(pluginDepJupiterEngineArtifacts); - invokeMethod( mojo, "setupStuff" ); + invokeMethod(mojo, "setupStuff"); - Artifact junitPlatformArtifact = invokeMethod( mojo, "getJUnit5Artifact" ); - assertThat( junitPlatformArtifact.getGroupId() ).isEqualTo( "org.junit.platform" ); - assertThat( junitPlatformArtifact.getArtifactId() ).isEqualTo( "junit-platform-engine" ); - assertThat( junitPlatformArtifact.getVersion() ).isEqualTo( "1.4.0" ); + Artifact junitPlatformArtifact = invokeMethod(mojo, "getJUnit5Artifact"); + assertThat(junitPlatformArtifact.getGroupId()).isEqualTo("org.junit.platform"); + assertThat(junitPlatformArtifact.getArtifactId()).isEqualTo("junit-platform-engine"); + assertThat(junitPlatformArtifact.getVersion()).isEqualTo("1.4.0"); JUnitPlatformProviderInfo prov = - mojo.createJUnitPlatformProviderInfo( junitPlatformArtifact, testClasspathWrapper ); + mojo.createJUnitPlatformProviderInfo(junitPlatformArtifact, testClasspathWrapper); - assertThat( prov.isApplicable() ) - .isTrue(); + assertThat(prov.isApplicable()).isTrue(); - when( mojo.getSession().getProjectBuildingRequest() ) - .thenReturn( mock( ProjectBuildingRequest.class ) ); + when(mojo.getSession().getProjectBuildingRequest()).thenReturn(mock(ProjectBuildingRequest.class)); - PluginDescriptor pluginDescriptor = mock( PluginDescriptor.class ); - mojo.setPluginDescriptor( pluginDescriptor ); - Plugin p = mock( Plugin.class ); - when( pluginDescriptor.getPlugin() ) - .thenReturn( p ); - List directPluginDependencies = toDependencies( pluginDepJupiterEngine ); - when( p.getDependencies() ) - .thenReturn( directPluginDependencies ); + PluginDescriptor pluginDescriptor = mock(PluginDescriptor.class); + mojo.setPluginDescriptor(pluginDescriptor); + Plugin p = mock(Plugin.class); + when(pluginDescriptor.getPlugin()).thenReturn(p); + List directPluginDependencies = toDependencies(pluginDepJupiterEngine); + when(p.getDependencies()).thenReturn(directPluginDependencies); Set resolvedProviderArtifacts = prov.getProviderClasspath(); - Artifact java5 = new DefaultArtifact( "org.apache.maven.surefire", "common-java5", - surefireVersion, null, "jar", null, mock( ArtifactHandler.class ) ); - Artifact launcher = new DefaultArtifact( "org.junit.platform", "junit-platform-launcher", - createFromVersion( "1.4.0" ), null, "jar", null, mock( ArtifactHandler.class ) ); - Artifact jupiterEngine = new DefaultArtifact( "org.junit.jupiter", "junit-jupiter-engine", - createFromVersion( "5.4.0" ), null, "jar", null, mock( ArtifactHandler.class ) ); - Artifact platformEngine = new DefaultArtifact( "org.junit.platform", "junit-platform-engine", - createFromVersion( "1.4.0" ), null, "jar", null, mock( ArtifactHandler.class ) ); - assertThat( resolvedProviderArtifacts ) - .hasSize( 5 ) - .containsOnly( surefireProvider, java5, launcher, jupiterEngine, platformEngine ); - - assertThat( testClasspathWrapper.getTestDependencies() ) - .hasSize( 5 ) - .containsEntry( "third.party:artifact", testClasspathSomeTestArtifact ) - .containsEntry( "org.junit.jupiter:junit-jupiter-api", testClasspathJupiterApi ) - .containsEntry( "org.apiguardian:apiguardian-api", testClasspathApiguardian ) - .containsEntry( "org.junit.platform:junit-platform-commons", testClasspathCommons ) - .containsEntry( "org.opentest4j:opentest4j", testClasspathOpentest4j ); + Artifact java5 = new DefaultArtifact( + "org.apache.maven.surefire", + "common-java5", + surefireVersion, + null, + "jar", + null, + mock(ArtifactHandler.class)); + Artifact launcher = new DefaultArtifact( + "org.junit.platform", + "junit-platform-launcher", + createFromVersion("1.4.0"), + null, + "jar", + null, + mock(ArtifactHandler.class)); + Artifact jupiterEngine = new DefaultArtifact( + "org.junit.jupiter", + "junit-jupiter-engine", + createFromVersion("5.4.0"), + null, + "jar", + null, + mock(ArtifactHandler.class)); + Artifact platformEngine = new DefaultArtifact( + "org.junit.platform", + "junit-platform-engine", + createFromVersion("1.4.0"), + null, + "jar", + null, + mock(ArtifactHandler.class)); + assertThat(resolvedProviderArtifacts) + .hasSize(5) + .containsOnly(surefireProvider, java5, launcher, jupiterEngine, platformEngine); + + assertThat(testClasspathWrapper.getTestDependencies()) + .hasSize(5) + .containsEntry("third.party:artifact", testClasspathSomeTestArtifact) + .containsEntry("org.junit.jupiter:junit-jupiter-api", testClasspathJupiterApi) + .containsEntry("org.apiguardian:apiguardian-api", testClasspathApiguardian) + .containsEntry("org.junit.platform:junit-platform-commons", testClasspathCommons) + .containsEntry("org.opentest4j:opentest4j", testClasspathOpentest4j); } @Test - public void shouldConvertJunitEngineParameters() throws Exception - { + public void shouldConvertJunitEngineParameters() throws Exception { Properties properties = new Properties(); - setInternalState( mojo, "properties", properties ); + setInternalState(mojo, "properties", properties); - invokeMethod( mojo, "convertJunitEngineParameters" ); - assertThat( properties ).isEmpty(); + invokeMethod(mojo, "convertJunitEngineParameters"); + assertThat(properties).isEmpty(); - mojo.setIncludeJUnit5Engines( new String[0] ); - mojo.setExcludeJUnit5Engines( new String[0] ); - invokeMethod( mojo, "convertJunitEngineParameters" ); - assertThat( properties ).isEmpty(); + mojo.setIncludeJUnit5Engines(new String[0]); + mojo.setExcludeJUnit5Engines(new String[0]); + invokeMethod(mojo, "convertJunitEngineParameters"); + assertThat(properties).isEmpty(); - mojo.setIncludeJUnit5Engines( new String[] {"e1", "e2"} ); - invokeMethod( mojo, "convertJunitEngineParameters" ); - assertThat( properties ) - .containsEntry( "includejunit5engines", "e1,e2" ); + mojo.setIncludeJUnit5Engines(new String[] {"e1", "e2"}); + invokeMethod(mojo, "convertJunitEngineParameters"); + assertThat(properties).containsEntry("includejunit5engines", "e1,e2"); - mojo.setExcludeJUnit5Engines( new String[] {"e1", "e2"} ); - invokeMethod( mojo, "convertJunitEngineParameters" ); - assertThat( properties ) - .containsEntry( "excludejunit5engines", "e1,e2" ); + mojo.setExcludeJUnit5Engines(new String[] {"e1", "e2"}); + invokeMethod(mojo, "convertJunitEngineParameters"); + assertThat(properties).containsEntry("excludejunit5engines", "e1,e2"); } private static ArtifactResolutionResult createJUnitPlatformLauncherResolutionResult( - Artifact junit5Engine, Artifact apiguardian, Artifact commons, Artifact opentest4j ) - { - ArtifactResolutionResult launcherResolutionResult = mock( ArtifactResolutionResult.class ); + Artifact junit5Engine, Artifact apiguardian, Artifact commons, Artifact opentest4j) { + ArtifactResolutionResult launcherResolutionResult = mock(ArtifactResolutionResult.class); Set resolvedLauncherArtifacts = new HashSet<>(); - Artifact launcher = new DefaultArtifact( "org.junit.platform", "junit-platform-launcher", - commons.getVersionRange(), null, "jar", null, mock( ArtifactHandler.class ) ); - resolvedLauncherArtifacts.add( launcher ); - resolvedLauncherArtifacts.add( apiguardian ); - resolvedLauncherArtifacts.add( junit5Engine ); - resolvedLauncherArtifacts.add( commons ); - resolvedLauncherArtifacts.add( opentest4j ); - resolvedLauncherArtifacts.remove( null ); - when( launcherResolutionResult.getArtifacts() ) - .thenReturn( resolvedLauncherArtifacts ); + Artifact launcher = new DefaultArtifact( + "org.junit.platform", + "junit-platform-launcher", + commons.getVersionRange(), + null, + "jar", + null, + mock(ArtifactHandler.class)); + resolvedLauncherArtifacts.add(launcher); + resolvedLauncherArtifacts.add(apiguardian); + resolvedLauncherArtifacts.add(junit5Engine); + resolvedLauncherArtifacts.add(commons); + resolvedLauncherArtifacts.add(opentest4j); + resolvedLauncherArtifacts.remove(null); + when(launcherResolutionResult.getArtifacts()).thenReturn(resolvedLauncherArtifacts); return launcherResolutionResult; } - private static ArtifactResolutionResult createJupiterEngineResolutionResult() - { - ArtifactResolutionResult launcherResolutionResult = mock( ArtifactResolutionResult.class ); + private static ArtifactResolutionResult createJupiterEngineResolutionResult() { + ArtifactResolutionResult launcherResolutionResult = mock(ArtifactResolutionResult.class); Set resolvedLauncherArtifacts = new HashSet<>(); - resolvedLauncherArtifacts.add( new DefaultArtifact( "org.junit.jupiter", "junit-jupiter-engine", - createFromVersion( "5.4.0" ), null, "jar", null, mock( ArtifactHandler.class ) ) ); - resolvedLauncherArtifacts.add( new DefaultArtifact( "org.junit.jupiter", "junit-jupiter-api", - createFromVersion( "5.4.0" ), null, "jar", null, mock( ArtifactHandler.class ) ) ); - resolvedLauncherArtifacts.add( new DefaultArtifact( "org.junit.platform", "junit-platform-engine", - createFromVersion( "1.4.0" ), null, "jar", null, mock( ArtifactHandler.class ) ) ); - resolvedLauncherArtifacts.add( new DefaultArtifact( "org.apiguardian", "apiguardian-api", - createFromVersion( "1.0.0" ), null, "jar", null, mock( ArtifactHandler.class ) ) ); - resolvedLauncherArtifacts.add( new DefaultArtifact( "org.opentest4j", "opentest4j", - createFromVersion( "1.1.1" ), null, "jar", null, mock( ArtifactHandler.class ) ) ); - resolvedLauncherArtifacts.add( new DefaultArtifact( "org.junit.platform", "junit-platform-commons", - createFromVersion( "1.4.0" ), null, "jar", null, mock( ArtifactHandler.class ) ) ); - when( launcherResolutionResult.getArtifacts() ) - .thenReturn( resolvedLauncherArtifacts ); + resolvedLauncherArtifacts.add(new DefaultArtifact( + "org.junit.jupiter", + "junit-jupiter-engine", + createFromVersion("5.4.0"), + null, + "jar", + null, + mock(ArtifactHandler.class))); + resolvedLauncherArtifacts.add(new DefaultArtifact( + "org.junit.jupiter", + "junit-jupiter-api", + createFromVersion("5.4.0"), + null, + "jar", + null, + mock(ArtifactHandler.class))); + resolvedLauncherArtifacts.add(new DefaultArtifact( + "org.junit.platform", + "junit-platform-engine", + createFromVersion("1.4.0"), + null, + "jar", + null, + mock(ArtifactHandler.class))); + resolvedLauncherArtifacts.add(new DefaultArtifact( + "org.apiguardian", + "apiguardian-api", + createFromVersion("1.0.0"), + null, + "jar", + null, + mock(ArtifactHandler.class))); + resolvedLauncherArtifacts.add(new DefaultArtifact( + "org.opentest4j", + "opentest4j", + createFromVersion("1.1.1"), + null, + "jar", + null, + mock(ArtifactHandler.class))); + resolvedLauncherArtifacts.add(new DefaultArtifact( + "org.junit.platform", + "junit-platform-commons", + createFromVersion("1.4.0"), + null, + "jar", + null, + mock(ArtifactHandler.class))); + when(launcherResolutionResult.getArtifacts()).thenReturn(resolvedLauncherArtifacts); return launcherResolutionResult; } - private static ArtifactResolutionResult createExpectedJUnitPlatformLauncherResolutionResult() - { - Artifact engine = new DefaultArtifact( "org.junit.platform", "junit-platform-engine", - createFromVersion( "1.4.0" ), null, "jar", null, mock( ArtifactHandler.class ) ); - Artifact commons = new DefaultArtifact( "org.junit.platform", "junit-platform-commons", - createFromVersion( "1.4.0" ), null, "jar", null, mock( ArtifactHandler.class ) ); - Artifact apiguardian = new DefaultArtifact( "org.apiguardian", "apiguardian-api", - createFromVersion( "1.0.0" ), null, "jar", null, mock( ArtifactHandler.class ) ); - Artifact opentest4j = new DefaultArtifact( "org.opentest4j", "opentest4j", - createFromVersion( "1.1.1" ), null, "jar", null, mock( ArtifactHandler.class ) ); - return createJUnitPlatformLauncherResolutionResult( engine, apiguardian, commons, opentest4j ); + private static ArtifactResolutionResult createExpectedJUnitPlatformLauncherResolutionResult() { + Artifact engine = new DefaultArtifact( + "org.junit.platform", + "junit-platform-engine", + createFromVersion("1.4.0"), + null, + "jar", + null, + mock(ArtifactHandler.class)); + Artifact commons = new DefaultArtifact( + "org.junit.platform", + "junit-platform-commons", + createFromVersion("1.4.0"), + null, + "jar", + null, + mock(ArtifactHandler.class)); + Artifact apiguardian = new DefaultArtifact( + "org.apiguardian", + "apiguardian-api", + createFromVersion("1.0.0"), + null, + "jar", + null, + mock(ArtifactHandler.class)); + Artifact opentest4j = new DefaultArtifact( + "org.opentest4j", + "opentest4j", + createFromVersion("1.1.1"), + null, + "jar", + null, + mock(ArtifactHandler.class)); + return createJUnitPlatformLauncherResolutionResult(engine, apiguardian, commons, opentest4j); } - private static ArtifactResolutionResult createSurefireProviderResolutionResult( VersionRange surefireVersion ) - { - ArtifactResolutionResult surefirePlatformResolutionResult = mock( ArtifactResolutionResult.class ); - - Artifact provider = new DefaultArtifact( "org.apache.maven.surefire", "surefire-junit-platform", - surefireVersion, null, "jar", null, mock( ArtifactHandler.class ) ); - Artifact java5 = new DefaultArtifact( "org.apache.maven.surefire", "common-java5", - surefireVersion, null, "jar", null, mock( ArtifactHandler.class ) ); - Artifact launcher = new DefaultArtifact( "org.junit.platform", "junit-platform-launcher", - createFromVersion( "1.3.2" ), null, "jar", null, mock( ArtifactHandler.class ) ); - Artifact apiguardian = new DefaultArtifact( "org.apiguardian", "apiguardian-api", - createFromVersion( "1.0.0" ), null, "jar", null, mock( ArtifactHandler.class ) ); - Artifact engine = new DefaultArtifact( "org.junit.platform", "junit-platform-engine", - createFromVersion( "1.3.2" ), null, "jar", null, mock( ArtifactHandler.class ) ); - Artifact commons = new DefaultArtifact( "org.junit.platform", "junit-platform-commons", - createFromVersion( "1.3.2" ), null, "jar", null, mock( ArtifactHandler.class ) ); - Artifact opentest4j = new DefaultArtifact( "org.opentest4j", "opentest4j", - createFromVersion( "1.1.1" ), null, "jar", null, mock( ArtifactHandler.class ) ); + private static ArtifactResolutionResult createSurefireProviderResolutionResult(VersionRange surefireVersion) { + ArtifactResolutionResult surefirePlatformResolutionResult = mock(ArtifactResolutionResult.class); + + Artifact provider = new DefaultArtifact( + "org.apache.maven.surefire", + "surefire-junit-platform", + surefireVersion, + null, + "jar", + null, + mock(ArtifactHandler.class)); + Artifact java5 = new DefaultArtifact( + "org.apache.maven.surefire", + "common-java5", + surefireVersion, + null, + "jar", + null, + mock(ArtifactHandler.class)); + Artifact launcher = new DefaultArtifact( + "org.junit.platform", + "junit-platform-launcher", + createFromVersion("1.3.2"), + null, + "jar", + null, + mock(ArtifactHandler.class)); + Artifact apiguardian = new DefaultArtifact( + "org.apiguardian", + "apiguardian-api", + createFromVersion("1.0.0"), + null, + "jar", + null, + mock(ArtifactHandler.class)); + Artifact engine = new DefaultArtifact( + "org.junit.platform", + "junit-platform-engine", + createFromVersion("1.3.2"), + null, + "jar", + null, + mock(ArtifactHandler.class)); + Artifact commons = new DefaultArtifact( + "org.junit.platform", + "junit-platform-commons", + createFromVersion("1.3.2"), + null, + "jar", + null, + mock(ArtifactHandler.class)); + Artifact opentest4j = new DefaultArtifact( + "org.opentest4j", + "opentest4j", + createFromVersion("1.1.1"), + null, + "jar", + null, + mock(ArtifactHandler.class)); Set providerArtifacts = new HashSet<>(); - providerArtifacts.add( provider ); - providerArtifacts.add( java5 ); - providerArtifacts.add( launcher ); - providerArtifacts.add( apiguardian ); - providerArtifacts.add( engine ); - providerArtifacts.add( commons ); - providerArtifacts.add( opentest4j ); - - when( surefirePlatformResolutionResult.getArtifacts() ) - .thenReturn( providerArtifacts ); + providerArtifacts.add(provider); + providerArtifacts.add(java5); + providerArtifacts.add(launcher); + providerArtifacts.add(apiguardian); + providerArtifacts.add(engine); + providerArtifacts.add(commons); + providerArtifacts.add(opentest4j); + + when(surefirePlatformResolutionResult.getArtifacts()).thenReturn(providerArtifacts); return surefirePlatformResolutionResult; } @Test - public void shouldVerifyConfigParameters() throws Exception - { - Mojo mojo = new Mojo() - { + public void shouldVerifyConfigParameters() throws Exception { + Mojo mojo = new Mojo() { @Override - public File getTestClassesDirectory() - { - return new File( System.getProperty( "user.dir" ), "target/test-classes" ); + public File getTestClassesDirectory() { + return new File(System.getProperty("user.dir"), "target/test-classes"); } @Override - protected String getEnableProcessChecker() - { + protected String getEnableProcessChecker() { return "fake"; } }; - e.expect( MojoFailureException.class ); - e.expectMessage( "Unexpected value 'fake' in the configuration parameter 'enableProcessChecker'." ); + e.expect(MojoFailureException.class); + e.expectMessage("Unexpected value 'fake' in the configuration parameter 'enableProcessChecker'."); mojo.verifyParameters(); } - private void setProjectDepedenciesToMojo( Artifact... deps ) - { - for ( Artifact dep : deps ) - { - mojo.getProjectArtifactMap() - .put( dep.getGroupId() + ":" + dep.getArtifactId(), dep ); + private void setProjectDepedenciesToMojo(Artifact... deps) { + for (Artifact dep : deps) { + mojo.getProjectArtifactMap().put(dep.getGroupId() + ":" + dep.getArtifactId(), dep); } } - private void addPluginDependencies( Artifact... deps ) - { - for ( Artifact dep : deps ) - { - mojo.getPluginArtifactMap() - .put( dep.getGroupId() + ":" + dep.getArtifactId(), dep ); + private void addPluginDependencies(Artifact... deps) { + for (Artifact dep : deps) { + mojo.getPluginArtifactMap().put(dep.getGroupId() + ":" + dep.getArtifactId(), dep); } } /** * */ - public static class Mojo - extends AbstractSurefireMojo implements SurefireReportParameters - { + public static class Mojo extends AbstractSurefireMojo implements SurefireReportParameters { private File mainBuildPath; private File testClassesDirectory; private boolean useModulePath; @@ -2005,687 +2589,547 @@ public static class Mojo private String test; private boolean testFailureIgnore; - private JUnitPlatformProviderInfo createJUnitPlatformProviderInfo( Artifact junitPlatformArtifact, - TestClassPath testClasspathWrapper ) - { - return new JUnitPlatformProviderInfo( null, junitPlatformArtifact, testClasspathWrapper ); + private JUnitPlatformProviderInfo createJUnitPlatformProviderInfo( + Artifact junitPlatformArtifact, TestClassPath testClasspathWrapper) { + return new JUnitPlatformProviderInfo(null, junitPlatformArtifact, testClasspathWrapper); } - void setProjectTestArtifacts( List projectTestArtifacts ) - { + void setProjectTestArtifacts(List projectTestArtifacts) { this.projectTestArtifacts = projectTestArtifacts; } @Override - List getProjectTestArtifacts() - { + List getProjectTestArtifacts() { return projectTestArtifacts; } @Override - protected void logDebugOrCliShowErrors( String s ) - { + protected void logDebugOrCliShowErrors(String s) { // do nothing } @Override - protected String getPluginName() - { + protected String getPluginName() { return null; } @Override - protected int getRerunFailingTestsCount() - { + protected int getRerunFailingTestsCount() { return 0; } @Override - public boolean isSkipTests() - { + public boolean isSkipTests() { return false; } @Override - public void setSkipTests( boolean skipTests ) - { - - } + public void setSkipTests(boolean skipTests) {} @Override - public boolean isSkipExec() - { + public boolean isSkipExec() { return false; } @Override - public void setSkipExec( boolean skipExec ) - { - - } + public void setSkipExec(boolean skipExec) {} @Override - public boolean isSkip() - { + public boolean isSkip() { return false; } @Override - public void setSkip( boolean skip ) - { - - } + public void setSkip(boolean skip) {} @Override - public boolean isTestFailureIgnore() - { + public boolean isTestFailureIgnore() { return testFailureIgnore; } @Override - public void setTestFailureIgnore( boolean testFailureIgnore ) - { + public void setTestFailureIgnore(boolean testFailureIgnore) { this.testFailureIgnore = testFailureIgnore; } @Override - public File getBasedir() - { + public File getBasedir() { return null; } @Override - public void setBasedir( File basedir ) - { - - } + public void setBasedir(File basedir) {} @Override - public File getTestClassesDirectory() - { + public File getTestClassesDirectory() { return testClassesDirectory; } @Override - public void setTestClassesDirectory( File testClassesDirectory ) - { + public void setTestClassesDirectory(File testClassesDirectory) { this.testClassesDirectory = testClassesDirectory; } @Override - public File getMainBuildPath() - { + public File getMainBuildPath() { return mainBuildPath; } @Override - public void setMainBuildPath( File mainBuildPath ) - { + public void setMainBuildPath(File mainBuildPath) { this.mainBuildPath = mainBuildPath; } @Override - public File getReportsDirectory() - { + public File getReportsDirectory() { return null; } @Override - public void setReportsDirectory( File reportsDirectory ) - { - - } + public void setReportsDirectory(File reportsDirectory) {} @Override - public String getTest() - { + public String getTest() { return test; } @Override - public void setTest( String test ) - { + public void setTest(String test) { this.test = test; } @Override - public List getIncludes() - { + public List getIncludes() { return includes; } @Override - public void setIncludes( List includes ) - { + public void setIncludes(List includes) { this.includes = includes; } - void setIncludesFile( File includesFile ) - { + void setIncludesFile(File includesFile) { this.includesFile = includesFile; } @Override - public File getIncludesFile() - { + public File getIncludesFile() { return includesFile; } @Override - public List getExcludes() - { + public List getExcludes() { return excludes; } @Override - public void setExcludes( List excludes ) - { + public void setExcludes(List excludes) { this.excludes = excludes; } @Override - public boolean isPrintSummary() - { + public boolean isPrintSummary() { return false; } @Override - public void setPrintSummary( boolean printSummary ) - { - - } + public void setPrintSummary(boolean printSummary) {} @Override - public String getReportFormat() - { + public String getReportFormat() { return null; } @Override - public void setReportFormat( String reportFormat ) - { - - } + public void setReportFormat(String reportFormat) {} @Override - public boolean isUseFile() - { + public boolean isUseFile() { return false; } @Override - public void setUseFile( boolean useFile ) - { - - } + public void setUseFile(boolean useFile) {} @Override - public String getDebugForkedProcess() - { + public String getDebugForkedProcess() { return null; } @Override - public void setDebugForkedProcess( String debugForkedProcess ) - { - - } + public void setDebugForkedProcess(String debugForkedProcess) {} @Override - public int getForkedProcessTimeoutInSeconds() - { + public int getForkedProcessTimeoutInSeconds() { return 0; } @Override - public void setForkedProcessTimeoutInSeconds( int forkedProcessTimeoutInSeconds ) - { - - } + public void setForkedProcessTimeoutInSeconds(int forkedProcessTimeoutInSeconds) {} @Override - public int getForkedProcessExitTimeoutInSeconds() - { + public int getForkedProcessExitTimeoutInSeconds() { return 0; } @Override - public void setForkedProcessExitTimeoutInSeconds( int forkedProcessTerminationTimeoutInSeconds ) - { - - } + public void setForkedProcessExitTimeoutInSeconds(int forkedProcessTerminationTimeoutInSeconds) {} @Override - public double getParallelTestsTimeoutInSeconds() - { + public double getParallelTestsTimeoutInSeconds() { return 0; } @Override - public void setParallelTestsTimeoutInSeconds( double parallelTestsTimeoutInSeconds ) - { - - } + public void setParallelTestsTimeoutInSeconds(double parallelTestsTimeoutInSeconds) {} @Override - public double getParallelTestsTimeoutForcedInSeconds() - { + public double getParallelTestsTimeoutForcedInSeconds() { return 0; } @Override - public void setParallelTestsTimeoutForcedInSeconds( double parallelTestsTimeoutForcedInSeconds ) - { - - } + public void setParallelTestsTimeoutForcedInSeconds(double parallelTestsTimeoutForcedInSeconds) {} @Override - public boolean isUseSystemClassLoader() - { + public boolean isUseSystemClassLoader() { return false; } @Override - public void setUseSystemClassLoader( boolean useSystemClassLoader ) - { - - } + public void setUseSystemClassLoader(boolean useSystemClassLoader) {} @Override - public boolean isUseManifestOnlyJar() - { + public boolean isUseManifestOnlyJar() { return false; } @Override - public void setUseManifestOnlyJar( boolean useManifestOnlyJar ) - { - - } + public void setUseManifestOnlyJar(boolean useManifestOnlyJar) {} @Override - public String getEncoding() - { + public String getEncoding() { return null; } @Override - public void setEncoding( String encoding ) - { - - } + public void setEncoding(String encoding) {} @Override - public boolean getFailIfNoSpecifiedTests() - { + public boolean getFailIfNoSpecifiedTests() { return false; } @Override - public void setFailIfNoSpecifiedTests( boolean failIfNoSpecifiedTests ) - { - - } + public void setFailIfNoSpecifiedTests(boolean failIfNoSpecifiedTests) {} @Override - public int getSkipAfterFailureCount() - { + public int getSkipAfterFailureCount() { return 0; } @Override - public String getShutdown() - { + public String getShutdown() { return null; } - void setExcludesFile( File excludesFile ) - { + void setExcludesFile(File excludesFile) { this.excludesFile = excludesFile; } @Override - public File getExcludesFile() - { + public File getExcludesFile() { return excludesFile; } @Override - protected List suiteXmlFiles() - { + protected List suiteXmlFiles() { return null; } @Override - protected boolean hasSuiteXmlFiles() - { + protected boolean hasSuiteXmlFiles() { return false; } @Override - protected String[] getExcludedEnvironmentVariables() - { + protected String[] getExcludedEnvironmentVariables() { return new String[0]; } @Override - public File[] getSuiteXmlFiles() - { + public File[] getSuiteXmlFiles() { return new File[0]; } @Override - public void setSuiteXmlFiles( File[] suiteXmlFiles ) - { - - } + public void setSuiteXmlFiles(File[] suiteXmlFiles) {} @Override - public String getRunOrder() - { + public String getRunOrder() { return null; } @Override - public void setRunOrder( String runOrder ) - { - - } + public void setRunOrder(String runOrder) {} @Override - public Long getRunOrderRandomSeed() - { + public Long getRunOrderRandomSeed() { return null; } @Override - public void setRunOrderRandomSeed( Long runOrderRandomSeed ) - { - - } + public void setRunOrderRandomSeed(Long runOrderRandomSeed) {} @Override - protected void handleSummary( RunResult summary, Exception firstForkException ) - { - - } + protected void handleSummary(RunResult summary, Exception firstForkException) {} @Override - protected boolean isSkipExecution() - { + protected boolean isSkipExecution() { return false; } @Override - protected String[] getDefaultIncludes() - { + protected String[] getDefaultIncludes() { return new String[0]; } @Override - protected String getReportSchemaLocation() - { + protected String getReportSchemaLocation() { return null; } @Override - protected boolean useModulePath() - { + protected boolean useModulePath() { return useModulePath; } @Override - protected void setUseModulePath( boolean useModulePath ) - { + protected void setUseModulePath(boolean useModulePath) { this.useModulePath = useModulePath; } @Override - protected String getEnableProcessChecker() - { + protected String getEnableProcessChecker() { return null; } @Override - protected ForkNodeFactory getForkNode() - { + protected ForkNodeFactory getForkNode() { return null; } @Override - protected Artifact getMojoArtifact() - { - return new DefaultArtifact( "org.apache.maven.surefire", "maven-surefire-plugin", createFromVersion( "1" ), - null, "jar", null, mock( ArtifactHandler.class ) ); + protected Artifact getMojoArtifact() { + return new DefaultArtifact( + "org.apache.maven.surefire", + "maven-surefire-plugin", + createFromVersion("1"), + null, + "jar", + null, + mock(ArtifactHandler.class)); } @Override - public File getSystemPropertiesFile() - { + public File getSystemPropertiesFile() { return null; } @Override - public void setSystemPropertiesFile( File systemPropertiesFile ) - { - - } + public void setSystemPropertiesFile(File systemPropertiesFile) {} - public void setToolchain( Toolchain toolchain ) - { - setInternalState( this, "toolchain", toolchain ); + public void setToolchain(Toolchain toolchain) { + setInternalState(this, "toolchain", toolchain); } - public void setJvm( String jvm ) - { - setInternalState( this, "jvm", jvm ); + public void setJvm(String jvm) { + setInternalState(this, "jvm", jvm); } @Override - public int getFailOnFlakeCount() - { + public int getFailOnFlakeCount() { return failOnFlakeCount; } @Override - public void setFailOnFlakeCount( int failOnFlakeCount ) - { + public void setFailOnFlakeCount(int failOnFlakeCount) { this.failOnFlakeCount = failOnFlakeCount; } @Override - public String[] getIncludeJUnit5Engines() - { + public String[] getIncludeJUnit5Engines() { return includeJUnit5Engines; } @Override - public void setIncludeJUnit5Engines( String[] includeJUnit5Engines ) - { + public void setIncludeJUnit5Engines(String[] includeJUnit5Engines) { this.includeJUnit5Engines = includeJUnit5Engines; } @Override - public String[] getExcludeJUnit5Engines() - { + public String[] getExcludeJUnit5Engines() { return excludeJUnit5Engines; } @Override - public void setExcludeJUnit5Engines( String[] excludeJUnit5Engines ) - { + public void setExcludeJUnit5Engines(String[] excludeJUnit5Engines) { this.excludeJUnit5Engines = excludeJUnit5Engines; } } @Test - public void shouldNotPerformMethodFilteringOnIncludes() throws Exception - { + public void shouldNotPerformMethodFilteringOnIncludes() throws Exception { Mojo plugin = new Mojo(); - File includesExcludes = SureFireFileManager.createTempFile( "surefire", "includes" ); - FileUtils.write( includesExcludes, "AnotherTest#method" , UTF_8 ); - plugin.setIncludesFile( includesExcludes ); + File includesExcludes = SureFireFileManager.createTempFile("surefire", "includes"); + FileUtils.write(includesExcludes, "AnotherTest#method", UTF_8); + plugin.setIncludesFile(includesExcludes); List includes = new LinkedList<>(); - includes.add( "AnotherTest#method " ); - plugin.setIncludes( includes ); + includes.add("AnotherTest#method "); + plugin.setIncludes(includes); - VersionRange version = VersionRange.createFromVersion( "1.0" ); + VersionRange version = VersionRange.createFromVersion("1.0"); ArtifactHandler handler = new DefaultArtifactHandler(); - Artifact testDeps = new DefaultArtifact( "g", "a", version, "compile", "jar", null, handler ); - File artifactFile = SureFireFileManager.createTempFile( "surefire", ".jar" ); + Artifact testDeps = new DefaultArtifact("g", "a", version, "compile", "jar", null, handler); + File artifactFile = SureFireFileManager.createTempFile("surefire", ".jar"); artifactFile.deleteOnExit(); - testDeps.setFile( artifactFile ); - plugin.setProjectTestArtifacts( singletonList( testDeps ) ); - plugin.setDependenciesToScan( new String[] { "g:a" } ); + testDeps.setFile(artifactFile); + plugin.setProjectTestArtifacts(singletonList(testDeps)); + plugin.setDependenciesToScan(new String[] {"g:a"}); - e.expectMessage( "Method filter prohibited in includes|excludes parameter: AnotherTest#method " ); + e.expectMessage("Method filter prohibited in includes|excludes parameter: AnotherTest#method "); plugin.scanDependencies(); } @Test - public void shouldFilterTestsOnIncludesFile() throws Exception - { + public void shouldFilterTestsOnIncludesFile() throws Exception { Mojo plugin = new Mojo(); - plugin.setLogger( mock( Logger.class ) ); + plugin.setLogger(mock(Logger.class)); - File includes = SureFireFileManager.createTempFile( "surefire", "includes" ); - FileUtils.write( includes, "AnotherTest#method" , UTF_8 ); - plugin.setIncludesFile( includes ); + File includes = SureFireFileManager.createTempFile("surefire", "includes"); + FileUtils.write(includes, "AnotherTest#method", UTF_8); + plugin.setIncludesFile(includes); - VersionRange version = VersionRange.createFromVersion( "1.0" ); + VersionRange version = VersionRange.createFromVersion("1.0"); ArtifactHandler handler = new DefaultArtifactHandler(); - Artifact testDeps = new DefaultArtifact( "g", "a", version, "compile", "test-jar", null, handler ); - File artifactFile = SureFireFileManager.createTempFile( "surefire", "classes" ); + Artifact testDeps = new DefaultArtifact("g", "a", version, "compile", "test-jar", null, handler); + File artifactFile = SureFireFileManager.createTempFile("surefire", "classes"); String classDir = artifactFile.getCanonicalPath(); - assertThat( artifactFile.delete() ).isTrue(); - File classes = new File( classDir ); - assertThat( classes.mkdir() ).isTrue(); - testDeps.setFile( classes ); - assertThat( new File( classes, "AnotherTest.class" ).createNewFile() ) - .isTrue(); - plugin.setProjectTestArtifacts( singletonList( testDeps ) ); - plugin.setDependenciesToScan( new String[] { "g:a" } ); + assertThat(artifactFile.delete()).isTrue(); + File classes = new File(classDir); + assertThat(classes.mkdir()).isTrue(); + testDeps.setFile(classes); + assertThat(new File(classes, "AnotherTest.class").createNewFile()).isTrue(); + plugin.setProjectTestArtifacts(singletonList(testDeps)); + plugin.setDependenciesToScan(new String[] {"g:a"}); DefaultScanResult result = plugin.scanDependencies(); - assertThat ( result.getClasses() ).hasSize( 1 ); - assertThat ( result.getClasses().iterator().next() ).isEqualTo( "AnotherTest" ); + assertThat(result.getClasses()).hasSize(1); + assertThat(result.getClasses().iterator().next()).isEqualTo("AnotherTest"); } @Test - public void shouldFilterTestsOnExcludesFile() throws Exception - { + public void shouldFilterTestsOnExcludesFile() throws Exception { Mojo plugin = new Mojo(); - plugin.setLogger( mock( Logger.class ) ); + plugin.setLogger(mock(Logger.class)); - File excludes = SureFireFileManager.createTempFile( "surefire", "-excludes" ); - FileUtils.write( excludes, "AnotherTest" , UTF_8 ); - plugin.setExcludesFile( excludes ); + File excludes = SureFireFileManager.createTempFile("surefire", "-excludes"); + FileUtils.write(excludes, "AnotherTest", UTF_8); + plugin.setExcludesFile(excludes); - VersionRange version = VersionRange.createFromVersion( "1.0" ); + VersionRange version = VersionRange.createFromVersion("1.0"); ArtifactHandler handler = new DefaultArtifactHandler(); - Artifact testDeps = new DefaultArtifact( "g", "a", version, "compile", "test-jar", null, handler ); - File artifactFile = SureFireFileManager.createTempFile( "surefire", "-classes" ); + Artifact testDeps = new DefaultArtifact("g", "a", version, "compile", "test-jar", null, handler); + File artifactFile = SureFireFileManager.createTempFile("surefire", "-classes"); String classDir = artifactFile.getCanonicalPath(); - assertThat( artifactFile.delete() ).isTrue(); - File classes = new File( classDir ); - assertThat( classes.mkdir() ).isTrue(); - testDeps.setFile( classes ); - assertThat( new File( classes, "AnotherTest.class" ).createNewFile() ) - .isTrue(); - plugin.setProjectTestArtifacts( singletonList( testDeps ) ); - plugin.setDependenciesToScan( new String[] { "g:a" } ); + assertThat(artifactFile.delete()).isTrue(); + File classes = new File(classDir); + assertThat(classes.mkdir()).isTrue(); + testDeps.setFile(classes); + assertThat(new File(classes, "AnotherTest.class").createNewFile()).isTrue(); + plugin.setProjectTestArtifacts(singletonList(testDeps)); + plugin.setDependenciesToScan(new String[] {"g:a"}); DefaultScanResult result = plugin.scanDependencies(); - assertThat ( result.getClasses() ) - .isEmpty(); + assertThat(result.getClasses()).isEmpty(); } @Test - public void shouldFilterTestsOnExcludes() throws Exception - { + public void shouldFilterTestsOnExcludes() throws Exception { Mojo plugin = new Mojo(); - plugin.setLogger( mock( Logger.class ) ); + plugin.setLogger(mock(Logger.class)); - plugin.setExcludes( singletonList( "AnotherTest" ) ); + plugin.setExcludes(singletonList("AnotherTest")); - VersionRange version = VersionRange.createFromVersion( "1.0" ); + VersionRange version = VersionRange.createFromVersion("1.0"); ArtifactHandler handler = new DefaultArtifactHandler(); - Artifact testDeps = new DefaultArtifact( "g", "a", version, "compile", "jar", null, handler ); - File artifactFile = SureFireFileManager.createTempFile( "surefire", "-classes" ); + Artifact testDeps = new DefaultArtifact("g", "a", version, "compile", "jar", null, handler); + File artifactFile = SureFireFileManager.createTempFile("surefire", "-classes"); String classDir = artifactFile.getCanonicalPath(); - assertThat( artifactFile.delete() ).isTrue(); - File classes = new File( classDir ); - assertThat( classes.mkdir() ).isTrue(); - testDeps.setFile( classes ); - assertThat( new File( classes, "AnotherTest.class" ).createNewFile() ) - .isTrue(); - plugin.setProjectTestArtifacts( singletonList( testDeps ) ); - plugin.setDependenciesToScan( new String[] { "g:a" } ); + assertThat(artifactFile.delete()).isTrue(); + File classes = new File(classDir); + assertThat(classes.mkdir()).isTrue(); + testDeps.setFile(classes); + assertThat(new File(classes, "AnotherTest.class").createNewFile()).isTrue(); + plugin.setProjectTestArtifacts(singletonList(testDeps)); + plugin.setDependenciesToScan(new String[] {"g:a"}); DefaultScanResult result = plugin.scanDependencies(); - assertThat ( result.getClasses() ) - .isEmpty(); + assertThat(result.getClasses()).isEmpty(); } @Test - public void shouldUseOnlySpecificTests() throws Exception - { + public void shouldUseOnlySpecificTests() throws Exception { Mojo plugin = new Mojo(); - plugin.setLogger( mock( Logger.class ) ); + plugin.setLogger(mock(Logger.class)); - File includes = SureFireFileManager.createTempFile( "surefire", "-includes" ); - FileUtils.write( includes, "AnotherTest" , UTF_8 ); - plugin.setIncludesFile( includes ); - plugin.setTest( "DifferentTest" ); + File includes = SureFireFileManager.createTempFile("surefire", "-includes"); + FileUtils.write(includes, "AnotherTest", UTF_8); + plugin.setIncludesFile(includes); + plugin.setTest("DifferentTest"); - VersionRange version = VersionRange.createFromVersion( "1.0" ); + VersionRange version = VersionRange.createFromVersion("1.0"); ArtifactHandler handler = new DefaultArtifactHandler(); - Artifact testDeps = new DefaultArtifact( "g", "a", version, "compile", "test-jar", null, handler ); - File artifactFile = SureFireFileManager.createTempFile( "surefire", "-classes" ); + Artifact testDeps = new DefaultArtifact("g", "a", version, "compile", "test-jar", null, handler); + File artifactFile = SureFireFileManager.createTempFile("surefire", "-classes"); String classDir = artifactFile.getCanonicalPath(); - assertThat( artifactFile.delete() ).isTrue(); - File classes = new File( classDir ); - assertThat( classes.mkdir() ).isTrue(); - testDeps.setFile( classes ); - assertThat( new File( classes, "AnotherTest.class" ).createNewFile() ) - .isTrue(); - plugin.setProjectTestArtifacts( singletonList( testDeps ) ); - plugin.setDependenciesToScan( new String[] { "g:a" } ); + assertThat(artifactFile.delete()).isTrue(); + File classes = new File(classDir); + assertThat(classes.mkdir()).isTrue(); + testDeps.setFile(classes); + assertThat(new File(classes, "AnotherTest.class").createNewFile()).isTrue(); + plugin.setProjectTestArtifacts(singletonList(testDeps)); + plugin.setDependenciesToScan(new String[] {"g:a"}); DefaultScanResult result = plugin.scanDependencies(); - assertThat ( result.getClasses() ) - .isEmpty(); + assertThat(result.getClasses()).isEmpty(); } - private static File mockFile( String absolutePath ) - { - File f = mock( File.class ); - when( f.getAbsolutePath() ).thenReturn( absolutePath ); + private static File mockFile(String absolutePath) { + File f = mock(File.class); + when(f.getAbsolutePath()).thenReturn(absolutePath); return f; } - private static Dependency toDependency( Artifact artifact ) - { + private static Dependency toDependency(Artifact artifact) { Dependency dependency = new Dependency(); - dependency.setGroupId( artifact.getGroupId() ); - dependency.setArtifactId( artifact.getArtifactId() ); - dependency.setVersion( artifact.getBaseVersion() ); - dependency.setType( "jar" ); + dependency.setGroupId(artifact.getGroupId()); + dependency.setArtifactId(artifact.getArtifactId()); + dependency.setVersion(artifact.getBaseVersion()); + dependency.setType("jar"); return dependency; } - private static List toDependencies( Artifact... artifacts ) - { + private static List toDependencies(Artifact... artifacts) { List dependencies = new ArrayList<>(); - for ( Artifact artifact : artifacts ) - { - dependencies.add( toDependency( artifact ) ); + for (Artifact artifact : artifacts) { + dependencies.add(toDependency(artifact)); } return dependencies; } diff --git a/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/AbstractSurefireMojoToolchainsTest.java b/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/AbstractSurefireMojoToolchainsTest.java index 4ebe62a6e3..822c709eba 100644 --- a/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/AbstractSurefireMojoToolchainsTest.java +++ b/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/AbstractSurefireMojoToolchainsTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,14 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.surefire; + +import java.io.File; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.Collections; +import java.util.List; +import java.util.Map; import org.apache.maven.execution.MavenSession; import org.apache.maven.plugin.MojoFailureException; @@ -35,13 +41,6 @@ import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; -import java.io.File; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.Collections; -import java.util.List; -import java.util.Map; - import static java.io.File.separatorChar; import static java.util.Collections.emptyMap; import static java.util.Collections.singletonList; @@ -60,11 +59,10 @@ /** * Test for {@link AbstractSurefireMojo}. jdkToolchain parameter */ -@RunWith( PowerMockRunner.class ) -@PrepareForTest( {AbstractSurefireMojo.class} ) -@PowerMockIgnore( {"org.jacoco.agent.rt.*", "com.vladium.emma.rt.*"} ) -public class AbstractSurefireMojoToolchainsTest -{ +@RunWith(PowerMockRunner.class) +@PrepareForTest({AbstractSurefireMojo.class}) +@PowerMockIgnore({"org.jacoco.agent.rt.*", "com.vladium.emma.rt.*"}) +public class AbstractSurefireMojoToolchainsTest { @Rule public final ExpectedException e = ExpectedException.none(); @@ -73,24 +71,24 @@ public class AbstractSurefireMojoToolchainsTest * when the jdkToolchain parameter is set. */ @Test - public void shouldCallMaven33xMethodWhenSpecSet() throws Exception - { + public void shouldCallMaven33xMethodWhenSpecSet() throws Exception { AbstractSurefireMojoTest.Mojo mojo = new AbstractSurefireMojoTest.Mojo(); - Toolchain expectedFromMaven33Method = mock( Toolchain.class ); - MockToolchainManager toolchainManager = new MockToolchainManager( null, null ); - mojo.setToolchainManager( toolchainManager ); - mojo.setJdkToolchain( singletonMap( "version", "1.8" ) ); + Toolchain expectedFromMaven33Method = mock(Toolchain.class); + MockToolchainManager toolchainManager = new MockToolchainManager(null, null); + mojo.setToolchainManager(toolchainManager); + mojo.setJdkToolchain(singletonMap("version", "1.8")); - mockStatic( AbstractSurefireMojo.class ); + mockStatic(AbstractSurefireMojo.class); when( - AbstractSurefireMojo.class, - "getToolchainMaven33x", - ToolchainManager.class, - toolchainManager, - mojo.getSession(), mojo.getJdkToolchain() ).thenReturn( expectedFromMaven33Method ); - Toolchain actual = invokeMethod( mojo, "getToolchain" ); - assertThat( actual ) - .isSameAs( expectedFromMaven33Method ); + AbstractSurefireMojo.class, + "getToolchainMaven33x", + ToolchainManager.class, + toolchainManager, + mojo.getSession(), + mojo.getJdkToolchain()) + .thenReturn(expectedFromMaven33Method); + Toolchain actual = invokeMethod(mojo, "getToolchain"); + assertThat(actual).isSameAs(expectedFromMaven33Method); } /** @@ -99,55 +97,50 @@ public void shouldCallMaven33xMethodWhenSpecSet() throws Exception * getToolchain() returns the main maven toolchain from the build context */ @Test - public void shouldFallthroughToBuildContextWhenNoSpecSet() throws Exception - { + public void shouldFallthroughToBuildContextWhenNoSpecSet() throws Exception { AbstractSurefireMojoTest.Mojo mojo = new AbstractSurefireMojoTest.Mojo(); - Toolchain expectedFromContext = mock( Toolchain.class ); - Toolchain expectedFromSpec = mock( Toolchain.class ); //ensure it still behaves correctly even if not null - mojo.setToolchainManager( new MockToolchainManager( expectedFromSpec, expectedFromContext ) ); - Toolchain actual = invokeMethod( mojo, "getToolchain" ); - assertThat( actual ) - .isSameAs( expectedFromContext ); + Toolchain expectedFromContext = mock(Toolchain.class); + Toolchain expectedFromSpec = mock(Toolchain.class); // ensure it still behaves correctly even if not null + mojo.setToolchainManager(new MockToolchainManager(expectedFromSpec, expectedFromContext)); + Toolchain actual = invokeMethod(mojo, "getToolchain"); + assertThat(actual).isSameAs(expectedFromContext); } @Test - public void shouldReturnNoToolchainInMaven32() throws Exception - { - Toolchain toolchain = invokeMethod( AbstractSurefireMojo.class, - "getToolchainMaven33x", - MockToolchainManagerMaven32.class, - new MockToolchainManagerMaven32( null ), - mock( MavenSession.class ), - emptyMap() ); - assertNull( toolchain ); + public void shouldReturnNoToolchainInMaven32() throws Exception { + Toolchain toolchain = invokeMethod( + AbstractSurefireMojo.class, + "getToolchainMaven33x", + MockToolchainManagerMaven32.class, + new MockToolchainManagerMaven32(null), + mock(MavenSession.class), + emptyMap()); + assertNull(toolchain); } - @Test( expected = MojoFailureException.class ) - public void shouldThrowMaven33xToolchain() throws Exception - { + @Test(expected = MojoFailureException.class) + public void shouldThrowMaven33xToolchain() throws Exception { invokeMethod( - AbstractSurefireMojo.class, - "getToolchainMaven33x", - MockToolchainManager.class, - new MockToolchainManager( null, null ), - mock( MavenSession.class ), - emptyMap() ); + AbstractSurefireMojo.class, + "getToolchainMaven33x", + MockToolchainManager.class, + new MockToolchainManager(null, null), + mock(MavenSession.class), + emptyMap()); } @Test - public void shouldGetMaven33xToolchain() throws Exception - { - Toolchain expected = mock( Toolchain.class ); + public void shouldGetMaven33xToolchain() throws Exception { + Toolchain expected = mock(Toolchain.class); Toolchain actual = invokeMethod( - AbstractSurefireMojo.class, - "getToolchainMaven33x", - MockToolchainManager.class, - new MockToolchainManager( expected, null ), - mock( MavenSession.class ), - emptyMap() ); - - assertThat( actual ) - .isSameAs( expected ); + AbstractSurefireMojo.class, + "getToolchainMaven33x", + MockToolchainManager.class, + new MockToolchainManager(expected, null), + mock(MavenSession.class), + emptyMap()); + + assertThat(actual).isSameAs(expected); } /** @@ -155,36 +148,34 @@ public void shouldGetMaven33xToolchain() throws Exception * contains a Toolchain-driven entry when toolchain is set. */ @Test - public void shouldChangeJavaHomeFromToolchain() throws Exception - { + public void shouldChangeJavaHomeFromToolchain() throws Exception { AbstractSurefireMojoTest.Mojo mojo = new AbstractSurefireMojoTest.Mojo(); - DefaultJavaToolChain toolchain = mock( DefaultJavaToolChain.class ); - when( toolchain.findTool( "java" ) ).thenReturn( "/path/from/toolchain" ); - when( toolchain.getJavaHome() ).thenReturn( "/some/path" ); - mojo.setToolchain( toolchain ); - - assertThat( mojo.getEnvironmentVariables() ).isEmpty(); - JdkAttributes effectiveJvm = invokeMethod( mojo, "getEffectiveJvm" ); - assertThat( mojo.getEnvironmentVariables() ).containsEntry( "JAVA_HOME", "/some/path" ); - assertThat( effectiveJvm.getJvmExecutable().getPath() ) - .contains( "/path/from/toolchain".replace( '/', separatorChar ) ); + DefaultJavaToolChain toolchain = mock(DefaultJavaToolChain.class); + when(toolchain.findTool("java")).thenReturn("/path/from/toolchain"); + when(toolchain.getJavaHome()).thenReturn("/some/path"); + mojo.setToolchain(toolchain); + + assertThat(mojo.getEnvironmentVariables()).isEmpty(); + JdkAttributes effectiveJvm = invokeMethod(mojo, "getEffectiveJvm"); + assertThat(mojo.getEnvironmentVariables()).containsEntry("JAVA_HOME", "/some/path"); + assertThat(effectiveJvm.getJvmExecutable().getPath()) + .contains("/path/from/toolchain".replace('/', separatorChar)); } @Test - public void shouldNotChangeJavaHomeFromToolchainIfAlreadySet() throws Exception - { + public void shouldNotChangeJavaHomeFromToolchainIfAlreadySet() throws Exception { AbstractSurefireMojoTest.Mojo mojo = new AbstractSurefireMojoTest.Mojo(); - mojo.setEnvironmentVariables( singletonMap( "JAVA_HOME", "/already/set/path" ) ); + mojo.setEnvironmentVariables(singletonMap("JAVA_HOME", "/already/set/path")); - DefaultJavaToolChain toolchain = mock( DefaultJavaToolChain.class ); - when( toolchain.findTool( "java" ) ).thenReturn( "/path/from/toolchain" ); - when( toolchain.getJavaHome() ).thenReturn( "/some/path" ); - mojo.setToolchain( toolchain ); + DefaultJavaToolChain toolchain = mock(DefaultJavaToolChain.class); + when(toolchain.findTool("java")).thenReturn("/path/from/toolchain"); + when(toolchain.getJavaHome()).thenReturn("/some/path"); + mojo.setToolchain(toolchain); - JdkAttributes effectiveJvm = invokeMethod( mojo, "getEffectiveJvm" ); - assertThat( mojo.getEnvironmentVariables() ).containsEntry( "JAVA_HOME", "/already/set/path" ); - assertThat( effectiveJvm.getJvmExecutable().getPath() ) - .contains( "/path/from/toolchain".replace( '/', separatorChar ) ); + JdkAttributes effectiveJvm = invokeMethod(mojo, "getEffectiveJvm"); + assertThat(mojo.getEnvironmentVariables()).containsEntry("JAVA_HOME", "/already/set/path"); + assertThat(effectiveJvm.getJvmExecutable().getPath()) + .contains("/path/from/toolchain".replace('/', separatorChar)); } /** @@ -192,21 +183,18 @@ public void shouldNotChangeJavaHomeFromToolchainIfAlreadySet() throws Exception * contains a jvm parameter-driven entry when jvm is set. */ @Test - public void shouldChangeJavaHomeFromJvm() throws Exception - { + public void shouldChangeJavaHomeFromJvm() throws Exception { AbstractSurefireMojoTest.Mojo mojo = new AbstractSurefireMojoTest.Mojo(); File currentJdkHome = toJdkHomeFromJre(); - String javaExecutablePath = FilenameUtils.concat( - currentJdkHome.getAbsolutePath(), "bin/java" ); + String javaExecutablePath = FilenameUtils.concat(currentJdkHome.getAbsolutePath(), "bin/java"); - mojo.setJvm( javaExecutablePath ); + mojo.setJvm(javaExecutablePath); - assertThat( mojo.getEnvironmentVariables() ).isEmpty(); - JdkAttributes effectiveJvm = invokeMethod( mojo, "getEffectiveJvm" ); - assertThat( mojo.getEnvironmentVariables() ) - .containsEntry( "JAVA_HOME", currentJdkHome.getAbsolutePath() ); - assertThat( effectiveJvm.getJvmExecutable().getPath() ).contains( javaExecutablePath ); + assertThat(mojo.getEnvironmentVariables()).isEmpty(); + JdkAttributes effectiveJvm = invokeMethod(mojo, "getEffectiveJvm"); + assertThat(mojo.getEnvironmentVariables()).containsEntry("JAVA_HOME", currentJdkHome.getAbsolutePath()); + assertThat(effectiveJvm.getJvmExecutable().getPath()).contains(javaExecutablePath); } /** @@ -214,84 +202,71 @@ public void shouldChangeJavaHomeFromJvm() throws Exception * and we will not override it */ @Test - public void shouldNotChangeJavaHomeFromJvmIfAlreadySet() throws Exception - { + public void shouldNotChangeJavaHomeFromJvmIfAlreadySet() throws Exception { AbstractSurefireMojoTest.Mojo mojo = new AbstractSurefireMojoTest.Mojo(); - mojo.setEnvironmentVariables( singletonMap( "JAVA_HOME", "/already/set/path" ) ); + mojo.setEnvironmentVariables(singletonMap("JAVA_HOME", "/already/set/path")); File currentJdkHome = toJdkHomeFromJre(); - String javaExecutablePath = FilenameUtils.concat( currentJdkHome.getAbsolutePath(), "bin/java" ); + String javaExecutablePath = FilenameUtils.concat(currentJdkHome.getAbsolutePath(), "bin/java"); - mojo.setJvm( javaExecutablePath ); + mojo.setJvm(javaExecutablePath); - JdkAttributes effectiveJvm = invokeMethod( mojo, "getEffectiveJvm" ); - assertThat( mojo.getEnvironmentVariables() ) - .containsEntry( "JAVA_HOME", "/already/set/path" ); - assertThat( effectiveJvm.getJvmExecutable().getPath() ).contains( javaExecutablePath ); + JdkAttributes effectiveJvm = invokeMethod(mojo, "getEffectiveJvm"); + assertThat(mojo.getEnvironmentVariables()).containsEntry("JAVA_HOME", "/already/set/path"); + assertThat(effectiveJvm.getJvmExecutable().getPath()).contains(javaExecutablePath); } @Test - public void withoutJvmAndToolchain() throws Exception - { + public void withoutJvmAndToolchain() throws Exception { AbstractSurefireMojoTest.Mojo mojo = new AbstractSurefireMojoTest.Mojo(); - Logger logger = mock( Logger.class ); - mojo.setLogger( logger ); - ArgumentCaptor argument = ArgumentCaptor.forClass( String.class ); - JdkAttributes effectiveJvm = invokeMethod( mojo, "getEffectiveJvm" ); + Logger logger = mock(Logger.class); + mojo.setLogger(logger); + ArgumentCaptor argument = ArgumentCaptor.forClass(String.class); + JdkAttributes effectiveJvm = invokeMethod(mojo, "getEffectiveJvm"); - assertThat( mojo.getJvm() ) - .isNull(); + assertThat(mojo.getJvm()).isNull(); - assertThat( mojo.getEnvironmentVariables() ) - .isEmpty(); + assertThat(mojo.getEnvironmentVariables()).isEmpty(); - assertThat( effectiveJvm ) - .isNotNull(); + assertThat(effectiveJvm).isNotNull(); - assertThat( effectiveJvm.getJvmExecutable() ) - .isNotNull(); + assertThat(effectiveJvm.getJvmExecutable()).isNotNull(); - Path javaHome = Paths.get( System.getProperty( "java.home" ) ).normalize(); - boolean isLocalJvm = effectiveJvm.getJvmExecutable().toPath().normalize().startsWith( javaHome ); - assertThat( isLocalJvm ) - .isTrue(); + Path javaHome = Paths.get(System.getProperty("java.home")).normalize(); + boolean isLocalJvm = + effectiveJvm.getJvmExecutable().toPath().normalize().startsWith(javaHome); + assertThat(isLocalJvm).isTrue(); - verify( logger, times( 1 ) ) - .debug( argument.capture() ); + verify(logger, times(1)).debug(argument.capture()); - assertThat( argument.getValue() ) - .startsWith( "Using JVM: " + System.getProperty( "java.home" ) ); + assertThat(argument.getValue()).startsWith("Using JVM: " + System.getProperty("java.home")); } @Test - public void shouldFailWithWrongJvmExecPath() throws Exception - { + public void shouldFailWithWrongJvmExecPath() throws Exception { AbstractSurefireMojoTest.Mojo mojo = new AbstractSurefireMojoTest.Mojo(); - mojo.setLogger( mock( Logger.class ) ); - mojo.setJvm( System.getProperty( "user.dir" ) ); + mojo.setLogger(mock(Logger.class)); + mojo.setJvm(System.getProperty("user.dir")); - e.expect( MojoFailureException.class ); - e.expectMessage( startsWith( "Given path does not end with java executor" ) ); + e.expect(MojoFailureException.class); + e.expectMessage(startsWith("Given path does not end with java executor")); - invokeMethod( mojo, "getEffectiveJvm" ); + invokeMethod(mojo, "getEffectiveJvm"); } /** * Mocks a ToolchainManager */ - public static final class MockToolchainManager extends MockToolchainManagerMaven32 - { + public static final class MockToolchainManager extends MockToolchainManagerMaven32 { private final Toolchain specToolchain; - public MockToolchainManager( Toolchain specToolchain, Toolchain buildContextToolchain ) - { - super( buildContextToolchain ); + public MockToolchainManager(Toolchain specToolchain, Toolchain buildContextToolchain) { + super(buildContextToolchain); this.specToolchain = specToolchain; } - public List getToolchains( MavenSession session, String type, Map requirements ) - { - return specToolchain == null ? Collections.emptyList() : singletonList( specToolchain ); + public List getToolchains(MavenSession session, String type, Map requirements) { + return specToolchain == null ? Collections.emptyList() : singletonList(specToolchain); } } @@ -299,19 +274,16 @@ public List getToolchains( MavenSession session, String type, Map argumentMsg = ArgumentCaptor.forClass( String.class ); - verify( consoleLogger, times( 1 ) ).info( argumentMsg.capture() ); - assertThat( argumentMsg.getAllValues() ).hasSize( 1 ); - assertThat( argumentMsg.getAllValues().get( 0 ) ).isEqualTo( "msg" ); + decorator.info("msg"); + ArgumentCaptor argumentMsg = ArgumentCaptor.forClass(String.class); + verify(consoleLogger, times(1)).info(argumentMsg.capture()); + assertThat(argumentMsg.getAllValues()).hasSize(1); + assertThat(argumentMsg.getAllValues().get(0)).isEqualTo("msg"); } } diff --git a/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/DataZT1A.java b/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/DataZT1A.java index 7cbd568bdd..13a3bcba0b 100644 --- a/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/DataZT1A.java +++ b/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/DataZT1A.java @@ -1,3 +1,21 @@ +/* + * 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.maven.plugin.surefire; /* @@ -22,6 +40,4 @@ /** * */ -public class DataZT1A -{ -} +public class DataZT1A {} diff --git a/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/DataZT2A.java b/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/DataZT2A.java index 3779ca1a02..0c9c0291d7 100644 --- a/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/DataZT2A.java +++ b/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/DataZT2A.java @@ -1,3 +1,21 @@ +/* + * 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.maven.plugin.surefire; /* @@ -22,6 +40,4 @@ /** * */ -public class DataZT2A -{ -} +public class DataZT2A {} diff --git a/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/DataZT3A.java b/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/DataZT3A.java index c44752b539..53b9ce5075 100644 --- a/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/DataZT3A.java +++ b/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/DataZT3A.java @@ -1,3 +1,21 @@ +/* + * 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.maven.plugin.surefire; /* @@ -20,8 +38,6 @@ */ /** - * + * */ -public class DataZT3A -{ -} +public class DataZT3A {} diff --git a/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/MojoMocklessTest.java b/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/MojoMocklessTest.java index 25e417c6ef..d3717fc7d4 100644 --- a/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/MojoMocklessTest.java +++ b/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/MojoMocklessTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,13 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.surefire; + +import java.io.File; +import java.io.FileOutputStream; +import java.util.List; +import java.util.zip.ZipEntry; +import java.util.zip.ZipOutputStream; import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.DefaultArtifact; @@ -28,19 +33,13 @@ import org.apache.maven.plugin.surefire.extensions.SurefireConsoleOutputReporter; import org.apache.maven.plugin.surefire.extensions.SurefireStatelessReporter; import org.apache.maven.plugin.surefire.extensions.SurefireStatelessTestsetInfoReporter; -import org.apache.maven.surefire.extensions.ForkNodeFactory; import org.apache.maven.surefire.api.suite.RunResult; import org.apache.maven.surefire.api.util.DefaultScanResult; import org.apache.maven.surefire.api.util.SureFireFileManager; +import org.apache.maven.surefire.extensions.ForkNodeFactory; import org.codehaus.plexus.logging.Logger; import org.junit.Test; -import java.io.File; -import java.io.FileOutputStream; -import java.util.List; -import java.util.zip.ZipEntry; -import java.util.zip.ZipOutputStream; - import static java.util.Arrays.asList; import static java.util.Collections.singletonList; import static org.assertj.core.api.Assertions.assertThat; @@ -52,768 +51,570 @@ /** * */ -public class MojoMocklessTest -{ +public class MojoMocklessTest { @Test - public void testGetStartupReportConfiguration() throws Exception - { - AbstractSurefireMojo surefirePlugin = new Mojo( null, null ); - StartupReportConfiguration config = invokeMethod( surefirePlugin, "getStartupReportConfiguration", "", false ); - - assertThat( config.getXmlReporter() ) - .isNotNull() - .isInstanceOf( SurefireStatelessReporter.class ); - - assertThat( config.getConsoleOutputReporter() ) - .isNotNull() - .isInstanceOf( SurefireConsoleOutputReporter.class ); - - assertThat( config.getTestsetReporter() ) - .isNotNull() - .isInstanceOf( SurefireStatelessTestsetInfoReporter.class ); + public void testGetStartupReportConfiguration() throws Exception { + AbstractSurefireMojo surefirePlugin = new Mojo(null, null); + StartupReportConfiguration config = invokeMethod(surefirePlugin, "getStartupReportConfiguration", "", false); + + assertThat(config.getXmlReporter()).isNotNull().isInstanceOf(SurefireStatelessReporter.class); + + assertThat(config.getConsoleOutputReporter()).isNotNull().isInstanceOf(SurefireConsoleOutputReporter.class); + + assertThat(config.getTestsetReporter()).isNotNull().isInstanceOf(SurefireStatelessTestsetInfoReporter.class); } @Test - public void testGetStartupReportConfiguration2() throws Exception - { - AbstractSurefireMojo surefirePlugin = new Mojo( null, null ); - SurefireStatelessReporter xmlReporter = new SurefireStatelessReporter( false, "3.0" ); + public void testGetStartupReportConfiguration2() throws Exception { + AbstractSurefireMojo surefirePlugin = new Mojo(null, null); + SurefireStatelessReporter xmlReporter = new SurefireStatelessReporter(false, "3.0"); SurefireConsoleOutputReporter consoleReporter = new SurefireConsoleOutputReporter(); SurefireStatelessTestsetInfoReporter testsetInfoReporter = new SurefireStatelessTestsetInfoReporter(); - setInternalState( surefirePlugin, "statelessTestsetReporter", xmlReporter ); - setInternalState( surefirePlugin, "consoleOutputReporter", consoleReporter ); - setInternalState( surefirePlugin, "statelessTestsetInfoReporter", testsetInfoReporter ); + setInternalState(surefirePlugin, "statelessTestsetReporter", xmlReporter); + setInternalState(surefirePlugin, "consoleOutputReporter", consoleReporter); + setInternalState(surefirePlugin, "statelessTestsetInfoReporter", testsetInfoReporter); - StartupReportConfiguration config = invokeMethod( surefirePlugin, "getStartupReportConfiguration", "", false ); + StartupReportConfiguration config = invokeMethod(surefirePlugin, "getStartupReportConfiguration", "", false); - assertThat( config.getXmlReporter() ) - .isNotNull() - .isSameAs( xmlReporter ); + assertThat(config.getXmlReporter()).isNotNull().isSameAs(xmlReporter); - assertThat( config.getConsoleOutputReporter() ) - .isNotNull() - .isSameAs( consoleReporter ); + assertThat(config.getConsoleOutputReporter()).isNotNull().isSameAs(consoleReporter); - assertThat( config.getTestsetReporter() ) - .isNotNull() - .isSameAs( testsetInfoReporter ); + assertThat(config.getTestsetReporter()).isNotNull().isSameAs(testsetInfoReporter); } @Test - @SuppressWarnings( "checkstyle:magicnumber" ) - public void testForkCountComputation() - { - AbstractSurefireMojo surefirePlugin = new Mojo( null, null ); - assertConversionFails( surefirePlugin, "nothing" ); + @SuppressWarnings("checkstyle:magicnumber") + public void testForkCountComputation() { + AbstractSurefireMojo surefirePlugin = new Mojo(null, null); + assertConversionFails(surefirePlugin, "nothing"); - assertConversionFails( surefirePlugin, "5,0" ); - assertConversionFails( surefirePlugin, "5.0" ); - assertConversionFails( surefirePlugin, "5,0C" ); - assertConversionFails( surefirePlugin, "5.0CC" ); + assertConversionFails(surefirePlugin, "5,0"); + assertConversionFails(surefirePlugin, "5.0"); + assertConversionFails(surefirePlugin, "5,0C"); + assertConversionFails(surefirePlugin, "5.0CC"); - assertForkCount( surefirePlugin, 5, "5" ); + assertForkCount(surefirePlugin, 5, "5"); int availableProcessors = Runtime.getRuntime().availableProcessors(); - assertForkCount( surefirePlugin, 3 * availableProcessors, "3C" ); - assertForkCount( surefirePlugin, (int) ( 2.5 * availableProcessors ), "2.5C" ); - assertForkCount( surefirePlugin, availableProcessors, "1.0001 C" ); - assertForkCount( surefirePlugin, 1, 1d / ( (double) availableProcessors + 1 ) + "C" ); - assertForkCount( surefirePlugin, 0, "0 C" ); + assertForkCount(surefirePlugin, 3 * availableProcessors, "3C"); + assertForkCount(surefirePlugin, (int) (2.5 * availableProcessors), "2.5C"); + assertForkCount(surefirePlugin, availableProcessors, "1.0001 C"); + assertForkCount(surefirePlugin, 1, 1d / ((double) availableProcessors + 1) + "C"); + assertForkCount(surefirePlugin, 0, "0 C"); } - private static void assertForkCount( AbstractSurefireMojo surefirePlugin, int expected, String value ) - { - assertThat( surefirePlugin.convertWithCoreCount( value ) ) - .isEqualTo( expected ); + private static void assertForkCount(AbstractSurefireMojo surefirePlugin, int expected, String value) { + assertThat(surefirePlugin.convertWithCoreCount(value)).isEqualTo(expected); } - private static void assertConversionFails( AbstractSurefireMojo surefirePlugin, String value ) - { - try - { - surefirePlugin.convertWithCoreCount( value ); - } - catch ( NumberFormatException e ) - { + private static void assertConversionFails(AbstractSurefireMojo surefirePlugin, String value) { + try { + surefirePlugin.convertWithCoreCount(value); + } catch (NumberFormatException e) { return; } - fail( "Expected NumberFormatException when converting " + value ); + fail("Expected NumberFormatException when converting " + value); } @Test - public void scanDependenciesShouldReturnNull() - throws MojoFailureException - { - Mojo mojo = new Mojo( null, null ); + public void scanDependenciesShouldReturnNull() throws MojoFailureException { + Mojo mojo = new Mojo(null, null); DefaultScanResult result = mojo.scanDependencies(); - assertThat( result ) - .isNull(); + assertThat(result).isNull(); } @Test - public void scanDependenciesShouldReturnNullAfterMissingBuildArtifact() - throws MojoFailureException - { - VersionRange version = VersionRange.createFromVersion( "1.0" ); + public void scanDependenciesShouldReturnNullAfterMissingBuildArtifact() throws MojoFailureException { + VersionRange version = VersionRange.createFromVersion("1.0"); ArtifactHandler handler = new DefaultArtifactHandler(); - Artifact testDeps = new DefaultArtifact( "g", "a", version, "compile", "jar", null, handler ); - List projectTestArtifacts = singletonList( testDeps ); - String[] dependenciesToScan = { "g:a" }; - Mojo mojo = new Mojo( projectTestArtifacts, dependenciesToScan ); + Artifact testDeps = new DefaultArtifact("g", "a", version, "compile", "jar", null, handler); + List projectTestArtifacts = singletonList(testDeps); + String[] dependenciesToScan = {"g:a"}; + Mojo mojo = new Mojo(projectTestArtifacts, dependenciesToScan); DefaultScanResult result = mojo.scanDependencies(); - assertThat( result ) - .isNull(); + assertThat(result).isNull(); } @Test - public void scanDependenciesShouldReturnNullWithWAR() - throws MojoFailureException - { - VersionRange version = VersionRange.createFromVersion( "1.0" ); + public void scanDependenciesShouldReturnNullWithWAR() throws MojoFailureException { + VersionRange version = VersionRange.createFromVersion("1.0"); ArtifactHandler handler = new DefaultArtifactHandler(); - Artifact testDeps = new DefaultArtifact( "g", "a", version, "compile", "war", null, handler ); - testDeps.setFile( new File( new File( "target" ), "a-1.0.war" ) ); - List projectTestArtifacts = singletonList( testDeps ); - String[] dependenciesToScan = { "g:a" }; - Mojo mojo = new Mojo( projectTestArtifacts, dependenciesToScan ); + Artifact testDeps = new DefaultArtifact("g", "a", version, "compile", "war", null, handler); + testDeps.setFile(new File(new File("target"), "a-1.0.war")); + List projectTestArtifacts = singletonList(testDeps); + String[] dependenciesToScan = {"g:a"}; + Mojo mojo = new Mojo(projectTestArtifacts, dependenciesToScan); DefaultScanResult result = mojo.scanDependencies(); - assertThat( result ) - .isNull(); + assertThat(result).isNull(); } @Test - public void scanDependenciesShouldReturnNullWithExistingWAR() - throws Exception - { - VersionRange version = VersionRange.createFromVersion( "1.0" ); + public void scanDependenciesShouldReturnNullWithExistingWAR() throws Exception { + VersionRange version = VersionRange.createFromVersion("1.0"); ArtifactHandler handler = new DefaultArtifactHandler(); - Artifact testDeps = new DefaultArtifact( "g", "a", version, "compile", "war", null, handler ); - File artifactFile = SureFireFileManager.createTempFile( "surefire", ".war" ); - testDeps.setFile( artifactFile ); - List projectTestArtifacts = singletonList( testDeps ); - String[] dependenciesToScan = { "g:a" }; - Mojo mojo = new Mojo( projectTestArtifacts, dependenciesToScan ); + Artifact testDeps = new DefaultArtifact("g", "a", version, "compile", "war", null, handler); + File artifactFile = SureFireFileManager.createTempFile("surefire", ".war"); + testDeps.setFile(artifactFile); + List projectTestArtifacts = singletonList(testDeps); + String[] dependenciesToScan = {"g:a"}; + Mojo mojo = new Mojo(projectTestArtifacts, dependenciesToScan); DefaultScanResult result = mojo.scanDependencies(); - assertThat( result ) - .isNull(); + assertThat(result).isNull(); } @Test - public void scanDependenciesShouldReturnClassWithExistingTestJAR() - throws Exception - { - VersionRange version = VersionRange.createFromVersion( "1.0" ); + public void scanDependenciesShouldReturnClassWithExistingTestJAR() throws Exception { + VersionRange version = VersionRange.createFromVersion("1.0"); ArtifactHandler handler = new DefaultArtifactHandler(); - Artifact testDeps = new DefaultArtifact( "g", "a", version, "compile", "test-jar", null, handler ); + Artifact testDeps = new DefaultArtifact("g", "a", version, "compile", "test-jar", null, handler); - File artifactFile = SureFireFileManager.createTempFile( "surefire", ".jar" ); - testDeps.setFile( artifactFile ); - try ( ZipOutputStream os = new ZipOutputStream( new FileOutputStream( artifactFile ) ) ) - { - os.putNextEntry( new ZipEntry( "pkg/" ) ); + File artifactFile = SureFireFileManager.createTempFile("surefire", ".jar"); + testDeps.setFile(artifactFile); + try (ZipOutputStream os = new ZipOutputStream(new FileOutputStream(artifactFile))) { + os.putNextEntry(new ZipEntry("pkg/")); os.closeEntry(); - os.putNextEntry( new ZipEntry( "pkg/MyTest.class" ) ); + os.putNextEntry(new ZipEntry("pkg/MyTest.class")); os.closeEntry(); os.finish(); } - List projectTestArtifacts = singletonList( testDeps ); - String[] dependenciesToScan = { "g:a" }; - Mojo mojo = new Mojo( projectTestArtifacts, dependenciesToScan ); - mojo.setLogger( mock( Logger.class ) ); + List projectTestArtifacts = singletonList(testDeps); + String[] dependenciesToScan = {"g:a"}; + Mojo mojo = new Mojo(projectTestArtifacts, dependenciesToScan); + mojo.setLogger(mock(Logger.class)); DefaultScanResult result = mojo.scanDependencies(); - assertThat( result ) - .isNotNull(); + assertThat(result).isNotNull(); - assertThat( result.isEmpty() ) - .isFalse(); + assertThat(result.isEmpty()).isFalse(); - assertThat( result.getClasses() ) - .contains( "pkg.MyTest" ); + assertThat(result.getClasses()).contains("pkg.MyTest"); } @Test - public void scanDependenciesShouldReturnNullWithEmptyTestJAR() - throws Exception - { - VersionRange version = VersionRange.createFromVersion( "1.0" ); + public void scanDependenciesShouldReturnNullWithEmptyTestJAR() throws Exception { + VersionRange version = VersionRange.createFromVersion("1.0"); ArtifactHandler handler = new DefaultArtifactHandler(); - Artifact testDeps = new DefaultArtifact( "g", "a", version, "compile", "jar", null, handler ); + Artifact testDeps = new DefaultArtifact("g", "a", version, "compile", "jar", null, handler); - File artifactFile = SureFireFileManager.createTempFile( "surefire", ".jar" ); - testDeps.setFile( artifactFile ); - try ( ZipOutputStream os = new ZipOutputStream( new FileOutputStream( artifactFile ) ) ) - { - os.putNextEntry( new ZipEntry( "pkg/" ) ); + File artifactFile = SureFireFileManager.createTempFile("surefire", ".jar"); + testDeps.setFile(artifactFile); + try (ZipOutputStream os = new ZipOutputStream(new FileOutputStream(artifactFile))) { + os.putNextEntry(new ZipEntry("pkg/")); os.closeEntry(); os.finish(); } - List projectTestArtifacts = singletonList( testDeps ); - String[] dependenciesToScan = { "g:a" }; - Mojo mojo = new Mojo( projectTestArtifacts, dependenciesToScan ); - mojo.setLogger( mock( Logger.class ) ); + List projectTestArtifacts = singletonList(testDeps); + String[] dependenciesToScan = {"g:a"}; + Mojo mojo = new Mojo(projectTestArtifacts, dependenciesToScan); + mojo.setLogger(mock(Logger.class)); DefaultScanResult result = mojo.scanDependencies(); - assertThat( result ) - .isNotNull(); + assertThat(result).isNotNull(); - assertThat( result.isEmpty() ) - .isTrue(); + assertThat(result.isEmpty()).isTrue(); } @Test - public void scanDependenciesShouldReturnClassWithDirectory() - throws Exception - { - VersionRange version = VersionRange.createFromVersion( "1.0" ); + public void scanDependenciesShouldReturnClassWithDirectory() throws Exception { + VersionRange version = VersionRange.createFromVersion("1.0"); ArtifactHandler handler = new DefaultArtifactHandler(); - Artifact testDeps = new DefaultArtifact( "g", "a", version, "compile", "test-jar", null, handler ); + Artifact testDeps = new DefaultArtifact("g", "a", version, "compile", "test-jar", null, handler); - File artifactFile = SureFireFileManager.createTempFile( "surefire", "-classes" ); + File artifactFile = SureFireFileManager.createTempFile("surefire", "-classes"); String classDir = artifactFile.getCanonicalPath(); - assertThat( artifactFile.delete() ).isTrue(); - File classes = new File( classDir ); - assertThat( classes.mkdir() ).isTrue(); + assertThat(artifactFile.delete()).isTrue(); + File classes = new File(classDir); + assertThat(classes.mkdir()).isTrue(); - testDeps.setFile( classes ); + testDeps.setFile(classes); - assertThat( new File( classes, "AnotherTest.class" ).createNewFile() ) - .isTrue(); + assertThat(new File(classes, "AnotherTest.class").createNewFile()).isTrue(); - List projectTestArtifacts = singletonList( testDeps ); - String[] dependenciesToScan = { "g:a" }; - Mojo mojo = new Mojo( projectTestArtifacts, dependenciesToScan ); - mojo.setLogger( mock( Logger.class ) ); + List projectTestArtifacts = singletonList(testDeps); + String[] dependenciesToScan = {"g:a"}; + Mojo mojo = new Mojo(projectTestArtifacts, dependenciesToScan); + mojo.setLogger(mock(Logger.class)); DefaultScanResult result = mojo.scanDependencies(); - assertThat( result ) - .isNotNull(); + assertThat(result).isNotNull(); - assertThat( result.isEmpty() ) - .isFalse(); + assertThat(result.isEmpty()).isFalse(); - assertThat( result.getClasses() ) - .contains( "AnotherTest" ); + assertThat(result.getClasses()).contains("AnotherTest"); } @Test - public void scanMultipleDependencies() - throws Exception - { - VersionRange version = VersionRange.createFromVersion( "1.0" ); + public void scanMultipleDependencies() throws Exception { + VersionRange version = VersionRange.createFromVersion("1.0"); ArtifactHandler handler = new DefaultArtifactHandler(); - Artifact testDep1 = new DefaultArtifact( "g", "x", version, "compile", "jar", null, handler ); + Artifact testDep1 = new DefaultArtifact("g", "x", version, "compile", "jar", null, handler); - File artifactFile1 = SureFireFileManager.createTempFile( "surefire", "-classes" ); + File artifactFile1 = SureFireFileManager.createTempFile("surefire", "-classes"); String classDir = artifactFile1.getCanonicalPath(); - assertThat( artifactFile1.delete() ).isTrue(); - File classes = new File( classDir ); - assertThat( classes.mkdir() ).isTrue(); + assertThat(artifactFile1.delete()).isTrue(); + File classes = new File(classDir); + assertThat(classes.mkdir()).isTrue(); - testDep1.setFile( classes ); + testDep1.setFile(classes); - assertThat( new File( classes, "AnotherTest.class" ).createNewFile() ) - .isTrue(); + assertThat(new File(classes, "AnotherTest.class").createNewFile()).isTrue(); - Artifact testDep2 = new DefaultArtifact( "g", "a", version, "test", "jar", null, handler ); - File artifactFile2 = SureFireFileManager.createTempFile( "surefire", ".jar" ); - testDep2.setFile( artifactFile2 ); - try ( ZipOutputStream os = new ZipOutputStream( new FileOutputStream( artifactFile2 ) ) ) - { - os.putNextEntry( new ZipEntry( "pkg/" ) ); + Artifact testDep2 = new DefaultArtifact("g", "a", version, "test", "jar", null, handler); + File artifactFile2 = SureFireFileManager.createTempFile("surefire", ".jar"); + testDep2.setFile(artifactFile2); + try (ZipOutputStream os = new ZipOutputStream(new FileOutputStream(artifactFile2))) { + os.putNextEntry(new ZipEntry("pkg/")); os.closeEntry(); - os.putNextEntry( new ZipEntry( "pkg/MyTest.class" ) ); + os.putNextEntry(new ZipEntry("pkg/MyTest.class")); os.closeEntry(); os.finish(); } - List projectTestArtifacts = asList( testDep1, testDep2 ); - String[] dependenciesToScan = { "g:a" }; - Mojo mojo = new Mojo( projectTestArtifacts, dependenciesToScan ); - mojo.setLogger( mock( Logger.class ) ); + List projectTestArtifacts = asList(testDep1, testDep2); + String[] dependenciesToScan = {"g:a"}; + Mojo mojo = new Mojo(projectTestArtifacts, dependenciesToScan); + mojo.setLogger(mock(Logger.class)); DefaultScanResult result = mojo.scanDependencies(); - assertThat( result ) - .isNotNull(); + assertThat(result).isNotNull(); - assertThat( result.isEmpty() ) - .isFalse(); + assertThat(result.isEmpty()).isFalse(); - assertThat( result.getClasses() ) - .hasSize( 1 ); + assertThat(result.getClasses()).hasSize(1); - assertThat( result.getClasses() ) - .contains( "pkg.MyTest" ); + assertThat(result.getClasses()).contains("pkg.MyTest"); } - private static final class Mojo - extends AbstractSurefireMojo - { + private static final class Mojo extends AbstractSurefireMojo { private final List projectTestArtifacts; private final String[] dependenciesToScan; - Mojo( List projectTestArtifacts, String[] dependenciesToScan ) - { + Mojo(List projectTestArtifacts, String[] dependenciesToScan) { this.projectTestArtifacts = projectTestArtifacts; this.dependenciesToScan = dependenciesToScan; } @Override - protected String getPluginName() - { + protected String getPluginName() { return null; } @Override - protected int getRerunFailingTestsCount() - { + protected int getRerunFailingTestsCount() { return 0; } @Override - public boolean isSkipTests() - { + public boolean isSkipTests() { return false; } @Override - public void setSkipTests( boolean skipTests ) - { - - } + public void setSkipTests(boolean skipTests) {} @Override - public boolean isSkipExec() - { + public boolean isSkipExec() { return false; } @Override - public void setSkipExec( boolean skipExec ) - { - - } + public void setSkipExec(boolean skipExec) {} @Override - public boolean isSkip() - { + public boolean isSkip() { return false; } @Override - public void setSkip( boolean skip ) - { - - } + public void setSkip(boolean skip) {} @Override - public File getBasedir() - { + public File getBasedir() { return null; } @Override - public void setBasedir( File basedir ) - { - - } + public void setBasedir(File basedir) {} @Override - public File getTestClassesDirectory() - { + public File getTestClassesDirectory() { return null; } @Override - public void setTestClassesDirectory( File testClassesDirectory ) - { - - } + public void setTestClassesDirectory(File testClassesDirectory) {} @Override - public File getMainBuildPath() - { + public File getMainBuildPath() { return null; } @Override - public void setMainBuildPath( File mainBuildPath ) - { - - } + public void setMainBuildPath(File mainBuildPath) {} @Override - public File getReportsDirectory() - { + public File getReportsDirectory() { return null; } @Override - public void setReportsDirectory( File reportsDirectory ) - { - - } + public void setReportsDirectory(File reportsDirectory) {} @Override - public String getTest() - { + public String getTest() { return null; } @Override - public void setTest( String test ) - { - - } + public void setTest(String test) {} @Override - public List getIncludes() - { + public List getIncludes() { return null; } @Override - public File getIncludesFile() - { + public File getIncludesFile() { return null; } @Override - public void setIncludes( List includes ) - { - - } + public void setIncludes(List includes) {} @Override - public List getExcludes() - { + public List getExcludes() { return null; } @Override - public void setExcludes( List excludes ) - { - - } + public void setExcludes(List excludes) {} @Override - public boolean isPrintSummary() - { + public boolean isPrintSummary() { return false; } @Override - public void setPrintSummary( boolean printSummary ) - { - - } + public void setPrintSummary(boolean printSummary) {} @Override - public String getReportFormat() - { + public String getReportFormat() { return null; } @Override - public void setReportFormat( String reportFormat ) - { - - } + public void setReportFormat(String reportFormat) {} @Override - public boolean isUseFile() - { + public boolean isUseFile() { return false; } @Override - public void setUseFile( boolean useFile ) - { - - } + public void setUseFile(boolean useFile) {} @Override - public String getDebugForkedProcess() - { + public String getDebugForkedProcess() { return null; } @Override - public void setDebugForkedProcess( String debugForkedProcess ) - { - - } + public void setDebugForkedProcess(String debugForkedProcess) {} @Override - public int getForkedProcessTimeoutInSeconds() - { + public int getForkedProcessTimeoutInSeconds() { return 0; } @Override - public void setForkedProcessTimeoutInSeconds( int forkedProcessTimeoutInSeconds ) - { - - } + public void setForkedProcessTimeoutInSeconds(int forkedProcessTimeoutInSeconds) {} @Override - public int getForkedProcessExitTimeoutInSeconds() - { + public int getForkedProcessExitTimeoutInSeconds() { return 0; } @Override - public void setForkedProcessExitTimeoutInSeconds( int forkedProcessTerminationTimeoutInSeconds ) - { - - } + public void setForkedProcessExitTimeoutInSeconds(int forkedProcessTerminationTimeoutInSeconds) {} @Override - public double getParallelTestsTimeoutInSeconds() - { + public double getParallelTestsTimeoutInSeconds() { return 0; } @Override - public void setParallelTestsTimeoutInSeconds( double parallelTestsTimeoutInSeconds ) - { - - } + public void setParallelTestsTimeoutInSeconds(double parallelTestsTimeoutInSeconds) {} @Override - public double getParallelTestsTimeoutForcedInSeconds() - { + public double getParallelTestsTimeoutForcedInSeconds() { return 0; } @Override - public void setParallelTestsTimeoutForcedInSeconds( double parallelTestsTimeoutForcedInSeconds ) - { - - } + public void setParallelTestsTimeoutForcedInSeconds(double parallelTestsTimeoutForcedInSeconds) {} @Override - public boolean isUseSystemClassLoader() - { + public boolean isUseSystemClassLoader() { return false; } @Override - public void setUseSystemClassLoader( boolean useSystemClassLoader ) - { - - } + public void setUseSystemClassLoader(boolean useSystemClassLoader) {} @Override - public boolean isUseManifestOnlyJar() - { + public boolean isUseManifestOnlyJar() { return false; } @Override - public void setUseManifestOnlyJar( boolean useManifestOnlyJar ) - { - - } + public void setUseManifestOnlyJar(boolean useManifestOnlyJar) {} @Override - public String getEncoding() - { + public String getEncoding() { return null; } @Override - public void setEncoding( String encoding ) - { - - } + public void setEncoding(String encoding) {} @Override - public boolean getFailIfNoSpecifiedTests() - { + public boolean getFailIfNoSpecifiedTests() { return false; } @Override - public void setFailIfNoSpecifiedTests( boolean failIfNoSpecifiedTests ) - { - - } + public void setFailIfNoSpecifiedTests(boolean failIfNoSpecifiedTests) {} @Override - public int getSkipAfterFailureCount() - { + public int getSkipAfterFailureCount() { return 0; } @Override - public String getShutdown() - { + public String getShutdown() { return null; } @Override - public File getExcludesFile() - { + public File getExcludesFile() { return null; } @Override - protected List suiteXmlFiles() - { + protected List suiteXmlFiles() { return null; } @Override - protected boolean hasSuiteXmlFiles() - { + protected boolean hasSuiteXmlFiles() { return false; } @Override - protected String[] getExcludedEnvironmentVariables() - { + protected String[] getExcludedEnvironmentVariables() { return new String[0]; } @Override - public File[] getSuiteXmlFiles() - { + public File[] getSuiteXmlFiles() { return new File[0]; } @Override - public void setSuiteXmlFiles( File[] suiteXmlFiles ) - { - - } + public void setSuiteXmlFiles(File[] suiteXmlFiles) {} @Override - public String getRunOrder() - { + public String getRunOrder() { return null; } @Override - public void setRunOrder( String runOrder ) - { - - } + public void setRunOrder(String runOrder) {} @Override - public Long getRunOrderRandomSeed() - { + public Long getRunOrderRandomSeed() { return null; } @Override - public void setRunOrderRandomSeed( Long runOrderRandomSeed ) - { - - } + public void setRunOrderRandomSeed(Long runOrderRandomSeed) {} @Override - public String[] getDependenciesToScan() - { + public String[] getDependenciesToScan() { return dependenciesToScan; } @Override - protected void handleSummary( RunResult summary, Exception firstForkException ) - { - - } + protected void handleSummary(RunResult summary, Exception firstForkException) {} @Override - protected boolean isSkipExecution() - { + protected boolean isSkipExecution() { return false; } @Override - protected String[] getDefaultIncludes() - { + protected String[] getDefaultIncludes() { return new String[0]; } @Override - protected String getReportSchemaLocation() - { + protected String getReportSchemaLocation() { return null; } @Override - protected boolean useModulePath() - { + protected boolean useModulePath() { return false; } @Override - protected void setUseModulePath( boolean useModulePath ) - { - - } + protected void setUseModulePath(boolean useModulePath) {} @Override - protected ForkNodeFactory getForkNode() - { + protected ForkNodeFactory getForkNode() { return null; } @Override - protected String getEnableProcessChecker() - { + protected String getEnableProcessChecker() { return null; } @Override - protected Artifact getMojoArtifact() - { + protected Artifact getMojoArtifact() { return null; } @Override - List getProjectTestArtifacts() - { + List getProjectTestArtifacts() { return projectTestArtifacts; } @Override - public File getSystemPropertiesFile() - { + public File getSystemPropertiesFile() { return null; } @Override - public void setSystemPropertiesFile( File systemPropertiesFile ) - { - - } + public void setSystemPropertiesFile(File systemPropertiesFile) {} @Override - public String[] getIncludeJUnit5Engines() - { + public String[] getIncludeJUnit5Engines() { return null; } @Override - public void setIncludeJUnit5Engines( String[] includeJUnit5Engines ) - { - - } + public void setIncludeJUnit5Engines(String[] includeJUnit5Engines) {} @Override - public String[] getExcludeJUnit5Engines() - { + public String[] getExcludeJUnit5Engines() { return null; } @Override - public void setExcludeJUnit5Engines( String[] excludeJUnit5Engines ) - { - - } + public void setExcludeJUnit5Engines(String[] excludeJUnit5Engines) {} } } diff --git a/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/SurefireDependencyResolverTest.java b/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/SurefireDependencyResolverTest.java index 5b9512267b..c8f3b1890f 100644 --- a/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/SurefireDependencyResolverTest.java +++ b/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/SurefireDependencyResolverTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.surefire; import java.io.File; import java.util.Iterator; @@ -62,326 +61,256 @@ /** * */ -public class SurefireDependencyResolverTest -{ +public class SurefireDependencyResolverTest { @Rule public final ExpectedException expectedException = ExpectedException.none(); @Test - public void shouldNotBeWithinRangeNullArtifact() - { - boolean result = SurefireDependencyResolver.isWithinVersionSpec( null, "[4.7,)" ); - assertThat( result ) - .isFalse(); + public void shouldNotBeWithinRangeNullArtifact() { + boolean result = SurefireDependencyResolver.isWithinVersionSpec(null, "[4.7,)"); + assertThat(result).isFalse(); } @Test - public void shouldNotBeWithinRange() throws InvalidVersionSpecificationException - { - Artifact api = createArtifact( "junit", "junit", "4.6" ); - boolean result = SurefireDependencyResolver.isWithinVersionSpec( api, "[4.7,)" ); - assertThat( result ) - .isFalse(); + public void shouldNotBeWithinRange() throws InvalidVersionSpecificationException { + Artifact api = createArtifact("junit", "junit", "4.6"); + boolean result = SurefireDependencyResolver.isWithinVersionSpec(api, "[4.7,)"); + assertThat(result).isFalse(); } @Test - public void shouldBeWithinRange() throws InvalidVersionSpecificationException - { - Artifact api = createArtifact( "junit", "junit", "4.7" ); - boolean result = SurefireDependencyResolver.isWithinVersionSpec( api, "[4.7,)" ); - assertThat( result ) - .isTrue(); + public void shouldBeWithinRange() throws InvalidVersionSpecificationException { + Artifact api = createArtifact("junit", "junit", "4.7"); + boolean result = SurefireDependencyResolver.isWithinVersionSpec(api, "[4.7,)"); + assertThat(result).isTrue(); } @Test - public void shouldBeFarWithinRange() throws InvalidVersionSpecificationException - { - Artifact api = createArtifact( "junit", "junit", "4.13" ); - boolean result = SurefireDependencyResolver.isWithinVersionSpec( api, "[4.7,)" ); - assertThat( result ) - .isTrue(); + public void shouldBeFarWithinRange() throws InvalidVersionSpecificationException { + Artifact api = createArtifact("junit", "junit", "4.13"); + boolean result = SurefireDependencyResolver.isWithinVersionSpec(api, "[4.7,)"); + assertThat(result).isTrue(); } @Test - public void shouldBeFailWithinRange() throws InvalidVersionSpecificationException - { - Artifact api = createArtifact( "junit", "junit", "" ); - expectedException.expect( RuntimeException.class ); - expectedException.expectMessage( "Bug in plugin. Please report with stacktrace" ); - SurefireDependencyResolver.isWithinVersionSpec( api, "[4.7,)" ); + public void shouldBeFailWithinRange() throws InvalidVersionSpecificationException { + Artifact api = createArtifact("junit", "junit", ""); + expectedException.expect(RuntimeException.class); + expectedException.expectMessage("Bug in plugin. Please report with stacktrace"); + SurefireDependencyResolver.isWithinVersionSpec(api, "[4.7,)"); } @Test - public void testResolveArtifact() throws InvalidVersionSpecificationException, MojoExecutionException - { - final Artifact provider = createArtifact( "surefire-junit-platform" ); - RepositorySystem repositorySystem = mock( RepositorySystem.class ); - final ArtifactResolutionResult expectedResult = mock( ArtifactResolutionResult.class ); - when( repositorySystem.resolve( any( ArtifactResolutionRequest.class ) ) ) - .then( new Answer() - { - @Override - public ArtifactResolutionResult answer( InvocationOnMock invocation ) - { - Object[] args = invocation.getArguments(); - assertThat( args ) - .hasSize( 1 ); - ArtifactResolutionRequest request = (ArtifactResolutionRequest) args[0]; - assertThat( request.getArtifact() ) - .isSameAs( provider ); - assertThat( request.isResolveTransitively() ) - .isTrue(); - assertThat( request.getArtifactDependencies() ) - .isNull(); - assertThat( request.getRemoteRepositories() ) - .isNull(); - assertThat( request.getLocalRepository() ) - .isNull(); - assertThat( request.getCollectionFilter() ) - .isNotNull(); - assertThat( request.getCollectionFilter() ) - .isInstanceOf( RuntimeArtifactFilter.class ); - assertThat( request.getManagedVersionMap() ) - .isNull(); - assertThat( request.getMirrors() ) - .isEmpty(); - assertThat( request.getProxies() ) - .isEmpty(); - assertThat( request.getResolutionFilter() ) - .isNull(); - assertThat( request.getServers() ) - .isEmpty(); - return expectedResult; - } - } ); - - SurefireDependencyResolver surefireDependencyResolver = - new SurefireDependencyResolver( repositorySystem, null, null, null, null, - new DefaultResolutionErrorHandler(), null, false ); - - ArtifactResolutionResult actualResult = surefireDependencyResolver.resolvePluginArtifact( provider ); - - assertThat( actualResult ) - .isSameAs( expectedResult ); + public void testResolveArtifact() throws InvalidVersionSpecificationException, MojoExecutionException { + final Artifact provider = createArtifact("surefire-junit-platform"); + RepositorySystem repositorySystem = mock(RepositorySystem.class); + final ArtifactResolutionResult expectedResult = mock(ArtifactResolutionResult.class); + when(repositorySystem.resolve(any(ArtifactResolutionRequest.class))) + .then(new Answer() { + @Override + public ArtifactResolutionResult answer(InvocationOnMock invocation) { + Object[] args = invocation.getArguments(); + assertThat(args).hasSize(1); + ArtifactResolutionRequest request = (ArtifactResolutionRequest) args[0]; + assertThat(request.getArtifact()).isSameAs(provider); + assertThat(request.isResolveTransitively()).isTrue(); + assertThat(request.getArtifactDependencies()).isNull(); + assertThat(request.getRemoteRepositories()).isNull(); + assertThat(request.getLocalRepository()).isNull(); + assertThat(request.getCollectionFilter()).isNotNull(); + assertThat(request.getCollectionFilter()).isInstanceOf(RuntimeArtifactFilter.class); + assertThat(request.getManagedVersionMap()).isNull(); + assertThat(request.getMirrors()).isEmpty(); + assertThat(request.getProxies()).isEmpty(); + assertThat(request.getResolutionFilter()).isNull(); + assertThat(request.getServers()).isEmpty(); + return expectedResult; + } + }); + + SurefireDependencyResolver surefireDependencyResolver = new SurefireDependencyResolver( + repositorySystem, null, null, null, null, new DefaultResolutionErrorHandler(), null, false); + + ArtifactResolutionResult actualResult = surefireDependencyResolver.resolvePluginArtifact(provider); + + assertThat(actualResult).isSameAs(expectedResult); } @Test - public void testGetProviderClasspath() throws Exception - { + public void testGetProviderClasspath() throws Exception { - Artifact commonJunit4 = createArtifact( "common-junit4" ); - Artifact api = createArtifact( "surefire-api" ); - final Artifact provider = createArtifact( "surefire-junit-platform" ); - Artifact ext = createArtifact( "org.apiguardian", "apiguardian-api" ); - Artifact logger = createArtifact( "surefire-logger-api" ); + Artifact commonJunit4 = createArtifact("common-junit4"); + Artifact api = createArtifact("surefire-api"); + final Artifact provider = createArtifact("surefire-junit-platform"); + Artifact ext = createArtifact("org.apiguardian", "apiguardian-api"); + Artifact logger = createArtifact("surefire-logger-api"); Set providerArtifacts = new LinkedHashSet<>(); - providerArtifacts.add( commonJunit4 ); - providerArtifacts.add( api ); - providerArtifacts.add( provider ); - providerArtifacts.add( ext ); - providerArtifacts.add( logger ); - - final ArtifactResolutionResult result = mock( ArtifactResolutionResult.class ); - when( result.getArtifacts() ) - .thenReturn( providerArtifacts ); - - RepositorySystem repositorySystem = mock( RepositorySystem.class ); - when( repositorySystem.resolve( any( ArtifactResolutionRequest.class ) ) ) - .then( new Answer() - { - @Override - public ArtifactResolutionResult answer( InvocationOnMock invocation ) - { - Object[] args = invocation.getArguments(); - assertThat( args ) - .hasSize( 1 ); - ArtifactResolutionRequest request = (ArtifactResolutionRequest) args[0]; - assertThat( request.getArtifact() ) - .isSameAs( provider ); - assertThat( request.isResolveTransitively() ) - .isTrue(); - assertThat( request.getArtifactDependencies() ) - .isNull(); - assertThat( request.getRemoteRepositories() ) - .isNull(); - assertThat( request.getLocalRepository() ) - .isNull(); - assertThat( request.getCollectionFilter() ) - .isNotNull(); - assertThat( request.getCollectionFilter() ) - .isInstanceOf( RuntimeArtifactFilter.class ); - assertThat( request.getManagedVersionMap() ) - .isNull(); - assertThat( request.getMirrors() ) - .isEmpty(); - assertThat( request.getProxies() ) - .isEmpty(); - assertThat( request.getResolutionFilter() ) - .isNull(); - assertThat( request.getServers() ) - .isEmpty(); - return result; - } - } ); - when( repositorySystem.createDependencyArtifact( any( Dependency.class ) ) ) - .then( new Answer() - { - @Override - public Artifact answer( InvocationOnMock invocation ) - { - Object[] args = invocation.getArguments(); - assertThat( args ) - .hasSize( 1 ); - Dependency request = (Dependency) args[0]; - assertThat( request.getGroupId() ) - .isEqualTo( provider.getGroupId() ); - assertThat( request.getArtifactId() ) - .isEqualTo( provider.getArtifactId() ); - assertThat( request.getVersion() ) - .isEqualTo( provider.getVersion() ); - assertThat( request.getType() ) - .isEqualTo( provider.getType() ); - assertThat( request.getScope() ) - .isNull(); - return provider; - } - } ); - - ConsoleLogger log = mock( ConsoleLogger.class ); - - SurefireDependencyResolver surefireDependencyResolver = - new SurefireDependencyResolver( repositorySystem, log, null, null, null, - new DefaultResolutionErrorHandler(), null, false ); - - when( log.isDebugEnabled() ) - .thenReturn( true ); - - Set classpath = surefireDependencyResolver.getProviderClasspath( "surefire-junit-platform", "1" ); - - assertThat( classpath ) - .hasSize( 5 ); + providerArtifacts.add(commonJunit4); + providerArtifacts.add(api); + providerArtifacts.add(provider); + providerArtifacts.add(ext); + providerArtifacts.add(logger); + + final ArtifactResolutionResult result = mock(ArtifactResolutionResult.class); + when(result.getArtifacts()).thenReturn(providerArtifacts); + + RepositorySystem repositorySystem = mock(RepositorySystem.class); + when(repositorySystem.resolve(any(ArtifactResolutionRequest.class))) + .then(new Answer() { + @Override + public ArtifactResolutionResult answer(InvocationOnMock invocation) { + Object[] args = invocation.getArguments(); + assertThat(args).hasSize(1); + ArtifactResolutionRequest request = (ArtifactResolutionRequest) args[0]; + assertThat(request.getArtifact()).isSameAs(provider); + assertThat(request.isResolveTransitively()).isTrue(); + assertThat(request.getArtifactDependencies()).isNull(); + assertThat(request.getRemoteRepositories()).isNull(); + assertThat(request.getLocalRepository()).isNull(); + assertThat(request.getCollectionFilter()).isNotNull(); + assertThat(request.getCollectionFilter()).isInstanceOf(RuntimeArtifactFilter.class); + assertThat(request.getManagedVersionMap()).isNull(); + assertThat(request.getMirrors()).isEmpty(); + assertThat(request.getProxies()).isEmpty(); + assertThat(request.getResolutionFilter()).isNull(); + assertThat(request.getServers()).isEmpty(); + return result; + } + }); + when(repositorySystem.createDependencyArtifact(any(Dependency.class))).then(new Answer() { + @Override + public Artifact answer(InvocationOnMock invocation) { + Object[] args = invocation.getArguments(); + assertThat(args).hasSize(1); + Dependency request = (Dependency) args[0]; + assertThat(request.getGroupId()).isEqualTo(provider.getGroupId()); + assertThat(request.getArtifactId()).isEqualTo(provider.getArtifactId()); + assertThat(request.getVersion()).isEqualTo(provider.getVersion()); + assertThat(request.getType()).isEqualTo(provider.getType()); + assertThat(request.getScope()).isNull(); + return provider; + } + }); + + ConsoleLogger log = mock(ConsoleLogger.class); + + SurefireDependencyResolver surefireDependencyResolver = new SurefireDependencyResolver( + repositorySystem, log, null, null, null, new DefaultResolutionErrorHandler(), null, false); + + when(log.isDebugEnabled()).thenReturn(true); + + Set classpath = surefireDependencyResolver.getProviderClasspath("surefire-junit-platform", "1"); + + assertThat(classpath).hasSize(5); Iterator it = classpath.iterator(); // result should be ordered - assertThat( it.next() ) - .isSameAs( provider ); + assertThat(it.next()).isSameAs(provider); - assertThat( it.next() ) - .isSameAs( api ); + assertThat(it.next()).isSameAs(api); - assertThat( it.next() ) - .isSameAs( logger ); + assertThat(it.next()).isSameAs(logger); - assertThat( it.next() ) - .isSameAs( commonJunit4 ); + assertThat(it.next()).isSameAs(commonJunit4); - assertThat( it.next() ) - .isSameAs( ext ); + assertThat(it.next()).isSameAs(ext); } @Test - public void testGetProviderClasspathShouldPropagateTheResolutionException() throws Exception - { - Artifact provider = createArtifact( "surefire-junit-platform" ); - provider.setFile( null ); + public void testGetProviderClasspathShouldPropagateTheResolutionException() throws Exception { + Artifact provider = createArtifact("surefire-junit-platform"); + provider.setFile(null); Set providerArtifacts = new LinkedHashSet<>(); - providerArtifacts.add( provider ); + providerArtifacts.add(provider); - ArtifactResolutionResult result = mock( ArtifactResolutionResult.class ); - when( result.getArtifacts() ).thenReturn( providerArtifacts ); - when( result.hasMetadataResolutionExceptions() ).thenReturn( true ); + ArtifactResolutionResult result = mock(ArtifactResolutionResult.class); + when(result.getArtifacts()).thenReturn(providerArtifacts); + when(result.hasMetadataResolutionExceptions()).thenReturn(true); ArtifactResolutionException resolutionException = - new ArtifactResolutionException( "failed to resolve", provider ); - when( result.getMetadataResolutionException( 0 ) ).thenReturn( resolutionException ); - - RepositorySystem repositorySystem = mock( RepositorySystem.class ); - when( repositorySystem.resolve( any( ArtifactResolutionRequest.class ) ) ).thenReturn( result ); - when( repositorySystem.createDependencyArtifact( any( Dependency.class ) ) ).thenReturn( provider ); - - SurefireDependencyResolver surefireDependencyResolver = - new SurefireDependencyResolver( repositorySystem, mock( ConsoleLogger.class ), null, null, null, - new DefaultResolutionErrorHandler(), null, false ); - - assertThatThrownBy( () -> surefireDependencyResolver.getProviderClasspath( "surefire-junit-platform", "1" ) ) - .isInstanceOf( MojoExecutionException.class ) - .hasCause( resolutionException ); + new ArtifactResolutionException("failed to resolve", provider); + when(result.getMetadataResolutionException(0)).thenReturn(resolutionException); + + RepositorySystem repositorySystem = mock(RepositorySystem.class); + when(repositorySystem.resolve(any(ArtifactResolutionRequest.class))).thenReturn(result); + when(repositorySystem.createDependencyArtifact(any(Dependency.class))).thenReturn(provider); + + SurefireDependencyResolver surefireDependencyResolver = new SurefireDependencyResolver( + repositorySystem, + mock(ConsoleLogger.class), + null, + null, + null, + new DefaultResolutionErrorHandler(), + null, + false); + + assertThatThrownBy(() -> surefireDependencyResolver.getProviderClasspath("surefire-junit-platform", "1")) + .isInstanceOf(MojoExecutionException.class) + .hasCause(resolutionException); } @Test - public void testResolvePluginDependencies() throws Exception - { + public void testResolvePluginDependencies() throws Exception { Dependency providerAsDependency = new Dependency(); - providerAsDependency.setGroupId( PROVIDER_GROUP_ID ); - providerAsDependency.setArtifactId( "surefire-shadefire" ); - providerAsDependency.setVersion( "1" ); + providerAsDependency.setGroupId(PROVIDER_GROUP_ID); + providerAsDependency.setArtifactId("surefire-shadefire"); + providerAsDependency.setVersion("1"); - Artifact providerAsArtifact = createArtifact( "surefire-shadefire" ); + Artifact providerAsArtifact = createArtifact("surefire-shadefire"); - Plugin plugin = mock( Plugin.class ); - when( plugin.getDependencies() ) - .thenReturn( singletonList( providerAsDependency ) ); + Plugin plugin = mock(Plugin.class); + when(plugin.getDependencies()).thenReturn(singletonList(providerAsDependency)); - RepositorySystem repositorySystem = mock( RepositorySystem.class ); - when( repositorySystem.createDependencyArtifact( providerAsDependency ) ) - .thenReturn( providerAsArtifact ); + RepositorySystem repositorySystem = mock(RepositorySystem.class); + when(repositorySystem.createDependencyArtifact(providerAsDependency)).thenReturn(providerAsArtifact); - ArtifactResolutionResult resolutionResult = mock( ArtifactResolutionResult.class ); - when( resolutionResult.getArtifacts() ) - .thenReturn( singleton( providerAsArtifact ) ); + ArtifactResolutionResult resolutionResult = mock(ArtifactResolutionResult.class); + when(resolutionResult.getArtifacts()).thenReturn(singleton(providerAsArtifact)); ArgumentCaptor resolutionRequestCaptor = - ArgumentCaptor.forClass( ArtifactResolutionRequest.class ); - when( repositorySystem.resolve( resolutionRequestCaptor.capture() ) ) - .thenReturn( resolutionResult ); + ArgumentCaptor.forClass(ArtifactResolutionRequest.class); + when(repositorySystem.resolve(resolutionRequestCaptor.capture())).thenReturn(resolutionResult); Map pluginResolvedDependencies = - singletonMap( PROVIDER_GROUP_ID + ":surefire-shadefire", providerAsArtifact ); + singletonMap(PROVIDER_GROUP_ID + ":surefire-shadefire", providerAsArtifact); - SurefireDependencyResolver surefireDependencyResolver = - new SurefireDependencyResolver( repositorySystem, null, null, null, null, - new DefaultResolutionErrorHandler(), null, false ); + SurefireDependencyResolver surefireDependencyResolver = new SurefireDependencyResolver( + repositorySystem, null, null, null, null, new DefaultResolutionErrorHandler(), null, false); Map providers = - surefireDependencyResolver.resolvePluginDependencies( plugin, pluginResolvedDependencies ); + surefireDependencyResolver.resolvePluginDependencies(plugin, pluginResolvedDependencies); - assertThat( providers.values() ) - .hasSize( 1 ) - .containsOnly( providerAsArtifact ); + assertThat(providers.values()).hasSize(1).containsOnly(providerAsArtifact); - assertThat( resolutionRequestCaptor.getAllValues() ) - .hasSize( 1 ); + assertThat(resolutionRequestCaptor.getAllValues()).hasSize(1); ArtifactResolutionRequest resolutionRequest = resolutionRequestCaptor.getValue(); - assertThat( resolutionRequest.getArtifact() ) - .isSameAs( providerAsArtifact ); + assertThat(resolutionRequest.getArtifact()).isSameAs(providerAsArtifact); - verify( repositorySystem ).createDependencyArtifact( any( Dependency.class ) ); - verify( repositorySystem ).resolve( any( ArtifactResolutionRequest.class ) ); - verifyNoMoreInteractions( repositorySystem ); + verify(repositorySystem).createDependencyArtifact(any(Dependency.class)); + verify(repositorySystem).resolve(any(ArtifactResolutionRequest.class)); + verifyNoMoreInteractions(repositorySystem); } - private static Artifact createArtifact( String artifactId ) throws InvalidVersionSpecificationException - { - return createArtifact( PROVIDER_GROUP_ID, artifactId ); + private static Artifact createArtifact(String artifactId) throws InvalidVersionSpecificationException { + return createArtifact(PROVIDER_GROUP_ID, artifactId); } - private static Artifact createArtifact( String groupId, String artifactId ) - throws InvalidVersionSpecificationException - { - return createArtifact( groupId, artifactId, "1" ); + private static Artifact createArtifact(String groupId, String artifactId) + throws InvalidVersionSpecificationException { + return createArtifact(groupId, artifactId, "1"); } - private static Artifact createArtifact( String groupId, String artifactId, String version ) - throws InvalidVersionSpecificationException - { - VersionRange versionSpec = createFromVersionSpec( version ); + private static Artifact createArtifact(String groupId, String artifactId, String version) + throws InvalidVersionSpecificationException { + VersionRange versionSpec = createFromVersionSpec(version); DefaultArtifact defaultArtifact = - new DefaultArtifact( groupId, artifactId, versionSpec, "compile", "jar", "", null ); - defaultArtifact.setFile( new File( "" ) ); + new DefaultArtifact(groupId, artifactId, versionSpec, "compile", "jar", "", null); + defaultArtifact.setFile(new File("")); return defaultArtifact; } } diff --git a/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/SurefireHelperTest.java b/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/SurefireHelperTest.java index dbe2c3697b..61f01f77c8 100644 --- a/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/SurefireHelperTest.java +++ b/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/SurefireHelperTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,11 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.surefire; + +import java.io.File; +import java.util.ArrayList; +import java.util.List; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; @@ -32,10 +35,6 @@ import org.junit.rules.ExpectedException; import org.mockito.ArgumentCaptor; -import java.io.File; -import java.util.ArrayList; -import java.util.List; - import static java.util.Collections.addAll; import static java.util.Collections.singleton; import static org.apache.maven.plugin.surefire.SurefireHelper.escapeToPlatformPath; @@ -53,168 +52,151 @@ /** * Test of {@link SurefireHelper}. */ -public class SurefireHelperTest -{ +public class SurefireHelperTest { @Rule public ExpectedException e = ExpectedException.none(); @Test - public void shouldReplaceForkNumberPath() - { - File root = new File( System.getProperty( "user.dir", "" ) ); - File pathWithPlaceholder = new File( root, "${surefire.forkNumber}" ); - File changed = SurefireHelper.replaceForkThreadsInPath( pathWithPlaceholder, 5 ); - assertThat( changed.getPath() ) - .isEqualTo( new File( root, "5" ).getPath() ); + public void shouldReplaceForkNumberPath() { + File root = new File(System.getProperty("user.dir", "")); + File pathWithPlaceholder = new File(root, "${surefire.forkNumber}"); + File changed = SurefireHelper.replaceForkThreadsInPath(pathWithPlaceholder, 5); + assertThat(changed.getPath()).isEqualTo(new File(root, "5").getPath()); } @Test - public void shouldReplaceLongForkNumberPath() - { - File root = new File( System.getProperty( "user.dir", "" ) ); - File subDir = new File( root, "reports-${surefire.forkNumber}" ); - File pathWithPlaceholder = new File( subDir, "subfolder" ); - File changed = SurefireHelper.replaceForkThreadsInPath( pathWithPlaceholder, 5 ); - assertThat( changed.getPath() ) - .isEqualTo( new File( new File( root, "reports-5" ), "subfolder" ).getPath() ); + public void shouldReplaceLongForkNumberPath() { + File root = new File(System.getProperty("user.dir", "")); + File subDir = new File(root, "reports-${surefire.forkNumber}"); + File pathWithPlaceholder = new File(subDir, "subfolder"); + File changed = SurefireHelper.replaceForkThreadsInPath(pathWithPlaceholder, 5); + assertThat(changed.getPath()).isEqualTo(new File(new File(root, "reports-5"), "subfolder").getPath()); } @Test - public void shouldBeThreeDumpFiles() - { + public void shouldBeThreeDumpFiles() { String[] dumps = SurefireHelper.getDumpFilesToPrint(); - assertThat( dumps ).hasSize( 4 ); - assertThat( dumps ).doesNotHaveDuplicates(); + assertThat(dumps).hasSize(4); + assertThat(dumps).doesNotHaveDuplicates(); List onlyStrings = new ArrayList<>(); - addAll( onlyStrings, dumps ); - onlyStrings.removeAll( singleton( (String) null ) ); - assertThat( onlyStrings ).hasSize( 4 ); + addAll(onlyStrings, dumps); + onlyStrings.removeAll(singleton((String) null)); + assertThat(onlyStrings).hasSize(4); } @Test - public void shouldCloneDumpFiles() - { + public void shouldCloneDumpFiles() { String[] dumps1 = SurefireHelper.getDumpFilesToPrint(); String[] dumps2 = SurefireHelper.getDumpFilesToPrint(); - assertThat( dumps1 ).isNotSameAs( dumps2 ); + assertThat(dumps1).isNotSameAs(dumps2); } @Test - public void testConstants() - { - assertThat( SurefireHelper.DUMPSTREAM_FILENAME_FORMATTER ) - .isEqualTo( SurefireHelper.DUMP_FILE_PREFIX + "%d.dumpstream" ); + public void testConstants() { + assertThat(SurefireHelper.DUMPSTREAM_FILENAME_FORMATTER) + .isEqualTo(SurefireHelper.DUMP_FILE_PREFIX + "%d.dumpstream"); - assertThat( String.format( SurefireHelper.DUMPSTREAM_FILENAME_FORMATTER, 5 ) ) - .endsWith( "-jvmRun5.dumpstream" ); + assertThat(String.format(SurefireHelper.DUMPSTREAM_FILENAME_FORMATTER, 5)) + .endsWith("-jvmRun5.dumpstream"); } @Test - public void shouldEscapeWindowsPath() - { - assumeTrue( IS_OS_WINDOWS ); + public void shouldEscapeWindowsPath() { + assumeTrue(IS_OS_WINDOWS); String root = "X:\\path\\to\\project\\"; String pathToJar = "target\\surefire\\surefirebooter4942721306300108667.jar"; - @SuppressWarnings( "checkstyle:magicnumber" ) + @SuppressWarnings("checkstyle:magicnumber") int projectNameLength = 247 - root.length() - pathToJar.length(); StringBuilder projectFolder = new StringBuilder(); - for ( int i = 0; i < projectNameLength; i++ ) - { - projectFolder.append( 'x' ); + for (int i = 0; i < projectNameLength; i++) { + projectFolder.append('x'); } String path = root + projectFolder + "\\" + pathToJar; - String escaped = escapeToPlatformPath( path ); - assertThat( escaped ).isEqualTo( "\\\\?\\" + path ); + String escaped = escapeToPlatformPath(path); + assertThat(escaped).isEqualTo("\\\\?\\" + path); path = root + "\\" + pathToJar; - escaped = escapeToPlatformPath( path ); - assertThat( escaped ).isEqualTo( root + "\\" + pathToJar ); + escaped = escapeToPlatformPath(path); + assertThat(escaped).isEqualTo(root + "\\" + pathToJar); } @Test - public void shouldHandleFailWithoutExitCode() throws Exception - { - RunResult summary = new RunResult( 0, 0, 0, 0 ); + public void shouldHandleFailWithoutExitCode() throws Exception { + RunResult summary = new RunResult(0, 0, 0, 0); Mojo plugin = new Mojo(); - plugin.setTestFailureIgnore( true ); - - Logger logger = mock( Logger.class ); - when( logger.isErrorEnabled() ).thenReturn( true ); - doNothing().when( logger ).error( anyString() ); - TestSetFailedException exc = new TestSetFailedException( "failure" ); - reportExecution( plugin, summary, new PluginConsoleLogger( logger ), exc ); - ArgumentCaptor errorMessage = ArgumentCaptor.forClass( String.class ); - verify( logger ).error( errorMessage.capture() ); - assertThat( errorMessage.getValue() ).contains( "failure" ); + plugin.setTestFailureIgnore(true); + + Logger logger = mock(Logger.class); + when(logger.isErrorEnabled()).thenReturn(true); + doNothing().when(logger).error(anyString()); + TestSetFailedException exc = new TestSetFailedException("failure"); + reportExecution(plugin, summary, new PluginConsoleLogger(logger), exc); + ArgumentCaptor errorMessage = ArgumentCaptor.forClass(String.class); + verify(logger).error(errorMessage.capture()); + assertThat(errorMessage.getValue()).contains("failure"); } @Test - public void shouldHandleFailIfJvmNonZeroExitCode() throws Exception - { - RunResult summary = new RunResult( 0, 0, 0, 0 ); + public void shouldHandleFailIfJvmNonZeroExitCode() throws Exception { + RunResult summary = new RunResult(0, 0, 0, 0); Mojo plugin = new Mojo(); - plugin.setTestFailureIgnore( true ); + plugin.setTestFailureIgnore(true); - SurefireBooterForkException exc = new SurefireBooterForkException( "Unrecognized option: -Xxxx" ); - e.expect( MojoExecutionException.class ); - e.expectMessage( containsString( "Unrecognized option: -Xxxx" ) ); - reportExecution( plugin, summary, new PluginConsoleLogger( mock( Logger.class ) ), exc ); + SurefireBooterForkException exc = new SurefireBooterForkException("Unrecognized option: -Xxxx"); + e.expect(MojoExecutionException.class); + e.expectMessage(containsString("Unrecognized option: -Xxxx")); + reportExecution(plugin, summary, new PluginConsoleLogger(mock(Logger.class)), exc); } @Test - public void shouldHandleFailIfNoTests() throws Exception - { - RunResult summary = new RunResult( 0, 0, 0, 0 ); + public void shouldHandleFailIfNoTests() throws Exception { + RunResult summary = new RunResult(0, 0, 0, 0); Mojo plugin = new Mojo(); - plugin.setFailIfNoTests( true ); - e.expect( MojoFailureException.class ); - e.expectMessage( "No tests were executed! (Set -DfailIfNoTests=false to ignore this error.)" ); - reportExecution( plugin, summary, null, null ); + plugin.setFailIfNoTests(true); + e.expect(MojoFailureException.class); + e.expectMessage("No tests were executed! (Set -DfailIfNoTests=false to ignore this error.)"); + reportExecution(plugin, summary, null, null); } @Test - public void shouldHandleTestFailure() throws Exception - { - RunResult summary = new RunResult( 1, 0, 1, 0 ); - e.expect( MojoFailureException.class ); - e.expectMessage( "There are test failures.\n\nPlease refer to null " - + "for the individual test results.\nPlease refer to dump files (if any exist) " - + "[date].dump, [date]-jvmRun[N].dump and [date].dumpstream." ); - reportExecution( new Mojo(), summary, null, null ); + public void shouldHandleTestFailure() throws Exception { + RunResult summary = new RunResult(1, 0, 1, 0); + e.expect(MojoFailureException.class); + e.expectMessage("There are test failures.\n\nPlease refer to null " + + "for the individual test results.\nPlease refer to dump files (if any exist) " + + "[date].dump, [date]-jvmRun[N].dump and [date].dumpstream."); + reportExecution(new Mojo(), summary, null, null); } @Test - public void failsIfThereAreTooManyFlakes() throws Exception - { - RunResult summary = new RunResult( 1, 0, 0, 0, 1 ); + public void failsIfThereAreTooManyFlakes() throws Exception { + RunResult summary = new RunResult(1, 0, 0, 0, 1); Mojo reportParameters = new Mojo(); - reportParameters.setFailOnFlakeCount( 1 ); - e.expect( MojoFailureException.class ); - e.expectMessage( "There is 1 flake and failOnFlakeCount is set to 1.\n\nPlease refer to null " - + "for the individual test results.\nPlease refer to dump files (if any exist) " - + "[date].dump, [date]-jvmRun[N].dump and [date].dumpstream." ); - reportExecution( reportParameters, summary, null, null ); + reportParameters.setFailOnFlakeCount(1); + e.expect(MojoFailureException.class); + e.expectMessage("There is 1 flake and failOnFlakeCount is set to 1.\n\nPlease refer to null " + + "for the individual test results.\nPlease refer to dump files (if any exist) " + + "[date].dump, [date]-jvmRun[N].dump and [date].dumpstream."); + reportExecution(reportParameters, summary, null, null); } @Test - public void reportsFailuresAndFlakes() throws Exception - { - RunResult summary = new RunResult( 1, 0, 1, 0, 2 ); + public void reportsFailuresAndFlakes() throws Exception { + RunResult summary = new RunResult(1, 0, 1, 0, 2); Mojo reportParameters = new Mojo(); - reportParameters.setFailOnFlakeCount( 1 ); - e.expect( MojoFailureException.class ); - e.expectMessage( "There are test failures.\nThere are 2 flakes and failOnFlakeCount is set to 1." - + "\n\nPlease refer to null " - + "for the individual test results.\nPlease refer to dump files (if any exist) " - + "[date].dump, [date]-jvmRun[N].dump and [date].dumpstream." ); - reportExecution( reportParameters, summary, null, null ); + reportParameters.setFailOnFlakeCount(1); + e.expect(MojoFailureException.class); + e.expectMessage("There are test failures.\nThere are 2 flakes and failOnFlakeCount is set to 1." + + "\n\nPlease refer to null " + + "for the individual test results.\nPlease refer to dump files (if any exist) " + + "[date].dump, [date]-jvmRun[N].dump and [date].dumpstream."); + reportExecution(reportParameters, summary, null, null); } @Test - public void passesIfFlakesAreWithinThreshold() throws Exception - { - RunResult summary = new RunResult( 1, 0, 0, 0 , 1 ); - reportExecution( new Mojo(), summary, null, null ); + public void passesIfFlakesAreWithinThreshold() throws Exception { + RunResult summary = new RunResult(1, 0, 0, 0, 1); + reportExecution(new Mojo(), summary, null, null); } } diff --git a/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/SurefirePropertiesTest.java b/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/SurefirePropertiesTest.java index 69c5fbfc1a..9d3e797020 100644 --- a/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/SurefirePropertiesTest.java +++ b/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/SurefirePropertiesTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.surefire; import java.util.Enumeration; import java.util.Iterator; @@ -33,103 +32,92 @@ /** * Tests the insertion-order preserving properties collection */ -public class SurefirePropertiesTest - extends TestCase -{ +public class SurefirePropertiesTest extends TestCase { - public void testKeys() - throws Exception - { - SurefireProperties orderedProperties = new SurefireProperties( (KeyValueSource) null ); - orderedProperties.setProperty( "abc", "1" ); - orderedProperties.setProperty( "xyz", "1" ); - orderedProperties.setProperty( "efg", "1" ); + public void testKeys() throws Exception { + SurefireProperties orderedProperties = new SurefireProperties((KeyValueSource) null); + orderedProperties.setProperty("abc", "1"); + orderedProperties.setProperty("xyz", "1"); + orderedProperties.setProperty("efg", "1"); Enumeration keys = orderedProperties.keys(); - assertEquals( "abc", keys.nextElement() ); - assertEquals( "xyz", keys.nextElement() ); - assertEquals( "efg", keys.nextElement() ); + assertEquals("abc", keys.nextElement()); + assertEquals("xyz", keys.nextElement()); + assertEquals("efg", keys.nextElement()); } - public void testKeysReinsert() - throws Exception - { - SurefireProperties orderedProperties = new SurefireProperties( (KeyValueSource) null ); - orderedProperties.setProperty( "abc", "1" ); - orderedProperties.setProperty( "xyz", "1" ); - orderedProperties.setProperty( "efg", "1" ); - orderedProperties.setProperty( "abc", "2" ); - orderedProperties.remove( "xyz" ); - orderedProperties.setProperty( "xyz", "1" ); + public void testKeysReinsert() throws Exception { + SurefireProperties orderedProperties = new SurefireProperties((KeyValueSource) null); + orderedProperties.setProperty("abc", "1"); + orderedProperties.setProperty("xyz", "1"); + orderedProperties.setProperty("efg", "1"); + orderedProperties.setProperty("abc", "2"); + orderedProperties.remove("xyz"); + orderedProperties.setProperty("xyz", "1"); Enumeration keys = orderedProperties.keys(); - assertEquals( "abc", keys.nextElement() ); - assertEquals( "efg", keys.nextElement() ); - assertEquals( "xyz", keys.nextElement() ); + assertEquals("abc", keys.nextElement()); + assertEquals("efg", keys.nextElement()); + assertEquals("xyz", keys.nextElement()); } - public void testConstructWithOther() - { + public void testConstructWithOther() { Properties src = new Properties(); - src.setProperty( "a", "1" ); - src.setProperty( "b", "2" ); - SurefireProperties orderedProperties = new SurefireProperties( src ); + src.setProperty("a", "1"); + src.setProperty("b", "2"); + SurefireProperties orderedProperties = new SurefireProperties(src); // Cannot make assumptions about insertion order // keys() uses the items property, more reliable to test than size(), // which is based on the Properties class // see https://issues.apache.org/jira/browse/SUREFIRE-1445 - assertEquals( src.size(), list( orderedProperties.keys() ).size() ); - assertEquals( src.size(), size( orderedProperties.getStringKeySet().iterator() ) ); - assertEquals( 2, orderedProperties.size() ); + assertEquals(src.size(), list(orderedProperties.keys()).size()); + assertEquals(src.size(), size(orderedProperties.getStringKeySet().iterator())); + assertEquals(2, orderedProperties.size()); - assertTrue( list( orderedProperties.keys() ).contains( "a" ) ); - assertTrue( list( orderedProperties.keys() ).contains( "b" ) ); + assertTrue(list(orderedProperties.keys()).contains("a")); + assertTrue(list(orderedProperties.keys()).contains("b")); Iterator it = orderedProperties.getStringKeySet().iterator(); SortedSet keys = new TreeSet<>(); - keys.add( it.next() ); - keys.add( it.next() ); + keys.add(it.next()); + keys.add(it.next()); it = keys.iterator(); - assertEquals( "a", it.next() ); - assertEquals( "b", it.next() ); + assertEquals("a", it.next()); + assertEquals("b", it.next()); } - public void testPutAll() - { + public void testPutAll() { Properties src = new Properties(); - src.setProperty( "a", "1" ); - src.setProperty( "b", "2" ); + src.setProperty("a", "1"); + src.setProperty("b", "2"); SurefireProperties orderedProperties = new SurefireProperties(); - orderedProperties.putAll( src ); + orderedProperties.putAll(src); // Cannot make assumptions about insertion order // keys() uses the items property, more reliable to test than size(), // which is based on the Properties class // see https://issues.apache.org/jira/browse/SUREFIRE-1445 - assertEquals( src.size(), list( orderedProperties.keys() ).size() ); - assertEquals( src.size(), size( orderedProperties.getStringKeySet().iterator() ) ); - assertEquals( 2, orderedProperties.size() ); + assertEquals(src.size(), list(orderedProperties.keys()).size()); + assertEquals(src.size(), size(orderedProperties.getStringKeySet().iterator())); + assertEquals(2, orderedProperties.size()); - assertTrue( list( orderedProperties.keys() ).contains( "a" ) ); - assertTrue( list( orderedProperties.keys() ).contains( "b" ) ); + assertTrue(list(orderedProperties.keys()).contains("a")); + assertTrue(list(orderedProperties.keys()).contains("b")); Iterator it = orderedProperties.getStringKeySet().iterator(); SortedSet keys = new TreeSet<>(); - keys.add( it.next() ); - keys.add( it.next() ); + keys.add(it.next()); + keys.add(it.next()); it = keys.iterator(); - assertEquals( "a", it.next() ); - assertEquals( "b", it.next() ); + assertEquals("a", it.next()); + assertEquals("b", it.next()); } - private static int size( Iterator iterator ) - { + private static int size(Iterator iterator) { int count = 0; - while ( iterator.hasNext() ) - { + while (iterator.hasNext()) { iterator.next(); count++; } return count; } - } diff --git a/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/booterclient/BooterDeserializerProviderConfigurationTest.java b/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/booterclient/BooterDeserializerProviderConfigurationTest.java index 55f63f358d..9f3a37e21a 100644 --- a/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/booterclient/BooterDeserializerProviderConfigurationTest.java +++ b/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/booterclient/BooterDeserializerProviderConfigurationTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire.booterclient; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,18 +16,20 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.surefire.booterclient; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; import junit.framework.Assert; import junit.framework.TestCase; -import org.apache.maven.surefire.shared.io.FileUtils; -import org.apache.maven.surefire.booter.BooterDeserializer; -import org.apache.maven.surefire.booter.ClassLoaderConfiguration; -import org.apache.maven.surefire.booter.ClasspathConfiguration; -import org.apache.maven.surefire.booter.PropertiesWrapper; -import org.apache.maven.surefire.booter.ProviderConfiguration; import org.apache.maven.surefire.api.booter.Shutdown; -import org.apache.maven.surefire.booter.StartupConfiguration; -import org.apache.maven.surefire.booter.TypeEncodedValue; import org.apache.maven.surefire.api.cli.CommandLineOption; import org.apache.maven.surefire.api.report.ReporterConfiguration; import org.apache.maven.surefire.api.testset.DirectoryScannerParameters; @@ -39,33 +39,30 @@ import org.apache.maven.surefire.api.testset.TestListResolver; import org.apache.maven.surefire.api.testset.TestRequest; import org.apache.maven.surefire.api.util.RunOrder; +import org.apache.maven.surefire.booter.BooterDeserializer; +import org.apache.maven.surefire.booter.ClassLoaderConfiguration; +import org.apache.maven.surefire.booter.ClasspathConfiguration; +import org.apache.maven.surefire.booter.PropertiesWrapper; +import org.apache.maven.surefire.booter.ProviderConfiguration; +import org.apache.maven.surefire.booter.StartupConfiguration; +import org.apache.maven.surefire.booter.TypeEncodedValue; +import org.apache.maven.surefire.shared.io.FileUtils; import org.junit.After; import org.junit.Before; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.util.Arrays; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; - -import static org.apache.maven.surefire.booter.ProcessCheckerType.ALL; import static org.apache.maven.surefire.api.cli.CommandLineOption.LOGGING_LEVEL_DEBUG; import static org.apache.maven.surefire.api.cli.CommandLineOption.REACTOR_FAIL_FAST; import static org.apache.maven.surefire.api.cli.CommandLineOption.SHOW_ERRORS; +import static org.apache.maven.surefire.booter.ProcessCheckerType.ALL; /** * Performs roundtrip testing of serialization/deserialization of the ProviderConfiguration * * @author Kristian Rosenvold */ -public class BooterDeserializerProviderConfigurationTest - extends TestCase -{ +public class BooterDeserializerProviderConfigurationTest extends TestCase { - static final TypeEncodedValue TEST_TYPED = new TypeEncodedValue( String.class.getName(), "aTest" ); + static final TypeEncodedValue TEST_TYPED = new TypeEncodedValue(String.class.getName(), "aTest"); private static final String USER_REQUESTED_TEST = "aUserRequestedTest"; @@ -77,230 +74,211 @@ public class BooterDeserializerProviderConfigurationTest private File basedir; - private final List cli = - Arrays.asList( LOGGING_LEVEL_DEBUG, SHOW_ERRORS, REACTOR_FAIL_FAST ); + private final List cli = Arrays.asList(LOGGING_LEVEL_DEBUG, SHOW_ERRORS, REACTOR_FAIL_FAST); @Before - public void setupDirectories() throws IOException - { - File target = new File( System.getProperty( "user.dir" ), "target" ); - basedir = new File( target, "BooterDeserializerProviderConfigurationTest-" + ++idx ); - FileUtils.deleteDirectory( basedir ); - assertTrue( basedir.mkdirs() ); + public void setupDirectories() throws IOException { + File target = new File(System.getProperty("user.dir"), "target"); + basedir = new File(target, "BooterDeserializerProviderConfigurationTest-" + ++idx); + FileUtils.deleteDirectory(basedir); + assertTrue(basedir.mkdirs()); } @After - public void deleteDirectories() throws IOException - { - FileUtils.deleteDirectory( basedir ); + public void deleteDirectories() throws IOException { + FileUtils.deleteDirectory(basedir); } - private static ClassLoaderConfiguration getForkConfiguration() - { - return new ClassLoaderConfiguration( true, false ); + private static ClassLoaderConfiguration getForkConfiguration() { + return new ClassLoaderConfiguration(true, false); } // ProviderConfiguration methods - public void testDirectoryScannerParams() - throws IOException - { + public void testDirectoryScannerParams() throws IOException { - File aDir = new File( "." ); + File aDir = new File("."); List includes = new ArrayList<>(); List excludes = new ArrayList<>(); - includes.add( "abc" ); - includes.add( "cde" ); - excludes.add( "xx1" ); - excludes.add( "xx2" ); + includes.add("abc"); + includes.add("cde"); + excludes.add("xx1"); + excludes.add("xx2"); ClassLoaderConfiguration forkConfiguration = getForkConfiguration(); - final StartupConfiguration testStartupConfiguration = getTestStartupConfiguration( forkConfiguration ); + final StartupConfiguration testStartupConfiguration = getTestStartupConfiguration(forkConfiguration); ProviderConfiguration providerConfiguration = getReloadedProviderConfiguration(); - ProviderConfiguration read = saveAndReload( providerConfiguration, testStartupConfiguration, false ); - - Assert.assertEquals( aDir, read.getBaseDir() ); - Assert.assertEquals( includes.get( 0 ), read.getIncludes().get( 0 ) ); - Assert.assertEquals( includes.get( 1 ), read.getIncludes().get( 1 ) ); - Assert.assertEquals( excludes.get( 0 ), read.getExcludes().get( 0 ) ); - Assert.assertEquals( excludes.get( 1 ), read.getExcludes().get( 1 ) ); - assertEquals( cli, providerConfiguration.getMainCliOptions() ); + ProviderConfiguration read = saveAndReload(providerConfiguration, testStartupConfiguration, false); + + Assert.assertEquals(aDir, read.getBaseDir()); + Assert.assertEquals(includes.get(0), read.getIncludes().get(0)); + Assert.assertEquals(includes.get(1), read.getIncludes().get(1)); + Assert.assertEquals(excludes.get(0), read.getExcludes().get(0)); + Assert.assertEquals(excludes.get(1), read.getExcludes().get(1)); + assertEquals(cli, providerConfiguration.getMainCliOptions()); } - public void testReporterConfiguration() - throws IOException - { + public void testReporterConfiguration() throws IOException { DirectoryScannerParameters directoryScannerParameters = getDirectoryScannerParametersWithoutSpecificTests(); ClassLoaderConfiguration forkConfiguration = getForkConfiguration(); - ProviderConfiguration providerConfiguration = getTestProviderConfiguration( directoryScannerParameters, false ); + ProviderConfiguration providerConfiguration = getTestProviderConfiguration(directoryScannerParameters, false); - final StartupConfiguration testProviderConfiguration = getTestStartupConfiguration( forkConfiguration ); - ProviderConfiguration reloaded = saveAndReload( providerConfiguration, testProviderConfiguration, false ); + final StartupConfiguration testProviderConfiguration = getTestStartupConfiguration(forkConfiguration); + ProviderConfiguration reloaded = saveAndReload(providerConfiguration, testProviderConfiguration, false); - assertTrue( reloaded.getReporterConfiguration().isTrimStackTrace() ); - assertNotNull( reloaded.getReporterConfiguration().getReportsDirectory() ); - assertEquals( cli, providerConfiguration.getMainCliOptions() ); + assertTrue(reloaded.getReporterConfiguration().isTrimStackTrace()); + assertNotNull(reloaded.getReporterConfiguration().getReportsDirectory()); + assertEquals(cli, providerConfiguration.getMainCliOptions()); } - public void testTestArtifact() - throws IOException - { + public void testTestArtifact() throws IOException { ProviderConfiguration reloaded = getReloadedProviderConfiguration(); - Assert.assertEquals( "5.0", reloaded.getTestArtifact().getVersion() ); - Assert.assertEquals( "ABC", reloaded.getTestArtifact().getClassifier() ); - assertEquals( cli, reloaded.getMainCliOptions() ); + Assert.assertEquals("5.0", reloaded.getTestArtifact().getVersion()); + Assert.assertEquals("ABC", reloaded.getTestArtifact().getClassifier()); + assertEquals(cli, reloaded.getMainCliOptions()); } - public void testTestRequest() - throws IOException - { + public void testTestRequest() throws IOException { ProviderConfiguration reloaded = getReloadedProviderConfiguration(); TestRequest testSuiteDefinition = reloaded.getTestSuiteDefinition(); List suiteXmlFiles = testSuiteDefinition.getSuiteXmlFiles(); File[] expected = getSuiteXmlFiles(); - Assert.assertEquals( expected[0], suiteXmlFiles.get( 0 ) ); - Assert.assertEquals( expected[1], suiteXmlFiles.get( 1 ) ); - Assert.assertEquals( getTestSourceDirectory(), testSuiteDefinition.getTestSourceDirectory() ); + Assert.assertEquals(expected[0], suiteXmlFiles.get(0)); + Assert.assertEquals(expected[1], suiteXmlFiles.get(1)); + Assert.assertEquals(getTestSourceDirectory(), testSuiteDefinition.getTestSourceDirectory()); TestListResolver resolver = testSuiteDefinition.getTestListResolver(); - Assert.assertNotNull( resolver ); - Assert.assertFalse( resolver.isEmpty() ); - Assert.assertEquals( USER_REQUESTED_TEST + "#" + USER_REQUESTED_TEST_METHOD, - resolver.getPluginParameterTest() ); - Assert.assertFalse( resolver.getIncludedPatterns().isEmpty() ); - Assert.assertTrue( resolver.getExcludedPatterns().isEmpty() ); - Assert.assertEquals( 1, resolver.getIncludedPatterns().size() ); + Assert.assertNotNull(resolver); + Assert.assertFalse(resolver.isEmpty()); + Assert.assertEquals(USER_REQUESTED_TEST + "#" + USER_REQUESTED_TEST_METHOD, resolver.getPluginParameterTest()); + Assert.assertFalse(resolver.getIncludedPatterns().isEmpty()); + Assert.assertTrue(resolver.getExcludedPatterns().isEmpty()); + Assert.assertEquals(1, resolver.getIncludedPatterns().size()); ResolvedTest filter = resolver.getIncludedPatterns().iterator().next(); - Assert.assertNotNull( filter ); - Assert.assertEquals( "**/" + USER_REQUESTED_TEST, filter.getTestClassPattern() ); - Assert.assertEquals( USER_REQUESTED_TEST_METHOD, filter.getTestMethodPattern() ); - Assert.assertEquals( RERUN_FAILING_TEST_COUNT, testSuiteDefinition.getRerunFailingTestsCount() ); - assertEquals( cli, reloaded.getMainCliOptions() ); + Assert.assertNotNull(filter); + Assert.assertEquals("**/" + USER_REQUESTED_TEST, filter.getTestClassPattern()); + Assert.assertEquals(USER_REQUESTED_TEST_METHOD, filter.getTestMethodPattern()); + Assert.assertEquals(RERUN_FAILING_TEST_COUNT, testSuiteDefinition.getRerunFailingTestsCount()); + assertEquals(cli, reloaded.getMainCliOptions()); } - public void testTestForFork() - throws IOException - { + public void testTestForFork() throws IOException { final ProviderConfiguration reloaded = getReloadedProviderConfiguration(); - Assert.assertEquals( TEST_TYPED, reloaded.getTestForFork() ); - assertEquals( cli, reloaded.getMainCliOptions() ); + Assert.assertEquals(TEST_TYPED, reloaded.getTestForFork()); + assertEquals(cli, reloaded.getMainCliOptions()); } - public void testTestForForkWithMultipleFiles() - throws IOException - { + public void testTestForForkWithMultipleFiles() throws IOException { final ProviderConfiguration reloaded = getReloadedProviderConfigurationForReadFromInStream(); - Assert.assertNull( reloaded.getTestForFork() ); - Assert.assertTrue( reloaded.isReadTestsFromInStream() ); - assertEquals( cli, reloaded.getMainCliOptions() ); + Assert.assertNull(reloaded.getTestForFork()); + Assert.assertTrue(reloaded.isReadTestsFromInStream()); + assertEquals(cli, reloaded.getMainCliOptions()); } - public void testFailIfNoTests() - throws IOException - { + public void testFailIfNoTests() throws IOException { ProviderConfiguration reloaded = getReloadedProviderConfiguration(); - assertEquals( cli, reloaded.getMainCliOptions() ); + assertEquals(cli, reloaded.getMainCliOptions()); } - private ProviderConfiguration getReloadedProviderConfigurationForReadFromInStream() - throws IOException - { - return getReloadedProviderConfiguration( true ); + private ProviderConfiguration getReloadedProviderConfigurationForReadFromInStream() throws IOException { + return getReloadedProviderConfiguration(true); } - private ProviderConfiguration getReloadedProviderConfiguration() - throws IOException - { - return getReloadedProviderConfiguration( false ); + private ProviderConfiguration getReloadedProviderConfiguration() throws IOException { + return getReloadedProviderConfiguration(false); } - private ProviderConfiguration getReloadedProviderConfiguration( boolean readTestsFromInStream ) - throws IOException - { + private ProviderConfiguration getReloadedProviderConfiguration(boolean readTestsFromInStream) throws IOException { DirectoryScannerParameters directoryScannerParameters = getDirectoryScannerParametersWithoutSpecificTests(); ClassLoaderConfiguration forkConfiguration = getForkConfiguration(); ProviderConfiguration booterConfiguration = - getTestProviderConfiguration( directoryScannerParameters, readTestsFromInStream ); - assertEquals( cli, booterConfiguration.getMainCliOptions() ); - final StartupConfiguration testProviderConfiguration = getTestStartupConfiguration( forkConfiguration ); - return saveAndReload( booterConfiguration, testProviderConfiguration, readTestsFromInStream ); + getTestProviderConfiguration(directoryScannerParameters, readTestsFromInStream); + assertEquals(cli, booterConfiguration.getMainCliOptions()); + final StartupConfiguration testProviderConfiguration = getTestStartupConfiguration(forkConfiguration); + return saveAndReload(booterConfiguration, testProviderConfiguration, readTestsFromInStream); } - private DirectoryScannerParameters getDirectoryScannerParametersWithoutSpecificTests() - { - File aDir = new File( "." ); + private DirectoryScannerParameters getDirectoryScannerParametersWithoutSpecificTests() { + File aDir = new File("."); List includes = new ArrayList<>(); List excludes = new ArrayList<>(); - includes.add( "abc" ); - includes.add( "cde" ); - excludes.add( "xx1" ); - excludes.add( "xx2" ); + includes.add("abc"); + includes.add("cde"); + excludes.add("xx1"); + excludes.add("xx2"); - return new DirectoryScannerParameters( aDir, includes, excludes, Collections.emptyList(), - RunOrder.asString( RunOrder.DEFAULT ) ); + return new DirectoryScannerParameters( + aDir, includes, excludes, Collections.emptyList(), RunOrder.asString(RunOrder.DEFAULT)); } - private ProviderConfiguration saveAndReload( ProviderConfiguration booterConfiguration, - StartupConfiguration testProviderConfiguration, - boolean readTestsFromInStream ) - throws IOException - { - final ForkConfiguration forkConfiguration = ForkConfigurationTest.getForkConfiguration( basedir, null ); - PropertiesWrapper props = new PropertiesWrapper( new HashMap() ); - BooterSerializer booterSerializer = new BooterSerializer( forkConfiguration ); + private ProviderConfiguration saveAndReload( + ProviderConfiguration booterConfiguration, + StartupConfiguration testProviderConfiguration, + boolean readTestsFromInStream) + throws IOException { + final ForkConfiguration forkConfiguration = ForkConfigurationTest.getForkConfiguration(basedir, null); + PropertiesWrapper props = new PropertiesWrapper(new HashMap()); + BooterSerializer booterSerializer = new BooterSerializer(forkConfiguration); Object test; - if ( readTestsFromInStream ) - { + if (readTestsFromInStream) { test = null; - } - else - { + } else { test = "aTest"; } - final File propsTest = booterSerializer.serialize( props, booterConfiguration, testProviderConfiguration, test, - readTestsFromInStream, 51L, 1, "pipe://1" ); - BooterDeserializer booterDeserializer = new BooterDeserializer( new FileInputStream( propsTest ) ); - assertEquals( "51", (Object) booterDeserializer.getPluginPid() ); - assertEquals( "pipe://1", booterDeserializer.getConnectionString() ); + final File propsTest = booterSerializer.serialize( + props, booterConfiguration, testProviderConfiguration, test, readTestsFromInStream, 51L, 1, "pipe://1"); + BooterDeserializer booterDeserializer = new BooterDeserializer(new FileInputStream(propsTest)); + assertEquals("51", (Object) booterDeserializer.getPluginPid()); + assertEquals("pipe://1", booterDeserializer.getConnectionString()); return booterDeserializer.deserialize(); } - private ProviderConfiguration getTestProviderConfiguration( DirectoryScannerParameters directoryScannerParameters, - boolean readTestsFromInStream ) - { - File cwd = new File( "." ); - ReporterConfiguration reporterConfiguration = new ReporterConfiguration( cwd, true ); - TestRequest testSuiteDefinition = - new TestRequest( getSuiteXmlFileStrings(), getTestSourceDirectory(), - new TestListResolver( USER_REQUESTED_TEST + "#aUserRequestedTestMethod" ), - RERUN_FAILING_TEST_COUNT ); - RunOrderParameters runOrderParameters = new RunOrderParameters( RunOrder.DEFAULT, null ); - return new ProviderConfiguration( directoryScannerParameters, runOrderParameters, reporterConfiguration, - new TestArtifactInfo( "5.0", "ABC" ), testSuiteDefinition, new HashMap(), TEST_TYPED, - readTestsFromInStream, cli, 0, Shutdown.DEFAULT, 0 ); + private ProviderConfiguration getTestProviderConfiguration( + DirectoryScannerParameters directoryScannerParameters, boolean readTestsFromInStream) { + File cwd = new File("."); + ReporterConfiguration reporterConfiguration = new ReporterConfiguration(cwd, true); + TestRequest testSuiteDefinition = new TestRequest( + getSuiteXmlFileStrings(), + getTestSourceDirectory(), + new TestListResolver(USER_REQUESTED_TEST + "#aUserRequestedTestMethod"), + RERUN_FAILING_TEST_COUNT); + RunOrderParameters runOrderParameters = new RunOrderParameters(RunOrder.DEFAULT, null); + return new ProviderConfiguration( + directoryScannerParameters, + runOrderParameters, + reporterConfiguration, + new TestArtifactInfo("5.0", "ABC"), + testSuiteDefinition, + new HashMap(), + TEST_TYPED, + readTestsFromInStream, + cli, + 0, + Shutdown.DEFAULT, + 0); } - private StartupConfiguration getTestStartupConfiguration( ClassLoaderConfiguration classLoaderConfiguration ) - { - ClasspathConfiguration classpathConfiguration = new ClasspathConfiguration( true, true ); + private StartupConfiguration getTestStartupConfiguration(ClassLoaderConfiguration classLoaderConfiguration) { + ClasspathConfiguration classpathConfiguration = new ClasspathConfiguration(true, true); - return new StartupConfiguration( "com.provider", classpathConfiguration, classLoaderConfiguration, ALL, - Collections.emptyList() ); + return new StartupConfiguration( + "com.provider", + classpathConfiguration, + classLoaderConfiguration, + ALL, + Collections.emptyList()); } - private File getTestSourceDirectory() - { - return new File( "TestSrc" ); + private File getTestSourceDirectory() { + return new File("TestSrc"); } - private File[] getSuiteXmlFiles() - { - return new File[]{ new File( "A1" ), new File( "A2" ) }; + private File[] getSuiteXmlFiles() { + return new File[] {new File("A1"), new File("A2")}; } - private List getSuiteXmlFileStrings() - { - return Arrays.asList( "A1", "A2" ); + private List getSuiteXmlFileStrings() { + return Arrays.asList("A1", "A2"); } } diff --git a/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/booterclient/BooterDeserializerStartupConfigurationTest.java b/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/booterclient/BooterDeserializerStartupConfigurationTest.java index 9baf914af7..68f97be626 100644 --- a/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/booterclient/BooterDeserializerStartupConfigurationTest.java +++ b/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/booterclient/BooterDeserializerStartupConfigurationTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire.booterclient; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,51 +16,50 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.surefire.booterclient; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; import junit.framework.TestCase; -import org.apache.maven.surefire.booter.AbstractPathConfiguration; -import org.apache.maven.surefire.booter.BooterDeserializer; -import org.apache.maven.surefire.booter.ClassLoaderConfiguration; -import org.apache.maven.surefire.booter.Classpath; -import org.apache.maven.surefire.booter.ClasspathConfiguration; -import org.apache.maven.surefire.booter.PropertiesWrapper; -import org.apache.maven.surefire.booter.ProviderConfiguration; import org.apache.maven.surefire.api.booter.Shutdown; -import org.apache.maven.surefire.booter.StartupConfiguration; import org.apache.maven.surefire.api.cli.CommandLineOption; import org.apache.maven.surefire.api.report.ReporterConfiguration; -import org.apache.maven.surefire.shared.io.FileUtils; import org.apache.maven.surefire.api.testset.DirectoryScannerParameters; import org.apache.maven.surefire.api.testset.RunOrderParameters; import org.apache.maven.surefire.api.testset.TestArtifactInfo; import org.apache.maven.surefire.api.testset.TestListResolver; import org.apache.maven.surefire.api.testset.TestRequest; import org.apache.maven.surefire.api.util.RunOrder; +import org.apache.maven.surefire.booter.AbstractPathConfiguration; +import org.apache.maven.surefire.booter.BooterDeserializer; +import org.apache.maven.surefire.booter.ClassLoaderConfiguration; +import org.apache.maven.surefire.booter.Classpath; +import org.apache.maven.surefire.booter.ClasspathConfiguration; +import org.apache.maven.surefire.booter.PropertiesWrapper; +import org.apache.maven.surefire.booter.ProviderConfiguration; +import org.apache.maven.surefire.booter.StartupConfiguration; +import org.apache.maven.surefire.shared.io.FileUtils; import org.junit.After; import org.junit.Before; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; - -import static org.apache.maven.surefire.booter.ProcessCheckerType.ALL; import static org.apache.maven.surefire.api.cli.CommandLineOption.LOGGING_LEVEL_DEBUG; import static org.apache.maven.surefire.api.cli.CommandLineOption.REACTOR_FAIL_FAST; import static org.apache.maven.surefire.api.cli.CommandLineOption.SHOW_ERRORS; +import static org.apache.maven.surefire.booter.ProcessCheckerType.ALL; /** * Performs roundtrip testing of serialization/deserialization of The StartupConfiguration * * @author Kristian Rosenvold */ -public class BooterDeserializerStartupConfigurationTest - extends TestCase -{ +public class BooterDeserializerStartupConfigurationTest extends TestCase { private static int idx = 0; @@ -70,152 +67,152 @@ public class BooterDeserializerStartupConfigurationTest private final ClasspathConfiguration classpathConfiguration = createClasspathConfiguration(); - private final List cli = - Arrays.asList( LOGGING_LEVEL_DEBUG, SHOW_ERRORS, REACTOR_FAIL_FAST ); + private final List cli = Arrays.asList(LOGGING_LEVEL_DEBUG, SHOW_ERRORS, REACTOR_FAIL_FAST); @Before - public void setupDirectories() throws IOException - { - File target = new File( System.getProperty( "user.dir" ), "target" ); - basedir = new File( target, "BooterDeserializerProviderConfigurationTest-" + ++idx ); - FileUtils.deleteDirectory( basedir ); - assertTrue( basedir.mkdirs() ); + public void setupDirectories() throws IOException { + File target = new File(System.getProperty("user.dir"), "target"); + basedir = new File(target, "BooterDeserializerProviderConfigurationTest-" + ++idx); + FileUtils.deleteDirectory(basedir); + assertTrue(basedir.mkdirs()); } @After - public void deleteDirectories() throws IOException - { - FileUtils.deleteDirectory( basedir ); + public void deleteDirectories() throws IOException { + FileUtils.deleteDirectory(basedir); } - public void testProvider() - throws IOException - { - assertEquals( "com.provider", getReloadedStartupConfiguration().getProviderClassName() ); + public void testProvider() throws IOException { + assertEquals("com.provider", getReloadedStartupConfiguration().getProviderClassName()); } - public void testClassPathConfiguration() - throws IOException - { + public void testClassPathConfiguration() throws IOException { AbstractPathConfiguration reloadedClasspathConfiguration = - getReloadedStartupConfiguration().getClasspathConfiguration(); + getReloadedStartupConfiguration().getClasspathConfiguration(); - assertTrue( reloadedClasspathConfiguration instanceof ClasspathConfiguration ); - assertCpConfigEquals( classpathConfiguration, (ClasspathConfiguration) reloadedClasspathConfiguration ); + assertTrue(reloadedClasspathConfiguration instanceof ClasspathConfiguration); + assertCpConfigEquals(classpathConfiguration, (ClasspathConfiguration) reloadedClasspathConfiguration); } - public void testProcessChecker() throws IOException - { - assertEquals( ALL, getReloadedStartupConfiguration().getProcessChecker() ); + public void testProcessChecker() throws IOException { + assertEquals(ALL, getReloadedStartupConfiguration().getProcessChecker()); } - private void assertCpConfigEquals( ClasspathConfiguration expectedConfiguration, - ClasspathConfiguration actualConfiguration ) - { - assertEquals( expectedConfiguration.getTestClasspath().getClassPath(), - actualConfiguration.getTestClasspath().getClassPath() ); - assertEquals( expectedConfiguration.isEnableAssertions(), actualConfiguration.isEnableAssertions() ); - assertEquals( expectedConfiguration.isChildDelegation(), actualConfiguration.isChildDelegation() ); - assertEquals( expectedConfiguration.getProviderClasspath(), actualConfiguration.getProviderClasspath() ); - assertEquals( expectedConfiguration.getTestClasspath(), actualConfiguration.getTestClasspath() ); + private void assertCpConfigEquals( + ClasspathConfiguration expectedConfiguration, ClasspathConfiguration actualConfiguration) { + assertEquals( + expectedConfiguration.getTestClasspath().getClassPath(), + actualConfiguration.getTestClasspath().getClassPath()); + assertEquals(expectedConfiguration.isEnableAssertions(), actualConfiguration.isEnableAssertions()); + assertEquals(expectedConfiguration.isChildDelegation(), actualConfiguration.isChildDelegation()); + assertEquals(expectedConfiguration.getProviderClasspath(), actualConfiguration.getProviderClasspath()); + assertEquals(expectedConfiguration.getTestClasspath(), actualConfiguration.getTestClasspath()); } - public void testClassLoaderConfiguration() - throws IOException - { - assertFalse( getReloadedStartupConfiguration().isManifestOnlyJarRequestedAndUsable() ); + public void testClassLoaderConfiguration() throws IOException { + assertFalse(getReloadedStartupConfiguration().isManifestOnlyJarRequestedAndUsable()); } - public void testClassLoaderConfigurationTrues() - throws IOException - { + public void testClassLoaderConfigurationTrues() throws IOException { final StartupConfiguration testStartupConfiguration = - getTestStartupConfiguration( getManifestOnlyJarForkConfiguration() ); + getTestStartupConfiguration(getManifestOnlyJarForkConfiguration()); boolean current = testStartupConfiguration.isManifestOnlyJarRequestedAndUsable(); - assertEquals( current, saveAndReload( testStartupConfiguration ).isManifestOnlyJarRequestedAndUsable() ); + assertEquals(current, saveAndReload(testStartupConfiguration).isManifestOnlyJarRequestedAndUsable()); } - public void testProcessCheckerAll() throws IOException - { - assertEquals( ALL, getReloadedStartupConfiguration().getProcessChecker() ); + public void testProcessCheckerAll() throws IOException { + assertEquals(ALL, getReloadedStartupConfiguration().getProcessChecker()); } - public void testProcessCheckerNull() throws IOException - { - StartupConfiguration startupConfiguration = new StartupConfiguration( "com.provider", classpathConfiguration, - getManifestOnlyJarForkConfiguration(), null, Collections.emptyList() ); - assertNull( saveAndReload( startupConfiguration ).getProcessChecker() ); + public void testProcessCheckerNull() throws IOException { + StartupConfiguration startupConfiguration = new StartupConfiguration( + "com.provider", + classpathConfiguration, + getManifestOnlyJarForkConfiguration(), + null, + Collections.emptyList()); + assertNull(saveAndReload(startupConfiguration).getProcessChecker()); } - private ClasspathConfiguration createClasspathConfiguration() - { - Classpath testClassPath = new Classpath( Arrays.asList( "CP1", "CP2" ) ); - Classpath providerClasspath = new Classpath( Arrays.asList( "SP1", "SP2" ) ); - return new ClasspathConfiguration( testClassPath, providerClasspath, Classpath.emptyClasspath(), true, true ); + private ClasspathConfiguration createClasspathConfiguration() { + Classpath testClassPath = new Classpath(Arrays.asList("CP1", "CP2")); + Classpath providerClasspath = new Classpath(Arrays.asList("SP1", "SP2")); + return new ClasspathConfiguration(testClassPath, providerClasspath, Classpath.emptyClasspath(), true, true); } - private static ClassLoaderConfiguration getSystemClassLoaderConfiguration() - { - return new ClassLoaderConfiguration( true, false ); + private static ClassLoaderConfiguration getSystemClassLoaderConfiguration() { + return new ClassLoaderConfiguration(true, false); } - private static ClassLoaderConfiguration getManifestOnlyJarForkConfiguration() - { - return new ClassLoaderConfiguration( true, true ); + private static ClassLoaderConfiguration getManifestOnlyJarForkConfiguration() { + return new ClassLoaderConfiguration(true, true); } - private StartupConfiguration getReloadedStartupConfiguration() - throws IOException - { + private StartupConfiguration getReloadedStartupConfiguration() throws IOException { ClassLoaderConfiguration classLoaderConfiguration = getSystemClassLoaderConfiguration(); - return saveAndReload( getTestStartupConfiguration( classLoaderConfiguration ) ); + return saveAndReload(getTestStartupConfiguration(classLoaderConfiguration)); } - private StartupConfiguration saveAndReload( StartupConfiguration startupConfiguration ) - throws IOException - { - final ForkConfiguration forkConfiguration = ForkConfigurationTest.getForkConfiguration( basedir, null ); - PropertiesWrapper props = new PropertiesWrapper( new HashMap() ); - BooterSerializer booterSerializer = new BooterSerializer( forkConfiguration ); + private StartupConfiguration saveAndReload(StartupConfiguration startupConfiguration) throws IOException { + final ForkConfiguration forkConfiguration = ForkConfigurationTest.getForkConfiguration(basedir, null); + PropertiesWrapper props = new PropertiesWrapper(new HashMap()); + BooterSerializer booterSerializer = new BooterSerializer(forkConfiguration); String aTest = "aTest"; - File propsTest = booterSerializer.serialize( props, getProviderConfiguration(), startupConfiguration, aTest, - false, null, 1, "tcp://localhost:63003" ); - BooterDeserializer booterDeserializer = new BooterDeserializer( new FileInputStream( propsTest ) ); - assertNull( booterDeserializer.getPluginPid() ); - assertEquals( "tcp://localhost:63003", booterDeserializer.getConnectionString() ); + File propsTest = booterSerializer.serialize( + props, + getProviderConfiguration(), + startupConfiguration, + aTest, + false, + null, + 1, + "tcp://localhost:63003"); + BooterDeserializer booterDeserializer = new BooterDeserializer(new FileInputStream(propsTest)); + assertNull(booterDeserializer.getPluginPid()); + assertEquals("tcp://localhost:63003", booterDeserializer.getConnectionString()); return booterDeserializer.getStartupConfiguration(); } - private ProviderConfiguration getProviderConfiguration() - { - File cwd = new File( "." ); - DirectoryScannerParameters directoryScannerParameters = - new DirectoryScannerParameters( cwd, new ArrayList(), new ArrayList(), - new ArrayList(), "hourly" ); - ReporterConfiguration reporterConfiguration = new ReporterConfiguration( cwd, true ); - TestRequest testSuiteDefinition = - new TestRequest( Arrays.asList( getSuiteXmlFileStrings() ), getTestSourceDirectory(), - new TestListResolver( "aUserRequestedTest#aUserRequestedTestMethod" ) ); - - RunOrderParameters runOrderParameters = new RunOrderParameters( RunOrder.DEFAULT, null ); - return new ProviderConfiguration( directoryScannerParameters, runOrderParameters, reporterConfiguration, - new TestArtifactInfo( "5.0", "ABC" ), testSuiteDefinition, new HashMap(), - BooterDeserializerProviderConfigurationTest.TEST_TYPED, true, cli, 0, Shutdown.DEFAULT, 0 ); - } - - private StartupConfiguration getTestStartupConfiguration( ClassLoaderConfiguration classLoaderConfiguration ) - { - return new StartupConfiguration( "com.provider", classpathConfiguration, classLoaderConfiguration, ALL, - Collections.emptyList() ); - } - - private File getTestSourceDirectory() - { - return new File( "TestSrc" ); - } - - private String[] getSuiteXmlFileStrings() - { - return new String[]{ "A1", "A2" }; + private ProviderConfiguration getProviderConfiguration() { + File cwd = new File("."); + DirectoryScannerParameters directoryScannerParameters = new DirectoryScannerParameters( + cwd, new ArrayList(), new ArrayList(), new ArrayList(), "hourly"); + ReporterConfiguration reporterConfiguration = new ReporterConfiguration(cwd, true); + TestRequest testSuiteDefinition = new TestRequest( + Arrays.asList(getSuiteXmlFileStrings()), + getTestSourceDirectory(), + new TestListResolver("aUserRequestedTest#aUserRequestedTestMethod")); + + RunOrderParameters runOrderParameters = new RunOrderParameters(RunOrder.DEFAULT, null); + return new ProviderConfiguration( + directoryScannerParameters, + runOrderParameters, + reporterConfiguration, + new TestArtifactInfo("5.0", "ABC"), + testSuiteDefinition, + new HashMap(), + BooterDeserializerProviderConfigurationTest.TEST_TYPED, + true, + cli, + 0, + Shutdown.DEFAULT, + 0); + } + + private StartupConfiguration getTestStartupConfiguration(ClassLoaderConfiguration classLoaderConfiguration) { + return new StartupConfiguration( + "com.provider", + classpathConfiguration, + classLoaderConfiguration, + ALL, + Collections.emptyList()); + } + + private File getTestSourceDirectory() { + return new File("TestSrc"); + } + + private String[] getSuiteXmlFileStrings() { + return new String[] {"A1", "A2"}; } } diff --git a/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/booterclient/ChecksumCalculatorTest.java b/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/booterclient/ChecksumCalculatorTest.java index e5b91d373d..920c78a7e4 100644 --- a/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/booterclient/ChecksumCalculatorTest.java +++ b/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/booterclient/ChecksumCalculatorTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire.booterclient; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.surefire.booterclient; import org.junit.Test; @@ -26,13 +25,11 @@ /** * Tests for {@link ChecksumCalculator}. */ -public class ChecksumCalculatorTest -{ +public class ChecksumCalculatorTest { @Test - public void testGetSha1() - { + public void testGetSha1() { final ChecksumCalculator calculator = new ChecksumCalculator(); - calculator.add( "foö 🔥 Россия 한국 中国" ); - assertEquals( "3421557EBE66A4741CA51C8D610AB1AB41D1693B", calculator.getSha1() ); + calculator.add("foö 🔥 Россия 한국 中国"); + assertEquals("3421557EBE66A4741CA51C8D610AB1AB41D1693B", calculator.getSha1()); } } diff --git a/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/booterclient/DefaultForkConfigurationTest.java b/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/booterclient/DefaultForkConfigurationTest.java index ad668856e9..f3498c9e24 100644 --- a/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/booterclient/DefaultForkConfigurationTest.java +++ b/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/booterclient/DefaultForkConfigurationTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire.booterclient; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,15 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.surefire.booterclient; + +import javax.annotation.Nonnull; + +import java.io.File; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import java.util.Properties; import org.apache.maven.plugin.surefire.booterclient.lazytestprovider.Commandline; import org.apache.maven.plugin.surefire.log.api.ConsoleLogger; @@ -35,13 +42,6 @@ import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; -import javax.annotation.Nonnull; -import java.io.File; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; -import java.util.Properties; - import static java.util.Collections.singleton; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.anyString; @@ -63,11 +63,10 @@ * @author Tibor Digana (tibor17) * @since 2.21 */ -@RunWith( PowerMockRunner.class ) -@PrepareForTest( { DefaultForkConfiguration.class, Relocator.class } ) -@PowerMockIgnore( { "org.jacoco.agent.rt.*", "com.vladium.emma.rt.*" } ) -public class DefaultForkConfigurationTest -{ +@RunWith(PowerMockRunner.class) +@PrepareForTest({DefaultForkConfiguration.class, Relocator.class}) +@PowerMockIgnore({"org.jacoco.agent.rt.*", "com.vladium.emma.rt.*"}) +public class DefaultForkConfigurationTest { private Classpath booterClasspath; private File tempDirectory; private String debugLine; @@ -84,12 +83,11 @@ public class DefaultForkConfigurationTest private ForkNodeFactory forkNodeFactory; @Before - public void setup() - { - booterClasspath = new Classpath( singleton( "provider.jar" ) ); - tempDirectory = new File( "target/surefire" ); + public void setup() { + booterClasspath = new Classpath(singleton("provider.jar")); + tempDirectory = new File("target/surefire"); debugLine = ""; - workingDirectory = new File( "." ); + workingDirectory = new File("."); modelProperties = new Properties(); argLine = null; environmentVariables = new HashMap<>(); @@ -98,249 +96,327 @@ public void setup() forkCount = 2; reuseForks = true; pluginPlatform = new Platform(); - log = mock( ConsoleLogger.class ); - forkNodeFactory = mock( ForkNodeFactory.class ); + log = mock(ConsoleLogger.class); + forkNodeFactory = mock(ForkNodeFactory.class); } @Test - public void shouldBeNullArgLine() throws Exception - { - DefaultForkConfiguration config = new DefaultForkConfiguration( booterClasspath, tempDirectory, debugLine, - workingDirectory, modelProperties, argLine, environmentVariables, excludedEnvironmentVariables, - debug, forkCount, reuseForks, pluginPlatform, log, forkNodeFactory ) - { - - @Override - protected void resolveClasspath( @Nonnull Commandline cli, - @Nonnull String booterThatHasMainMethod, - @Nonnull StartupConfiguration config, - @Nonnull File dumpLogDirectory ) - { - } - }; - - DefaultForkConfiguration mockedConfig = spy( config ); - String newArgLine = invokeMethod( mockedConfig, "newJvmArgLine", new Class[] { int.class }, 2 ); - verifyPrivate( mockedConfig, times( 1 ) ).invoke( "interpolateArgLineWithPropertyExpressions" ); - verifyPrivate( mockedConfig, times( 1 ) ).invoke( "extendJvmArgLine", eq( "" ) ); - assertThat( newArgLine ).isEmpty(); + public void shouldBeNullArgLine() throws Exception { + DefaultForkConfiguration config = + new DefaultForkConfiguration( + booterClasspath, + tempDirectory, + debugLine, + workingDirectory, + modelProperties, + argLine, + environmentVariables, + excludedEnvironmentVariables, + debug, + forkCount, + reuseForks, + pluginPlatform, + log, + forkNodeFactory) { + + @Override + protected void resolveClasspath( + @Nonnull Commandline cli, + @Nonnull String booterThatHasMainMethod, + @Nonnull StartupConfiguration config, + @Nonnull File dumpLogDirectory) {} + }; + + DefaultForkConfiguration mockedConfig = spy(config); + String newArgLine = invokeMethod(mockedConfig, "newJvmArgLine", new Class[] {int.class}, 2); + verifyPrivate(mockedConfig, times(1)).invoke("interpolateArgLineWithPropertyExpressions"); + verifyPrivate(mockedConfig, times(1)).invoke("extendJvmArgLine", eq("")); + assertThat(newArgLine).isEmpty(); } @Test - public void shouldBeEmptyArgLine() throws Exception - { + public void shouldBeEmptyArgLine() throws Exception { argLine = ""; - DefaultForkConfiguration config = new DefaultForkConfiguration( booterClasspath, tempDirectory, debugLine, - workingDirectory, modelProperties, argLine, environmentVariables, excludedEnvironmentVariables, - debug, forkCount, reuseForks, pluginPlatform, log, forkNodeFactory ) - { - - @Override - protected void resolveClasspath( @Nonnull Commandline cli, - @Nonnull String booterThatHasMainMethod, - @Nonnull StartupConfiguration config, - @Nonnull File dumpLogDirectory ) - { - } - }; - - DefaultForkConfiguration mockedConfig = spy( config ); - String newArgLine = invokeMethod( mockedConfig, "newJvmArgLine", new Class[] { int.class }, 2 ); - verifyPrivate( mockedConfig, times( 1 ) ).invoke( "interpolateArgLineWithPropertyExpressions" ); - verifyPrivate( mockedConfig, times( 1 ) ).invoke( "extendJvmArgLine", eq( "" ) ); - assertThat( newArgLine ).isEmpty(); + DefaultForkConfiguration config = + new DefaultForkConfiguration( + booterClasspath, + tempDirectory, + debugLine, + workingDirectory, + modelProperties, + argLine, + environmentVariables, + excludedEnvironmentVariables, + debug, + forkCount, + reuseForks, + pluginPlatform, + log, + forkNodeFactory) { + + @Override + protected void resolveClasspath( + @Nonnull Commandline cli, + @Nonnull String booterThatHasMainMethod, + @Nonnull StartupConfiguration config, + @Nonnull File dumpLogDirectory) {} + }; + + DefaultForkConfiguration mockedConfig = spy(config); + String newArgLine = invokeMethod(mockedConfig, "newJvmArgLine", new Class[] {int.class}, 2); + verifyPrivate(mockedConfig, times(1)).invoke("interpolateArgLineWithPropertyExpressions"); + verifyPrivate(mockedConfig, times(1)).invoke("extendJvmArgLine", eq("")); + assertThat(newArgLine).isEmpty(); } @Test - public void shouldBeEmptyArgLineInsteadOfNewLines() throws Exception - { + public void shouldBeEmptyArgLineInsteadOfNewLines() throws Exception { argLine = "\n\r"; - DefaultForkConfiguration config = new DefaultForkConfiguration( booterClasspath, tempDirectory, debugLine, - workingDirectory, modelProperties, argLine, environmentVariables, excludedEnvironmentVariables, - debug, forkCount, reuseForks, pluginPlatform, log, forkNodeFactory ) - { - - @Override - protected void resolveClasspath( @Nonnull Commandline cli, - @Nonnull String booterThatHasMainMethod, - @Nonnull StartupConfiguration config, - @Nonnull File dumpLogDirectory ) - { - } - }; - - DefaultForkConfiguration mockedConfig = spy( config ); - String newArgLine = invokeMethod( mockedConfig, "newJvmArgLine", new Class[] { int.class }, 2 ); - verifyPrivate( mockedConfig, times( 1 ) ).invoke( "interpolateArgLineWithPropertyExpressions" ); - verifyPrivate( mockedConfig, times( 1 ) ).invoke( "extendJvmArgLine", eq( "" ) ); - assertThat( newArgLine ).isEmpty(); + DefaultForkConfiguration config = + new DefaultForkConfiguration( + booterClasspath, + tempDirectory, + debugLine, + workingDirectory, + modelProperties, + argLine, + environmentVariables, + excludedEnvironmentVariables, + debug, + forkCount, + reuseForks, + pluginPlatform, + log, + forkNodeFactory) { + + @Override + protected void resolveClasspath( + @Nonnull Commandline cli, + @Nonnull String booterThatHasMainMethod, + @Nonnull StartupConfiguration config, + @Nonnull File dumpLogDirectory) {} + }; + + DefaultForkConfiguration mockedConfig = spy(config); + String newArgLine = invokeMethod(mockedConfig, "newJvmArgLine", new Class[] {int.class}, 2); + verifyPrivate(mockedConfig, times(1)).invoke("interpolateArgLineWithPropertyExpressions"); + verifyPrivate(mockedConfig, times(1)).invoke("extendJvmArgLine", eq("")); + assertThat(newArgLine).isEmpty(); } @Test - public void shouldBeWithoutEscaping() throws Exception - { + public void shouldBeWithoutEscaping() throws Exception { argLine = "-Dfile.encoding=UTF-8"; - DefaultForkConfiguration config = new DefaultForkConfiguration( booterClasspath, tempDirectory, debugLine, - workingDirectory, modelProperties, argLine, environmentVariables, excludedEnvironmentVariables, - debug, forkCount, reuseForks, pluginPlatform, log, forkNodeFactory ) - { - - @Override - protected void resolveClasspath( @Nonnull Commandline cli, - @Nonnull String booterThatHasMainMethod, - @Nonnull StartupConfiguration config, - @Nonnull File dumpLogDirectory ) - { - } - }; - - DefaultForkConfiguration mockedConfig = spy( config ); - String newArgLine = invokeMethod( mockedConfig, "newJvmArgLine", new Class[] { int.class }, 2 ); - verifyPrivate( mockedConfig, times( 1 ) ).invoke( "interpolateArgLineWithPropertyExpressions" ); - verifyPrivate( mockedConfig, times( 1 ) ).invoke( "extendJvmArgLine", eq( "-Dfile.encoding=UTF-8" ) ); - assertThat( newArgLine ).isEqualTo( "-Dfile.encoding=UTF-8" ); + DefaultForkConfiguration config = + new DefaultForkConfiguration( + booterClasspath, + tempDirectory, + debugLine, + workingDirectory, + modelProperties, + argLine, + environmentVariables, + excludedEnvironmentVariables, + debug, + forkCount, + reuseForks, + pluginPlatform, + log, + forkNodeFactory) { + + @Override + protected void resolveClasspath( + @Nonnull Commandline cli, + @Nonnull String booterThatHasMainMethod, + @Nonnull StartupConfiguration config, + @Nonnull File dumpLogDirectory) {} + }; + + DefaultForkConfiguration mockedConfig = spy(config); + String newArgLine = invokeMethod(mockedConfig, "newJvmArgLine", new Class[] {int.class}, 2); + verifyPrivate(mockedConfig, times(1)).invoke("interpolateArgLineWithPropertyExpressions"); + verifyPrivate(mockedConfig, times(1)).invoke("extendJvmArgLine", eq("-Dfile.encoding=UTF-8")); + assertThat(newArgLine).isEqualTo("-Dfile.encoding=UTF-8"); } @Test - public void shouldBeWithEscaping() throws Exception - { - modelProperties.put( "encoding", "UTF-8" ); + public void shouldBeWithEscaping() throws Exception { + modelProperties.put("encoding", "UTF-8"); argLine = "-Dfile.encoding=@{encoding}"; - DefaultForkConfiguration config = new DefaultForkConfiguration( booterClasspath, tempDirectory, debugLine, - workingDirectory, modelProperties, argLine, environmentVariables, excludedEnvironmentVariables, - debug, forkCount, reuseForks, pluginPlatform, log, forkNodeFactory ) - { - - @Override - protected void resolveClasspath( @Nonnull Commandline cli, - @Nonnull String booterThatHasMainMethod, - @Nonnull StartupConfiguration config, - @Nonnull File dumpLogDirectory ) - { - } - }; - - DefaultForkConfiguration mockedConfig = spy( config ); - String newArgLine = invokeMethod( mockedConfig, "newJvmArgLine", new Class[] { int.class }, 2 ); - verifyPrivate( mockedConfig, times( 1 ) ).invoke( "interpolateArgLineWithPropertyExpressions" ); - verifyPrivate( mockedConfig, times( 1 ) ).invoke( "extendJvmArgLine", eq( "-Dfile.encoding=UTF-8" ) ); - assertThat( newArgLine ).isEqualTo( "-Dfile.encoding=UTF-8" ); + DefaultForkConfiguration config = + new DefaultForkConfiguration( + booterClasspath, + tempDirectory, + debugLine, + workingDirectory, + modelProperties, + argLine, + environmentVariables, + excludedEnvironmentVariables, + debug, + forkCount, + reuseForks, + pluginPlatform, + log, + forkNodeFactory) { + + @Override + protected void resolveClasspath( + @Nonnull Commandline cli, + @Nonnull String booterThatHasMainMethod, + @Nonnull StartupConfiguration config, + @Nonnull File dumpLogDirectory) {} + }; + + DefaultForkConfiguration mockedConfig = spy(config); + String newArgLine = invokeMethod(mockedConfig, "newJvmArgLine", new Class[] {int.class}, 2); + verifyPrivate(mockedConfig, times(1)).invoke("interpolateArgLineWithPropertyExpressions"); + verifyPrivate(mockedConfig, times(1)).invoke("extendJvmArgLine", eq("-Dfile.encoding=UTF-8")); + assertThat(newArgLine).isEqualTo("-Dfile.encoding=UTF-8"); } @Test - public void shouldBeWhitespaceInsteadOfNewLines() throws Exception - { + public void shouldBeWhitespaceInsteadOfNewLines() throws Exception { argLine = "a\n\rb"; - DefaultForkConfiguration config = new DefaultForkConfiguration( booterClasspath, tempDirectory, debugLine, - workingDirectory, modelProperties, argLine, environmentVariables, excludedEnvironmentVariables, - debug, forkCount, reuseForks, pluginPlatform, log, forkNodeFactory ) - { - - @Override - protected void resolveClasspath( @Nonnull Commandline cli, - @Nonnull String booterThatHasMainMethod, - @Nonnull StartupConfiguration config, - @Nonnull File dumpLogDirectory ) - { - } - }; - - DefaultForkConfiguration mockedConfig = spy( config ); - String newArgLine = invokeMethod( mockedConfig, "newJvmArgLine", new Class[] { int.class }, 2 ); - verifyPrivate( mockedConfig, times( 1 ) ).invoke( "interpolateArgLineWithPropertyExpressions" ); - verifyPrivate( mockedConfig, times( 1 ) ).invoke( "extendJvmArgLine", eq( "a b" ) ); - assertThat( newArgLine ).isEqualTo( "a b" ); + DefaultForkConfiguration config = + new DefaultForkConfiguration( + booterClasspath, + tempDirectory, + debugLine, + workingDirectory, + modelProperties, + argLine, + environmentVariables, + excludedEnvironmentVariables, + debug, + forkCount, + reuseForks, + pluginPlatform, + log, + forkNodeFactory) { + + @Override + protected void resolveClasspath( + @Nonnull Commandline cli, + @Nonnull String booterThatHasMainMethod, + @Nonnull StartupConfiguration config, + @Nonnull File dumpLogDirectory) {} + }; + + DefaultForkConfiguration mockedConfig = spy(config); + String newArgLine = invokeMethod(mockedConfig, "newJvmArgLine", new Class[] {int.class}, 2); + verifyPrivate(mockedConfig, times(1)).invoke("interpolateArgLineWithPropertyExpressions"); + verifyPrivate(mockedConfig, times(1)).invoke("extendJvmArgLine", eq("a b")); + assertThat(newArgLine).isEqualTo("a b"); } @Test - public void shouldEscapeThreadNumber() throws Exception - { + public void shouldEscapeThreadNumber() throws Exception { argLine = "-Dthread=${surefire.threadNumber}"; - DefaultForkConfiguration config = new DefaultForkConfiguration( booterClasspath, tempDirectory, debugLine, - workingDirectory, modelProperties, argLine, environmentVariables, excludedEnvironmentVariables, - debug, forkCount, reuseForks, pluginPlatform, log, forkNodeFactory ) - { - - @Override - protected void resolveClasspath( @Nonnull Commandline cli, - @Nonnull String booterThatHasMainMethod, - @Nonnull StartupConfiguration config, - @Nonnull File dumpLogDirectory ) - { - } - }; - - DefaultForkConfiguration mockedConfig = spy( config ); - String newArgLine = invokeMethod( mockedConfig, "newJvmArgLine", new Class[] { int.class }, 2 ); - verifyPrivate( mockedConfig, times( 1 ) ).invoke( "interpolateArgLineWithPropertyExpressions" ); - verifyPrivate( mockedConfig, times( 1 ) ).invoke( "extendJvmArgLine", eq( "-Dthread=" + forkCount ) ); - assertThat( newArgLine ).isEqualTo( "-Dthread=" + forkCount ); + DefaultForkConfiguration config = + new DefaultForkConfiguration( + booterClasspath, + tempDirectory, + debugLine, + workingDirectory, + modelProperties, + argLine, + environmentVariables, + excludedEnvironmentVariables, + debug, + forkCount, + reuseForks, + pluginPlatform, + log, + forkNodeFactory) { + + @Override + protected void resolveClasspath( + @Nonnull Commandline cli, + @Nonnull String booterThatHasMainMethod, + @Nonnull StartupConfiguration config, + @Nonnull File dumpLogDirectory) {} + }; + + DefaultForkConfiguration mockedConfig = spy(config); + String newArgLine = invokeMethod(mockedConfig, "newJvmArgLine", new Class[] {int.class}, 2); + verifyPrivate(mockedConfig, times(1)).invoke("interpolateArgLineWithPropertyExpressions"); + verifyPrivate(mockedConfig, times(1)).invoke("extendJvmArgLine", eq("-Dthread=" + forkCount)); + assertThat(newArgLine).isEqualTo("-Dthread=" + forkCount); } @Test - public void shouldEscapeForkNumber() throws Exception - { + public void shouldEscapeForkNumber() throws Exception { argLine = "-Dthread=${surefire.forkNumber}"; - DefaultForkConfiguration config = new DefaultForkConfiguration( booterClasspath, tempDirectory, debugLine, - workingDirectory, modelProperties, argLine, environmentVariables, excludedEnvironmentVariables, - debug, forkCount, reuseForks, pluginPlatform, log, forkNodeFactory ) - { - - @Override - protected void resolveClasspath( @Nonnull Commandline cli, - @Nonnull String booterThatHasMainMethod, - @Nonnull StartupConfiguration config, - @Nonnull File dumpLogDirectory ) - { - } - }; - - DefaultForkConfiguration mockedConfig = spy( config ); - String newArgLine = invokeMethod( mockedConfig, "newJvmArgLine", new Class[] { int.class }, 2 ); - verifyPrivate( mockedConfig, times( 1 ) ).invoke( "interpolateArgLineWithPropertyExpressions" ); - verifyPrivate( mockedConfig, times( 1 ) ).invoke( "extendJvmArgLine", eq( "-Dthread=" + forkCount ) ); - assertThat( newArgLine ).isEqualTo( "-Dthread=" + forkCount ); + DefaultForkConfiguration config = + new DefaultForkConfiguration( + booterClasspath, + tempDirectory, + debugLine, + workingDirectory, + modelProperties, + argLine, + environmentVariables, + excludedEnvironmentVariables, + debug, + forkCount, + reuseForks, + pluginPlatform, + log, + forkNodeFactory) { + + @Override + protected void resolveClasspath( + @Nonnull Commandline cli, + @Nonnull String booterThatHasMainMethod, + @Nonnull StartupConfiguration config, + @Nonnull File dumpLogDirectory) {} + }; + + DefaultForkConfiguration mockedConfig = spy(config); + String newArgLine = invokeMethod(mockedConfig, "newJvmArgLine", new Class[] {int.class}, 2); + verifyPrivate(mockedConfig, times(1)).invoke("interpolateArgLineWithPropertyExpressions"); + verifyPrivate(mockedConfig, times(1)).invoke("extendJvmArgLine", eq("-Dthread=" + forkCount)); + assertThat(newArgLine).isEqualTo("-Dthread=" + forkCount); } @Test - public void shouldRelocateBooterClassWhenShadefire() throws Exception - { - ClassLoaderConfiguration clc = new ClassLoaderConfiguration( true, true ); - ClasspathConfiguration cc = new ClasspathConfiguration( true, true ); - StartupConfiguration conf = new StartupConfiguration( "org.apache.maven.shadefire.surefire.MyProvider", - cc, clc, null, Collections.emptyList() ); - StartupConfiguration confMock = spy( conf ); - mockStatic( Relocator.class ); - when( Relocator.relocate( anyString() ) ).thenCallRealMethod(); - - String cls = invokeMethod( DefaultForkConfiguration.class, "findStartClass", confMock ); - - verify( confMock, times( 1 ) ).isShadefire(); - verifyStatic( Relocator.class, times( 1 ) ); - Relocator.relocate( eq( ForkedBooter.class.getName() ) ); - - assertThat( cls ).isEqualTo( "org.apache.maven.shadefire.surefire.booter.ForkedBooter" ); - assertThat( confMock.isShadefire() ).isTrue(); + public void shouldRelocateBooterClassWhenShadefire() throws Exception { + ClassLoaderConfiguration clc = new ClassLoaderConfiguration(true, true); + ClasspathConfiguration cc = new ClasspathConfiguration(true, true); + StartupConfiguration conf = new StartupConfiguration( + "org.apache.maven.shadefire.surefire.MyProvider", cc, clc, null, Collections.emptyList()); + StartupConfiguration confMock = spy(conf); + mockStatic(Relocator.class); + when(Relocator.relocate(anyString())).thenCallRealMethod(); + + String cls = invokeMethod(DefaultForkConfiguration.class, "findStartClass", confMock); + + verify(confMock, times(1)).isShadefire(); + verifyStatic(Relocator.class, times(1)); + Relocator.relocate(eq(ForkedBooter.class.getName())); + + assertThat(cls).isEqualTo("org.apache.maven.shadefire.surefire.booter.ForkedBooter"); + assertThat(confMock.isShadefire()).isTrue(); } @Test - public void shouldNotRelocateBooterClass() throws Exception - { - ClassLoaderConfiguration clc = new ClassLoaderConfiguration( true, true ); - ClasspathConfiguration cc = new ClasspathConfiguration( true, true ); - StartupConfiguration conf = new StartupConfiguration( "org.apache.maven.surefire.MyProvider", - cc, clc, null, Collections.emptyList() ); - StartupConfiguration confMock = spy( conf ); - mockStatic( Relocator.class ); - when( Relocator.relocate( anyString() ) ).thenCallRealMethod(); - - String cls = invokeMethod( DefaultForkConfiguration.class, "findStartClass", confMock ); - - verify( confMock, times( 1 ) ).isShadefire(); - verifyStatic( Relocator.class, never() ); - Relocator.relocate( eq( ForkedBooter.class.getName() ) ); - - assertThat( cls ).isEqualTo( "org.apache.maven.surefire.booter.ForkedBooter" ); - assertThat( confMock.isShadefire() ).isFalse(); + public void shouldNotRelocateBooterClass() throws Exception { + ClassLoaderConfiguration clc = new ClassLoaderConfiguration(true, true); + ClasspathConfiguration cc = new ClasspathConfiguration(true, true); + StartupConfiguration conf = new StartupConfiguration( + "org.apache.maven.surefire.MyProvider", cc, clc, null, Collections.emptyList()); + StartupConfiguration confMock = spy(conf); + mockStatic(Relocator.class); + when(Relocator.relocate(anyString())).thenCallRealMethod(); + + String cls = invokeMethod(DefaultForkConfiguration.class, "findStartClass", confMock); + + verify(confMock, times(1)).isShadefire(); + verifyStatic(Relocator.class, never()); + Relocator.relocate(eq(ForkedBooter.class.getName())); + + assertThat(cls).isEqualTo("org.apache.maven.surefire.booter.ForkedBooter"); + assertThat(confMock.isShadefire()).isFalse(); } } diff --git a/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/booterclient/ForkConfigurationTest.java b/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/booterclient/ForkConfigurationTest.java index d1771889eb..752a64ef93 100644 --- a/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/booterclient/ForkConfigurationTest.java +++ b/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/booterclient/ForkConfigurationTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire.booterclient; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,20 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.surefire.booterclient; + +import javax.annotation.Nonnull; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Properties; import org.apache.maven.plugin.surefire.JdkAttributes; import org.apache.maven.plugin.surefire.booterclient.lazytestprovider.Commandline; @@ -36,27 +48,15 @@ import org.junit.Before; import org.junit.Test; -import javax.annotation.Nonnull; -import java.io.File; -import java.io.IOException; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Properties; - import static java.lang.String.join; import static java.nio.file.Files.readAllBytes; import static java.util.Collections.singletonList; +import static org.apache.commons.io.FileUtils.getTempDirectory; import static org.apache.maven.surefire.api.util.internal.StringUtils.NL; import static org.apache.maven.surefire.booter.Classpath.emptyClasspath; import static org.apache.maven.surefire.booter.ProcessCheckerType.ALL; import static org.apache.maven.surefire.shared.lang3.SystemUtils.IS_OS_WINDOWS; import static org.assertj.core.api.Assertions.assertThat; -import static org.apache.commons.io.FileUtils.getTempDirectory; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; @@ -65,345 +65,346 @@ /** * */ -public class ForkConfigurationTest -{ - private static final StartupConfiguration STARTUP_CONFIG = new StartupConfiguration( "", - new ClasspathConfiguration( true, true ), - new ClassLoaderConfiguration( true, true ), ALL, Collections.emptyList() ); +public class ForkConfigurationTest { + private static final StartupConfiguration STARTUP_CONFIG = new StartupConfiguration( + "", + new ClasspathConfiguration(true, true), + new ClassLoaderConfiguration(true, true), + ALL, + Collections.emptyList()); private static int idx = 0; private File basedir; @Before - public void setupDirectories() throws IOException - { - File target = new File( System.getProperty( "user.dir" ), "target" ); - basedir = new File( target, "SUREFIRE-1136-" + ++idx ); - FileUtils.deleteDirectory( basedir ); - assertTrue( basedir.mkdirs() ); + public void setupDirectories() throws IOException { + File target = new File(System.getProperty("user.dir"), "target"); + basedir = new File(target, "SUREFIRE-1136-" + ++idx); + FileUtils.deleteDirectory(basedir); + assertTrue(basedir.mkdirs()); } @After - public void deleteDirectories() throws IOException - { - FileUtils.deleteDirectory( basedir ); + public void deleteDirectories() throws IOException { + FileUtils.deleteDirectory(basedir); } @Test - public void testEnv() throws Exception - { + public void testEnv() throws Exception { Map env = new HashMap<>(); - env.put( "key1", "val1" ); - env.put( "key2", "val2" ); - env.put( "key3", "val3" ); + env.put("key1", "val1"); + env.put("key2", "val2"); + env.put("key3", "val3"); String[] exclEnv = {"PATH"}; - String jvm = new File( new File( System.getProperty( "java.home" ), "bin" ), "java" ).getCanonicalPath(); - Platform platform = new Platform().withJdkExecAttributesForTests( new JdkAttributes( jvm, false ) ); - - ForkConfiguration config = new DefaultForkConfiguration( emptyClasspath(), basedir, "", basedir, - new Properties(), "", env, exclEnv, false, 1, true, - platform, new NullConsoleLogger(), mock( ForkNodeFactory.class ) ) - { - - @Override - protected void resolveClasspath( @Nonnull Commandline cli, - @Nonnull String booterThatHasMainMethod, - @Nonnull StartupConfiguration config, - @Nonnull File dumpLogDirectory ) - { - - } - }; + String jvm = new File(new File(System.getProperty("java.home"), "bin"), "java").getCanonicalPath(); + Platform platform = new Platform().withJdkExecAttributesForTests(new JdkAttributes(jvm, false)); + + ForkConfiguration config = + new DefaultForkConfiguration( + emptyClasspath(), + basedir, + "", + basedir, + new Properties(), + "", + env, + exclEnv, + false, + 1, + true, + platform, + new NullConsoleLogger(), + mock(ForkNodeFactory.class)) { + + @Override + protected void resolveClasspath( + @Nonnull Commandline cli, + @Nonnull String booterThatHasMainMethod, + @Nonnull StartupConfiguration config, + @Nonnull File dumpLogDirectory) {} + }; List providerJpmsArgs = new ArrayList<>(); - providerJpmsArgs.add( new String[]{ "arg2", "arg3" } ); + providerJpmsArgs.add(new String[] {"arg2", "arg3"}); File cpElement = getTempClasspathFile(); - List cp = singletonList( cpElement.getAbsolutePath() ); + List cp = singletonList(cpElement.getAbsolutePath()); - ClasspathConfiguration cpConfig = new ClasspathConfiguration( new Classpath( cp ), emptyClasspath(), - emptyClasspath(), true, true ); - ClassLoaderConfiguration clc = new ClassLoaderConfiguration( true, true ); - StartupConfiguration startup = new StartupConfiguration( "cls", cpConfig, clc, ALL, providerJpmsArgs ); + ClasspathConfiguration cpConfig = + new ClasspathConfiguration(new Classpath(cp), emptyClasspath(), emptyClasspath(), true, true); + ClassLoaderConfiguration clc = new ClassLoaderConfiguration(true, true); + StartupConfiguration startup = new StartupConfiguration("cls", cpConfig, clc, ALL, providerJpmsArgs); - org.apache.maven.surefire.shared.utils.cli.Commandline - cli = config.createCommandLine( startup, 1, getTempDirectory() ); + org.apache.maven.surefire.shared.utils.cli.Commandline cli = + config.createCommandLine(startup, 1, getTempDirectory()); - assertThat( cli.getEnvironmentVariables() ) - .contains( "key1=val1", "key2=val2", "key3=val3" ) - .doesNotContain( "PATH=" ) - .doesNotHaveDuplicates(); + assertThat(cli.getEnvironmentVariables()) + .contains("key1=val1", "key2=val2", "key3=val3") + .doesNotContain("PATH=") + .doesNotHaveDuplicates(); } @Test - public void testCliArgs() throws Exception - { - String jvm = new File( new File( System.getProperty( "java.home" ), "bin" ), "java" ).getCanonicalPath(); - Platform platform = new Platform().withJdkExecAttributesForTests( new JdkAttributes( jvm, false ) ); - - ModularClasspathForkConfiguration config = new ModularClasspathForkConfiguration( emptyClasspath(), basedir, - "", basedir, new Properties(), "arg1", Collections.emptyMap(), new String[0], false, 1, - true, platform, new NullConsoleLogger(), mock( ForkNodeFactory.class ) ); - - assertThat( config.isDebug() ).isFalse(); + public void testCliArgs() throws Exception { + String jvm = new File(new File(System.getProperty("java.home"), "bin"), "java").getCanonicalPath(); + Platform platform = new Platform().withJdkExecAttributesForTests(new JdkAttributes(jvm, false)); + + ModularClasspathForkConfiguration config = new ModularClasspathForkConfiguration( + emptyClasspath(), + basedir, + "", + basedir, + new Properties(), + "arg1", + Collections.emptyMap(), + new String[0], + false, + 1, + true, + platform, + new NullConsoleLogger(), + mock(ForkNodeFactory.class)); + + assertThat(config.isDebug()).isFalse(); List providerJpmsArgs = new ArrayList<>(); - providerJpmsArgs.add( new String[]{ "arg2", "arg3" } ); + providerJpmsArgs.add(new String[] {"arg2", "arg3"}); - ModularClasspath modulepath = new ModularClasspath( "test.module", Collections.emptyList(), - Collections.emptyList(), null, false ); - ModularClasspathConfiguration cpConfig = new ModularClasspathConfiguration( modulepath, emptyClasspath(), - emptyClasspath(), emptyClasspath(), false, true ); - ClassLoaderConfiguration clc = new ClassLoaderConfiguration( true, true ); - StartupConfiguration startup = new StartupConfiguration( "cls", cpConfig, clc, ALL, providerJpmsArgs ); + ModularClasspath modulepath = new ModularClasspath( + "test.module", Collections.emptyList(), Collections.emptyList(), null, false); + ModularClasspathConfiguration cpConfig = new ModularClasspathConfiguration( + modulepath, emptyClasspath(), emptyClasspath(), emptyClasspath(), false, true); + ClassLoaderConfiguration clc = new ClassLoaderConfiguration(true, true); + StartupConfiguration startup = new StartupConfiguration("cls", cpConfig, clc, ALL, providerJpmsArgs); - org.apache.maven.surefire.shared.utils.cli.Commandline - cli = config.createCommandLine( startup, 1, getTempDirectory() ); + org.apache.maven.surefire.shared.utils.cli.Commandline cli = + config.createCommandLine(startup, 1, getTempDirectory()); String cliAsString = cli.toString(); - assertThat( cliAsString ) - .contains( "arg1" ); + assertThat(cliAsString).contains("arg1"); // "/path/to/java arg1 @/path/to/argfile" - int beginOfFileArg = cliAsString.indexOf( '@', cliAsString.lastIndexOf( "arg1" ) ); - assertThat( beginOfFileArg ).isPositive(); - int endOfFileArg = cliAsString.indexOf( IS_OS_WINDOWS ? '"' : '\'', beginOfFileArg ); - assertThat( endOfFileArg ).isPositive(); - Path argFile = Paths.get( cliAsString.substring( beginOfFileArg + 1, endOfFileArg ) ); - String argFileText = new String( readAllBytes( argFile ) ); - assertThat( argFileText ) - .contains( "arg2" ) - .contains( "arg3" ) - .contains( "--add-modules" + NL + "test.module" ); + int beginOfFileArg = cliAsString.indexOf('@', cliAsString.lastIndexOf("arg1")); + assertThat(beginOfFileArg).isPositive(); + int endOfFileArg = cliAsString.indexOf(IS_OS_WINDOWS ? '"' : '\'', beginOfFileArg); + assertThat(endOfFileArg).isPositive(); + Path argFile = Paths.get(cliAsString.substring(beginOfFileArg + 1, endOfFileArg)); + String argFileText = new String(readAllBytes(argFile)); + assertThat(argFileText).contains("arg2").contains("arg3").contains("--add-modules" + NL + "test.module"); } @Test - public void testDebugLine() throws Exception - { - String jvm = new File( new File( System.getProperty( "java.home" ), "bin" ), "java" ).getCanonicalPath(); - Platform platform = new Platform().withJdkExecAttributesForTests( new JdkAttributes( jvm, false ) ); - - ConsoleLogger logger = mock( ConsoleLogger.class ); - ForkNodeFactory forkNodeFactory = mock( ForkNodeFactory.class ); - - ForkConfiguration config = new DefaultForkConfiguration( emptyClasspath(), basedir, - "-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=*:5005", basedir, new Properties(), "", - Collections.emptyMap(), new String[0], true, 1, true, - platform, logger, forkNodeFactory ) - { - - @Override - protected void resolveClasspath( @Nonnull Commandline cli, - @Nonnull String booterThatHasMainMethod, - @Nonnull StartupConfiguration config, - @Nonnull File dumpLogDirectory ) - { - - } - }; - - assertThat( config.isDebug() ) - .isTrue(); - - assertThat( config.getDebugLine() ) - .isEqualTo( "-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=*:5005" ); - - assertThat( config.getForkCount() ) - .isEqualTo( 1 ); - - assertThat( config.isReuseForks() ) - .isTrue(); - - assertThat( config.getForkNodeFactory() ) - .isSameAs( forkNodeFactory ); + public void testDebugLine() throws Exception { + String jvm = new File(new File(System.getProperty("java.home"), "bin"), "java").getCanonicalPath(); + Platform platform = new Platform().withJdkExecAttributesForTests(new JdkAttributes(jvm, false)); + + ConsoleLogger logger = mock(ConsoleLogger.class); + ForkNodeFactory forkNodeFactory = mock(ForkNodeFactory.class); + + ForkConfiguration config = + new DefaultForkConfiguration( + emptyClasspath(), + basedir, + "-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=*:5005", + basedir, + new Properties(), + "", + Collections.emptyMap(), + new String[0], + true, + 1, + true, + platform, + logger, + forkNodeFactory) { + + @Override + protected void resolveClasspath( + @Nonnull Commandline cli, + @Nonnull String booterThatHasMainMethod, + @Nonnull StartupConfiguration config, + @Nonnull File dumpLogDirectory) {} + }; + + assertThat(config.isDebug()).isTrue(); + + assertThat(config.getDebugLine()) + .isEqualTo("-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=*:5005"); + + assertThat(config.getForkCount()).isEqualTo(1); + + assertThat(config.isReuseForks()).isTrue(); + + assertThat(config.getForkNodeFactory()).isSameAs(forkNodeFactory); File cpElement = getTempClasspathFile(); - List cp = singletonList( cpElement.getAbsolutePath() ); + List cp = singletonList(cpElement.getAbsolutePath()); - ClasspathConfiguration cpConfig = new ClasspathConfiguration( new Classpath( cp ), emptyClasspath(), - emptyClasspath(), true, true ); - ClassLoaderConfiguration clc = new ClassLoaderConfiguration( true, true ); - StartupConfiguration startup = new StartupConfiguration( "org.apache.maven.surefire.JUnitProvider#main", - cpConfig, clc, ALL, Collections.emptyList() ); + ClasspathConfiguration cpConfig = + new ClasspathConfiguration(new Classpath(cp), emptyClasspath(), emptyClasspath(), true, true); + ClassLoaderConfiguration clc = new ClassLoaderConfiguration(true, true); + StartupConfiguration startup = new StartupConfiguration( + "org.apache.maven.surefire.JUnitProvider#main", cpConfig, clc, ALL, Collections.emptyList()); - assertThat( startup.isProviderMainClass() ) - .isTrue(); + assertThat(startup.isProviderMainClass()).isTrue(); - assertThat( startup.getProviderClassName() ) - .isEqualTo( "org.apache.maven.surefire.JUnitProvider#main" ); + assertThat(startup.getProviderClassName()).isEqualTo("org.apache.maven.surefire.JUnitProvider#main"); - assertThat( startup.isShadefire() ) - .isFalse(); + assertThat(startup.isShadefire()).isFalse(); - org.apache.maven.surefire.shared.utils.cli.Commandline - cli = config.createCommandLine( startup, 1, getTempDirectory() ); + org.apache.maven.surefire.shared.utils.cli.Commandline cli = + config.createCommandLine(startup, 1, getTempDirectory()); - assertThat( cli.toString() ) - .contains( "-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=*:5005" ); + assertThat(cli.toString()).contains("-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=*:5005"); } @Test - @SuppressWarnings( { "checkstyle:methodname", "checkstyle:magicnumber" } ) + @SuppressWarnings({"checkstyle:methodname", "checkstyle:magicnumber"}) public void testCreateCommandLine_UseSystemClassLoaderForkOnce_ShouldConstructManifestOnlyJar() - throws IOException, SurefireBooterForkException - { - ForkConfiguration config = getForkConfiguration( basedir, null ); + throws IOException, SurefireBooterForkException { + ForkConfiguration config = getForkConfiguration(basedir, null); File cpElement = getTempClasspathFile(); - List cp = singletonList( cpElement.getAbsolutePath() ); - ClasspathConfiguration cpConfig = new ClasspathConfiguration( new Classpath( cp ), emptyClasspath(), - emptyClasspath(), true, true ); - ClassLoaderConfiguration clc = new ClassLoaderConfiguration( true, true ); + List cp = singletonList(cpElement.getAbsolutePath()); + ClasspathConfiguration cpConfig = + new ClasspathConfiguration(new Classpath(cp), emptyClasspath(), emptyClasspath(), true, true); + ClassLoaderConfiguration clc = new ClassLoaderConfiguration(true, true); StartupConfiguration startup = - new StartupConfiguration( "", cpConfig, clc, ALL, Collections.emptyList() ); + new StartupConfiguration("", cpConfig, clc, ALL, Collections.emptyList()); - org.apache.maven.surefire.shared.utils.cli.Commandline - cli = config.createCommandLine( startup, 1, getTempDirectory() ); + org.apache.maven.surefire.shared.utils.cli.Commandline cli = + config.createCommandLine(startup, 1, getTempDirectory()); - String line = join( " ", cli.getCommandline() ); - assertTrue( line.contains( "-jar" ) ); + String line = join(" ", cli.getCommandline()); + assertTrue(line.contains("-jar")); } @Test - public void testArglineWithNewline() - throws IOException, SurefireBooterForkException - { + public void testArglineWithNewline() throws IOException, SurefireBooterForkException { // SUREFIRE-657 - ForkConfiguration config = getForkConfiguration( basedir, "abc\ndef" ); + ForkConfiguration config = getForkConfiguration(basedir, "abc\ndef"); File cpElement = getTempClasspathFile(); - List cp = singletonList( cpElement.getAbsolutePath() ); - ClasspathConfiguration cpConfig = new ClasspathConfiguration( new Classpath( cp ), emptyClasspath(), - emptyClasspath(), true, true ); - ClassLoaderConfiguration clc = new ClassLoaderConfiguration( true, true ); + List cp = singletonList(cpElement.getAbsolutePath()); + ClasspathConfiguration cpConfig = + new ClasspathConfiguration(new Classpath(cp), emptyClasspath(), emptyClasspath(), true, true); + ClassLoaderConfiguration clc = new ClassLoaderConfiguration(true, true); StartupConfiguration startup = - new StartupConfiguration( "", cpConfig, clc, ALL, Collections.emptyList() ); + new StartupConfiguration("", cpConfig, clc, ALL, Collections.emptyList()); - org.apache.maven.surefire.shared.utils.cli.Commandline - commandLine = config.createCommandLine( startup, 1, getTempDirectory() ); - assertThat( commandLine.toString() ).contains( IS_OS_WINDOWS ? "abc def" : "'abc' 'def'" ); + org.apache.maven.surefire.shared.utils.cli.Commandline commandLine = + config.createCommandLine(startup, 1, getTempDirectory()); + assertThat(commandLine.toString()).contains(IS_OS_WINDOWS ? "abc def" : "'abc' 'def'"); } @Test public void testCurrentWorkingDirectoryPropagationIncludingForkNumberExpansion() - throws IOException, SurefireBooterForkException - { - File cwd = new File( basedir, "fork_${surefire.forkNumber}" ); + throws IOException, SurefireBooterForkException { + File cwd = new File(basedir, "fork_${surefire.forkNumber}"); - ClasspathConfiguration cpConfig = new ClasspathConfiguration( emptyClasspath(), emptyClasspath(), - emptyClasspath(), true, true ); - ClassLoaderConfiguration clc = new ClassLoaderConfiguration( true, true ); + ClasspathConfiguration cpConfig = + new ClasspathConfiguration(emptyClasspath(), emptyClasspath(), emptyClasspath(), true, true); + ClassLoaderConfiguration clc = new ClassLoaderConfiguration(true, true); StartupConfiguration startup = - new StartupConfiguration( "", cpConfig, clc, ALL, Collections.emptyList() ); - ForkConfiguration config = getForkConfiguration( cwd.getCanonicalFile() ); - org.apache.maven.surefire.shared.utils.cli.Commandline - commandLine = config.createCommandLine( startup, 1, getTempDirectory() ); + new StartupConfiguration("", cpConfig, clc, ALL, Collections.emptyList()); + ForkConfiguration config = getForkConfiguration(cwd.getCanonicalFile()); + org.apache.maven.surefire.shared.utils.cli.Commandline commandLine = + config.createCommandLine(startup, 1, getTempDirectory()); - File forkDirectory = new File( basedir, "fork_1" ); + File forkDirectory = new File(basedir, "fork_1"); String shellWorkDir = commandLine.getShell().getWorkingDirectory().getCanonicalPath(); - assertEquals( shellWorkDir, forkDirectory.getCanonicalPath() ); + assertEquals(shellWorkDir, forkDirectory.getCanonicalPath()); } @Test - public void testExceptionWhenCurrentDirectoryIsNotRealDirectory() - throws IOException - { - File cwd = new File( basedir, "cwd.txt" ); - FileUtils.touch( cwd ); - - try - { - ForkConfiguration config = getForkConfiguration( cwd.getCanonicalFile() ); - config.createCommandLine( STARTUP_CONFIG, 1, getTempDirectory() ); - } - catch ( SurefireBooterForkException e ) - { + public void testExceptionWhenCurrentDirectoryIsNotRealDirectory() throws IOException { + File cwd = new File(basedir, "cwd.txt"); + FileUtils.touch(cwd); + + try { + ForkConfiguration config = getForkConfiguration(cwd.getCanonicalFile()); + config.createCommandLine(STARTUP_CONFIG, 1, getTempDirectory()); + } catch (SurefireBooterForkException e) { // To handle issue with ~ expansion on Windows String absolutePath = cwd.getCanonicalPath(); - assertEquals( "WorkingDirectory " + absolutePath + " exists and is not a directory", e.getMessage() ); + assertEquals("WorkingDirectory " + absolutePath + " exists and is not a directory", e.getMessage()); return; - } - finally - { - assertTrue( cwd.delete() ); + } finally { + assertTrue(cwd.delete()); } fail(); } @Test - public void testExceptionWhenCurrentDirectoryCannotBeCreated() - throws IOException - { + public void testExceptionWhenCurrentDirectoryCannotBeCreated() throws IOException { // NULL is invalid for JDK starting from 1.7.60 // - https://github.com/openjdk-mirror/jdk/commit/e5389115f3634d25d101e2dcc71f120d4fd9f72f // ? character is invalid on Windows, seems to be imposable to create invalid directory using Java on Linux - File cwd = new File( basedir, "?\u0000InvalidDirectoryName" ); + File cwd = new File(basedir, "?\u0000InvalidDirectoryName"); - try - { - ForkConfiguration config = getForkConfiguration( cwd.getAbsoluteFile() ); - config.createCommandLine( STARTUP_CONFIG, 1, getTempDirectory() ); - } - catch ( SurefireBooterForkException sbfe ) - { - assertEquals( "Cannot create workingDirectory " + cwd.getAbsolutePath(), sbfe.getMessage() ); + try { + ForkConfiguration config = getForkConfiguration(cwd.getAbsoluteFile()); + config.createCommandLine(STARTUP_CONFIG, 1, getTempDirectory()); + } catch (SurefireBooterForkException sbfe) { + assertEquals("Cannot create workingDirectory " + cwd.getAbsolutePath(), sbfe.getMessage()); return; - } - finally - { - FileUtils.deleteDirectory( cwd ); + } finally { + FileUtils.deleteDirectory(cwd); } - if ( IS_OS_WINDOWS || isJavaVersionAtLeast7u60() ) - { + if (IS_OS_WINDOWS || isJavaVersionAtLeast7u60()) { fail(); } } - private File getTempClasspathFile() - throws IOException - { - File cpElement = new File( basedir, "ForkConfigurationTest." + idx + ".file" ); - FileUtils.deleteDirectory( cpElement ); + private File getTempClasspathFile() throws IOException { + File cpElement = new File(basedir, "ForkConfigurationTest." + idx + ".file"); + FileUtils.deleteDirectory(cpElement); return cpElement; } - static ForkConfiguration getForkConfiguration( File basedir, String argLine ) - throws IOException - { - File jvm = new File( new File( System.getProperty( "java.home" ), "bin" ), "java" ); - return getForkConfiguration( basedir, argLine, jvm.getAbsolutePath(), new File( "." ).getCanonicalFile() ); + static ForkConfiguration getForkConfiguration(File basedir, String argLine) throws IOException { + File jvm = new File(new File(System.getProperty("java.home"), "bin"), "java"); + return getForkConfiguration(basedir, argLine, jvm.getAbsolutePath(), new File(".").getCanonicalFile()); } - private ForkConfiguration getForkConfiguration( File cwd ) - throws IOException - { - File jvm = new File( new File( System.getProperty( "java.home" ), "bin" ), "java" ); - return getForkConfiguration( basedir, null, jvm.getAbsolutePath(), cwd ); + private ForkConfiguration getForkConfiguration(File cwd) throws IOException { + File jvm = new File(new File(System.getProperty("java.home"), "bin"), "java"); + return getForkConfiguration(basedir, null, jvm.getAbsolutePath(), cwd); } - private static ForkConfiguration getForkConfiguration( File basedir, String argLine, String jvm, File cwd ) - throws IOException - { - Platform platform = new Platform().withJdkExecAttributesForTests( new JdkAttributes( jvm, false ) ); - File tmpDir = new File( new File( basedir, "target" ), "surefire" ); - FileUtils.deleteDirectory( tmpDir ); - assertTrue( tmpDir.mkdirs() ); - return new JarManifestForkConfiguration( emptyClasspath(), tmpDir, null, - cwd, new Properties(), argLine, - Collections.emptyMap(), new String[0], false, 1, false, - platform, new NullConsoleLogger(), mock( ForkNodeFactory.class ) ); + private static ForkConfiguration getForkConfiguration(File basedir, String argLine, String jvm, File cwd) + throws IOException { + Platform platform = new Platform().withJdkExecAttributesForTests(new JdkAttributes(jvm, false)); + File tmpDir = new File(new File(basedir, "target"), "surefire"); + FileUtils.deleteDirectory(tmpDir); + assertTrue(tmpDir.mkdirs()); + return new JarManifestForkConfiguration( + emptyClasspath(), + tmpDir, + null, + cwd, + new Properties(), + argLine, + Collections.emptyMap(), + new String[0], + false, + 1, + false, + platform, + new NullConsoleLogger(), + mock(ForkNodeFactory.class)); } // based on http://stackoverflow.com/questions/2591083/getting-version-of-java-in-runtime - @SuppressWarnings( "checkstyle:magicnumber" ) - private static boolean isJavaVersionAtLeast7u60() - { - String[] javaVersionElements = System.getProperty( "java.runtime.version" ).split( "\\.|_|-b" ); - return Integer.parseInt( javaVersionElements[1] ) >= 7 && Integer.parseInt( javaVersionElements[3] ) >= 60; + @SuppressWarnings("checkstyle:magicnumber") + private static boolean isJavaVersionAtLeast7u60() { + String[] javaVersionElements = + System.getProperty("java.runtime.version").split("\\.|_|-b"); + return Integer.parseInt(javaVersionElements[1]) >= 7 && Integer.parseInt(javaVersionElements[3]) >= 60; } } diff --git a/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/booterclient/ForkStarterTest.java b/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/booterclient/ForkStarterTest.java index ff04152a59..7419ff3f71 100644 --- a/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/booterclient/ForkStarterTest.java +++ b/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/booterclient/ForkStarterTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire.booterclient; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,18 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.surefire.booterclient; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayDeque; +import java.util.Collections; +import java.util.jar.Manifest; +import java.util.zip.Deflater; import org.apache.maven.plugin.surefire.StartupReportConfiguration; import org.apache.maven.plugin.surefire.SurefireProperties; @@ -33,16 +43,16 @@ import org.apache.maven.plugin.surefire.extensions.SurefireStatelessTestsetInfoReporter; import org.apache.maven.plugin.surefire.log.api.ConsoleLogger; import org.apache.maven.plugin.surefire.report.DefaultReporterFactory; +import org.apache.maven.surefire.api.booter.Shutdown; +import org.apache.maven.surefire.api.report.ReporterConfiguration; import org.apache.maven.surefire.booter.AbstractPathConfiguration; import org.apache.maven.surefire.booter.ClassLoaderConfiguration; import org.apache.maven.surefire.booter.Classpath; import org.apache.maven.surefire.booter.PropertiesWrapper; import org.apache.maven.surefire.booter.ProviderConfiguration; -import org.apache.maven.surefire.api.booter.Shutdown; import org.apache.maven.surefire.booter.StartupConfiguration; import org.apache.maven.surefire.booter.SurefireBooterForkException; import org.apache.maven.surefire.extensions.ForkNodeFactory; -import org.apache.maven.surefire.api.report.ReporterConfiguration; import org.apache.maven.surefire.shared.compress.archivers.zip.Zip64Mode; import org.apache.maven.surefire.shared.compress.archivers.zip.ZipArchiveEntry; import org.apache.maven.surefire.shared.compress.archivers.zip.ZipArchiveOutputStream; @@ -52,17 +62,6 @@ import org.junit.Test; import org.junit.rules.ExpectedException; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.ArrayDeque; -import java.util.Collections; -import java.util.jar.Manifest; -import java.util.zip.Deflater; - import static org.apache.commons.io.FileUtils.deleteQuietly; import static org.hamcrest.Matchers.containsString; import static org.mockito.ArgumentMatchers.eq; @@ -73,215 +72,244 @@ /** * */ -public class ForkStarterTest -{ - private static String baseDir = System.getProperty( "user.dir" ); +public class ForkStarterTest { + private static String baseDir = System.getProperty("user.dir"); private static File tmp; @Rule public final ExpectedException e = ExpectedException.none(); @BeforeClass - public static void prepareFiles() throws IOException - { - File target = new File( baseDir, "target" ); - tmp = new File( target, "tmp" ); + public static void prepareFiles() throws IOException { + File target = new File(baseDir, "target"); + tmp = new File(target, "tmp"); tmp.mkdirs(); - File booter = new File( tmp, "surefirebooter.jar" ); + File booter = new File(tmp, "surefirebooter.jar"); booter.createNewFile(); - try ( ZipArchiveOutputStream zos = new ZipArchiveOutputStream( new FileOutputStream( booter ) ) ) - { - zos.setUseZip64( Zip64Mode.Never ); - zos.setLevel( Deflater.NO_COMPRESSION ); + try (ZipArchiveOutputStream zos = new ZipArchiveOutputStream(new FileOutputStream(booter))) { + zos.setUseZip64(Zip64Mode.Never); + zos.setLevel(Deflater.NO_COMPRESSION); - ZipArchiveEntry ze = new ZipArchiveEntry( "META-INF/MANIFEST.MF" ); - zos.putArchiveEntry( ze ); + ZipArchiveEntry ze = new ZipArchiveEntry("META-INF/MANIFEST.MF"); + zos.putArchiveEntry(ze); Manifest man = new Manifest(); - man.getMainAttributes().putValue( "Manifest-Version", "1.0" ); - man.getMainAttributes().putValue( "Main-Class", MainClass.class.getName() ); + man.getMainAttributes().putValue("Manifest-Version", "1.0"); + man.getMainAttributes().putValue("Main-Class", MainClass.class.getName()); - man.write( zos ); + man.write(zos); zos.closeArchiveEntry(); - ze = new ZipArchiveEntry( "org/apache/maven/plugin/surefire/booterclient/MainClass.class" ); - zos.putArchiveEntry( ze ); - String classesDir = Paths.get( target.getPath(), "test-classes" ).toString(); - Path cls = Paths.get( classesDir, "org", "apache", "maven", "plugin", "surefire", "booterclient", - "MainClass.class" ); - zos.write( Files.readAllBytes( cls ) ); + ze = new ZipArchiveEntry("org/apache/maven/plugin/surefire/booterclient/MainClass.class"); + zos.putArchiveEntry(ze); + String classesDir = Paths.get(target.getPath(), "test-classes").toString(); + Path cls = Paths.get( + classesDir, "org", "apache", "maven", "plugin", "surefire", "booterclient", "MainClass.class"); + zos.write(Files.readAllBytes(cls)); zos.closeArchiveEntry(); } } @AfterClass - public static void deleteTmp() - { - deleteQuietly( tmp ); + public static void deleteTmp() { + deleteQuietly(tmp); } @Test - public void processShouldExitWithoutSayingGoodBye() throws Exception - { - ReporterConfiguration reporterConfiguration = new ReporterConfiguration( tmp, true ); - - ProviderConfiguration providerConfiguration = mock( ProviderConfiguration.class ); - when( providerConfiguration.getReporterConfiguration() ) - .thenReturn( reporterConfiguration ); - when( providerConfiguration.getShutdown() ) - .thenReturn( Shutdown.EXIT ); - - StartupConfiguration startupConfiguration = mock( StartupConfiguration.class ); - when( startupConfiguration.getClasspathConfiguration() ) - .thenReturn( new ClasspathConfig() ); - when( startupConfiguration.getClassLoaderConfiguration() ) - .thenReturn( new ClassLoaderConfiguration( false, false ) ); - when( startupConfiguration.getProviderClassName() ) - .thenReturn( MainClass.class.getName() ); - - ForkConfiguration forkConfiguration = mock( ForkConfiguration.class ); - when( forkConfiguration.getWorkingDirectory() ) - .thenReturn( tmp ); - when( forkConfiguration.getTempDirectory() ) - .thenReturn( tmp ); - when( forkConfiguration.getPluginPlatform() ) - .thenReturn( new Platform() ); + public void processShouldExitWithoutSayingGoodBye() throws Exception { + ReporterConfiguration reporterConfiguration = new ReporterConfiguration(tmp, true); + + ProviderConfiguration providerConfiguration = mock(ProviderConfiguration.class); + when(providerConfiguration.getReporterConfiguration()).thenReturn(reporterConfiguration); + when(providerConfiguration.getShutdown()).thenReturn(Shutdown.EXIT); + + StartupConfiguration startupConfiguration = mock(StartupConfiguration.class); + when(startupConfiguration.getClasspathConfiguration()).thenReturn(new ClasspathConfig()); + when(startupConfiguration.getClassLoaderConfiguration()).thenReturn(new ClassLoaderConfiguration(false, false)); + when(startupConfiguration.getProviderClassName()).thenReturn(MainClass.class.getName()); + + ForkConfiguration forkConfiguration = mock(ForkConfiguration.class); + when(forkConfiguration.getWorkingDirectory()).thenReturn(tmp); + when(forkConfiguration.getTempDirectory()).thenReturn(tmp); + when(forkConfiguration.getPluginPlatform()).thenReturn(new Platform()); Commandline cli = new Commandline(); - cli.setWorkingDirectory( tmp ); - cli.setExecutable( System.getProperty( "java.home" ) + "/bin/java" ); - cli.createArg().setLine( "-jar" ); - cli.createArg().setLine( "surefirebooter.jar" ); - cli.createArg().setLine( "fail" ); - when( forkConfiguration.createCommandLine( eq( startupConfiguration ), eq( 1 ), eq( tmp ) ) ) - .thenReturn( cli ); + cli.setWorkingDirectory(tmp); + cli.setExecutable(System.getProperty("java.home") + "/bin/java"); + cli.createArg().setLine("-jar"); + cli.createArg().setLine("surefirebooter.jar"); + cli.createArg().setLine("fail"); + when(forkConfiguration.createCommandLine(eq(startupConfiguration), eq(1), eq(tmp))) + .thenReturn(cli); SurefireStatelessTestsetInfoReporter statelessTestsetInfoReporter = new SurefireStatelessTestsetInfoReporter(); SurefireConsoleOutputReporter outputReporter = new SurefireConsoleOutputReporter(); - SurefireStatelessReporter xmlReporter = new SurefireStatelessReporter( true, "3" ); - - StartupReportConfiguration startupReportConfiguration = new StartupReportConfiguration( true, true, null, - false, tmp, true, "", null, false, 0, null, null, true, - xmlReporter, outputReporter, statelessTestsetInfoReporter ); - - ConsoleLogger logger = mock( ConsoleLogger.class ); - - ForkStarter forkStarter = new ForkStarter( providerConfiguration, startupConfiguration, forkConfiguration, - 0, startupReportConfiguration, logger ); - - DefaultReporterFactory reporterFactory = - new DefaultReporterFactory( startupReportConfiguration, logger, 1 ); - - e.expect( SurefireBooterForkException.class ); - e.expectMessage( containsString( "Process Exit Code: 1" ) ); - e.expectMessage( containsString( "The forked VM terminated without properly saying goodbye." ) ); - e.expectMessage( containsString( "VM crash or System.exit called?" ) ); - - Class[] types = {Object.class, PropertiesWrapper.class, ForkClient.class, SurefireProperties.class, - int.class, AbstractCommandReader.class, ForkNodeFactory.class, boolean.class}; - TestProvidingInputStream testProvidingInputStream = new TestProvidingInputStream( new ArrayDeque() ); - invokeMethod( forkStarter, "fork", types, null, - new PropertiesWrapper( Collections.emptyMap() ), - new ForkClient( reporterFactory, null, 1 ), - new SurefireProperties(), 1, testProvidingInputStream, new LegacyForkNodeFactory(), true ); + SurefireStatelessReporter xmlReporter = new SurefireStatelessReporter(true, "3"); + + StartupReportConfiguration startupReportConfiguration = new StartupReportConfiguration( + true, + true, + null, + false, + tmp, + true, + "", + null, + false, + 0, + null, + null, + true, + xmlReporter, + outputReporter, + statelessTestsetInfoReporter); + + ConsoleLogger logger = mock(ConsoleLogger.class); + + ForkStarter forkStarter = new ForkStarter( + providerConfiguration, startupConfiguration, forkConfiguration, 0, startupReportConfiguration, logger); + + DefaultReporterFactory reporterFactory = new DefaultReporterFactory(startupReportConfiguration, logger, 1); + + e.expect(SurefireBooterForkException.class); + e.expectMessage(containsString("Process Exit Code: 1")); + e.expectMessage(containsString("The forked VM terminated without properly saying goodbye.")); + e.expectMessage(containsString("VM crash or System.exit called?")); + + Class[] types = { + Object.class, + PropertiesWrapper.class, + ForkClient.class, + SurefireProperties.class, + int.class, + AbstractCommandReader.class, + ForkNodeFactory.class, + boolean.class + }; + TestProvidingInputStream testProvidingInputStream = new TestProvidingInputStream(new ArrayDeque()); + invokeMethod( + forkStarter, + "fork", + types, + null, + new PropertiesWrapper(Collections.emptyMap()), + new ForkClient(reporterFactory, null, 1), + new SurefireProperties(), + 1, + testProvidingInputStream, + new LegacyForkNodeFactory(), + true); testProvidingInputStream.close(); } @Test - public void processShouldWaitForAck() throws Exception - { - ReporterConfiguration reporterConfiguration = new ReporterConfiguration( tmp, true ); - - ProviderConfiguration providerConfiguration = mock( ProviderConfiguration.class ); - when( providerConfiguration.getReporterConfiguration() ) - .thenReturn( reporterConfiguration ); - when( providerConfiguration.getShutdown() ) - .thenReturn( Shutdown.EXIT ); - - StartupConfiguration startupConfiguration = mock( StartupConfiguration.class ); - when( startupConfiguration.getClasspathConfiguration() ) - .thenReturn( new ClasspathConfig() ); - when( startupConfiguration.getClassLoaderConfiguration() ) - .thenReturn( new ClassLoaderConfiguration( false, false ) ); - when( startupConfiguration.getProviderClassName() ) - .thenReturn( MainClass.class.getName() ); - - ForkConfiguration forkConfiguration = mock( ForkConfiguration.class ); - when( forkConfiguration.getWorkingDirectory() ) - .thenReturn( tmp ); - when( forkConfiguration.getTempDirectory() ) - .thenReturn( tmp ); - when( forkConfiguration.getPluginPlatform() ) - .thenReturn( new Platform() ); + public void processShouldWaitForAck() throws Exception { + ReporterConfiguration reporterConfiguration = new ReporterConfiguration(tmp, true); + + ProviderConfiguration providerConfiguration = mock(ProviderConfiguration.class); + when(providerConfiguration.getReporterConfiguration()).thenReturn(reporterConfiguration); + when(providerConfiguration.getShutdown()).thenReturn(Shutdown.EXIT); + + StartupConfiguration startupConfiguration = mock(StartupConfiguration.class); + when(startupConfiguration.getClasspathConfiguration()).thenReturn(new ClasspathConfig()); + when(startupConfiguration.getClassLoaderConfiguration()).thenReturn(new ClassLoaderConfiguration(false, false)); + when(startupConfiguration.getProviderClassName()).thenReturn(MainClass.class.getName()); + + ForkConfiguration forkConfiguration = mock(ForkConfiguration.class); + when(forkConfiguration.getWorkingDirectory()).thenReturn(tmp); + when(forkConfiguration.getTempDirectory()).thenReturn(tmp); + when(forkConfiguration.getPluginPlatform()).thenReturn(new Platform()); Commandline cli = new Commandline(); - cli.setWorkingDirectory( tmp ); - cli.setExecutable( System.getProperty( "java.home" ) + "/bin/java" ); - cli.createArg().setLine( "-jar" ); - cli.createArg().setLine( "surefirebooter.jar" ); - when( forkConfiguration.createCommandLine( eq( startupConfiguration ), eq( 1 ), eq( tmp ) ) ) - .thenReturn( cli ); + cli.setWorkingDirectory(tmp); + cli.setExecutable(System.getProperty("java.home") + "/bin/java"); + cli.createArg().setLine("-jar"); + cli.createArg().setLine("surefirebooter.jar"); + when(forkConfiguration.createCommandLine(eq(startupConfiguration), eq(1), eq(tmp))) + .thenReturn(cli); SurefireStatelessTestsetInfoReporter statelessTestsetInfoReporter = new SurefireStatelessTestsetInfoReporter(); SurefireConsoleOutputReporter outputReporter = new SurefireConsoleOutputReporter(); - SurefireStatelessReporter xmlReporter = new SurefireStatelessReporter( true, "3" ); - - StartupReportConfiguration startupReportConfiguration = new StartupReportConfiguration( true, true, null, - false, tmp, true, "", null, false, 0, null, null, true, - xmlReporter, outputReporter, statelessTestsetInfoReporter ); - - ConsoleLogger logger = mock( ConsoleLogger.class ); - - ForkStarter forkStarter = new ForkStarter( providerConfiguration, startupConfiguration, forkConfiguration, - 0, startupReportConfiguration, logger ); - - DefaultReporterFactory reporterFactory = - new DefaultReporterFactory( startupReportConfiguration, logger, 1 ); - - Class[] types = {Object.class, PropertiesWrapper.class, ForkClient.class, SurefireProperties.class, - int.class, AbstractCommandReader.class, ForkNodeFactory.class, boolean.class}; + SurefireStatelessReporter xmlReporter = new SurefireStatelessReporter(true, "3"); + + StartupReportConfiguration startupReportConfiguration = new StartupReportConfiguration( + true, + true, + null, + false, + tmp, + true, + "", + null, + false, + 0, + null, + null, + true, + xmlReporter, + outputReporter, + statelessTestsetInfoReporter); + + ConsoleLogger logger = mock(ConsoleLogger.class); + + ForkStarter forkStarter = new ForkStarter( + providerConfiguration, startupConfiguration, forkConfiguration, 0, startupReportConfiguration, logger); + + DefaultReporterFactory reporterFactory = new DefaultReporterFactory(startupReportConfiguration, logger, 1); + + Class[] types = { + Object.class, + PropertiesWrapper.class, + ForkClient.class, + SurefireProperties.class, + int.class, + AbstractCommandReader.class, + ForkNodeFactory.class, + boolean.class + }; TestLessInputStream testLessInputStream = new TestLessInputStreamBuilder().build(); - invokeMethod( forkStarter, "fork", types, null, - new PropertiesWrapper( Collections.emptyMap() ), - new ForkClient( reporterFactory, testLessInputStream, 1 ), - new SurefireProperties(), 1, testLessInputStream, new LegacyForkNodeFactory(), true ); + invokeMethod( + forkStarter, + "fork", + types, + null, + new PropertiesWrapper(Collections.emptyMap()), + new ForkClient(reporterFactory, testLessInputStream, 1), + new SurefireProperties(), + 1, + testLessInputStream, + new LegacyForkNodeFactory(), + true); testLessInputStream.close(); } - private static class ClasspathConfig extends AbstractPathConfiguration - { - ClasspathConfig() - { - this( Classpath.emptyClasspath(), false, false ); + private static class ClasspathConfig extends AbstractPathConfiguration { + ClasspathConfig() { + this(Classpath.emptyClasspath(), false, false); } - private ClasspathConfig( Classpath surefireClasspathUrls, boolean enableAssertions, boolean childDelegation ) - { - super( surefireClasspathUrls, enableAssertions, childDelegation ); + private ClasspathConfig(Classpath surefireClasspathUrls, boolean enableAssertions, boolean childDelegation) { + super(surefireClasspathUrls, enableAssertions, childDelegation); } @Override - public Classpath getTestClasspath() - { + public Classpath getTestClasspath() { return Classpath.emptyClasspath(); } @Override - public boolean isModularPathConfig() - { + public boolean isModularPathConfig() { return false; } @Override - public boolean isClassPathConfig() - { + public boolean isClassPathConfig() { return true; } @Override - protected Classpath getInprocClasspath() - { + protected Classpath getInprocClasspath() { return Classpath.emptyClasspath(); } } diff --git a/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/booterclient/ForkingRunListenerTest.java b/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/booterclient/ForkingRunListenerTest.java index e595cba075..d25e9b4ae0 100644 --- a/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/booterclient/ForkingRunListenerTest.java +++ b/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/booterclient/ForkingRunListenerTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire.booterclient; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,24 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.surefire.booterclient; + +import javax.annotation.Nonnull; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.Closeable; +import java.io.File; +import java.io.PrintStream; +import java.nio.channels.ReadableByteChannel; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.TimeUnit; import junit.framework.TestCase; import org.apache.maven.plugin.surefire.booterclient.lazytestprovider.NotifiableTestStream; @@ -25,12 +41,8 @@ import org.apache.maven.plugin.surefire.extensions.EventConsumerThread; import org.apache.maven.plugin.surefire.log.api.ConsoleLogger; import org.apache.maven.surefire.api.booter.ForkingRunListener; -import org.apache.maven.surefire.api.report.TestOutputReportEntry; -import org.apache.maven.surefire.booter.spi.EventChannelEncoder; import org.apache.maven.surefire.api.event.Event; -import org.apache.maven.surefire.extensions.EventHandler; import org.apache.maven.surefire.api.fork.ForkNodeArguments; -import org.apache.maven.surefire.extensions.util.CountdownCloseable; import org.apache.maven.surefire.api.report.CategorizedReportEntry; import org.apache.maven.surefire.api.report.LegacyPojoStackTraceWriter; import org.apache.maven.surefire.api.report.ReportEntry; @@ -39,25 +51,13 @@ import org.apache.maven.surefire.api.report.SimpleReportEntry; import org.apache.maven.surefire.api.report.StackTraceWriter; import org.apache.maven.surefire.api.report.TestOutputReceiver; -import org.apache.maven.surefire.api.report.TestSetReportEntry; +import org.apache.maven.surefire.api.report.TestOutputReportEntry; import org.apache.maven.surefire.api.report.TestReportListener; +import org.apache.maven.surefire.api.report.TestSetReportEntry; import org.apache.maven.surefire.api.util.internal.WritableBufferedByteChannel; - -import javax.annotation.Nonnull; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.Closeable; -import java.io.File; -import java.io.PrintStream; -import java.nio.channels.ReadableByteChannel; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.ConcurrentLinkedQueue; -import java.util.concurrent.LinkedBlockingQueue; -import java.util.concurrent.TimeUnit; +import org.apache.maven.surefire.booter.spi.EventChannelEncoder; +import org.apache.maven.surefire.extensions.EventHandler; +import org.apache.maven.surefire.extensions.util.CountdownCloseable; import static org.apache.maven.surefire.api.report.RunMode.NORMAL_RUN; import static org.apache.maven.surefire.api.report.TestOutputReportEntry.stdOut; @@ -70,127 +70,109 @@ /** * @author Kristian Rosenvold */ -@SuppressWarnings( "checkstyle:magicnumber" ) -public class ForkingRunListenerTest - extends TestCase -{ +@SuppressWarnings("checkstyle:magicnumber") +public class ForkingRunListenerTest extends TestCase { private final ByteArrayOutputStream content, anotherContent; - private final PrintStream printStream, anotherPrintStream; - public ForkingRunListenerTest() - { + public ForkingRunListenerTest() { content = new ByteArrayOutputStream(); - printStream = new PrintStream( content ); + printStream = new PrintStream(content); anotherContent = new ByteArrayOutputStream(); - anotherPrintStream = new PrintStream( anotherContent ); + anotherPrintStream = new PrintStream(anotherContent); } - private void reset() - { + private void reset() { printStream.flush(); content.reset(); } - public void testSetStarting() throws Exception - { + public void testSetStarting() throws Exception { final StandardTestRun standardTestRun = new StandardTestRun(); TestSetReportEntry expected = createDefaultReportEntry(); - standardTestRun.run().testSetStarting( expected ); - standardTestRun.assertExpected( MockReporter.SET_STARTING, expected ); + standardTestRun.run().testSetStarting(expected); + standardTestRun.assertExpected(MockReporter.SET_STARTING, expected); } - public void testSetCompleted() throws Exception - { + public void testSetCompleted() throws Exception { final StandardTestRun standardTestRun = new StandardTestRun(); TestSetReportEntry expected = createDefaultReportEntry(); - standardTestRun.run().testSetCompleted( expected ); - standardTestRun.assertExpected( MockReporter.SET_COMPLETED, expected ); + standardTestRun.run().testSetCompleted(expected); + standardTestRun.assertExpected(MockReporter.SET_COMPLETED, expected); } - public void testStarting() throws Exception - { + public void testStarting() throws Exception { final StandardTestRun standardTestRun = new StandardTestRun(); ReportEntry expected = createDefaultReportEntry(); - standardTestRun.run().testStarting( expected ); - standardTestRun.assertExpected( MockReporter.TEST_STARTING, expected ); + standardTestRun.run().testStarting(expected); + standardTestRun.assertExpected(MockReporter.TEST_STARTING, expected); } - public void testSucceeded() throws Exception - { + public void testSucceeded() throws Exception { final StandardTestRun standardTestRun = new StandardTestRun(); ReportEntry expected = createDefaultReportEntry(); - standardTestRun.run().testSucceeded( expected ); - standardTestRun.assertExpected( MockReporter.TEST_SUCCEEDED, expected ); + standardTestRun.run().testSucceeded(expected); + standardTestRun.assertExpected(MockReporter.TEST_SUCCEEDED, expected); } - public void testFailed() throws Exception - { + public void testFailed() throws Exception { final StandardTestRun standardTestRun = new StandardTestRun(); ReportEntry expected = createReportEntryWithStackTrace(); - standardTestRun.run().testFailed( expected ); - standardTestRun.assertExpected( MockReporter.TEST_FAILED, expected ); + standardTestRun.run().testFailed(expected); + standardTestRun.assertExpected(MockReporter.TEST_FAILED, expected); } - public void testFailedWithCommaInMessage() throws Exception - { + public void testFailedWithCommaInMessage() throws Exception { final StandardTestRun standardTestRun = new StandardTestRun(); - ReportEntry expected = createReportEntryWithSpecialMessage( "We, the people" ); - standardTestRun.run().testFailed( expected ); - standardTestRun.assertExpected( MockReporter.TEST_FAILED, expected ); + ReportEntry expected = createReportEntryWithSpecialMessage("We, the people"); + standardTestRun.run().testFailed(expected); + standardTestRun.assertExpected(MockReporter.TEST_FAILED, expected); } - public void testFailedWithUnicodeEscapeInMessage() throws Exception - { + public void testFailedWithUnicodeEscapeInMessage() throws Exception { final StandardTestRun standardTestRun = new StandardTestRun(); - ReportEntry expected = createReportEntryWithSpecialMessage( "We, \\u0177 people" ); - standardTestRun.run().testFailed( expected ); - standardTestRun.assertExpected( MockReporter.TEST_FAILED, expected ); + ReportEntry expected = createReportEntryWithSpecialMessage("We, \\u0177 people"); + standardTestRun.run().testFailed(expected); + standardTestRun.assertExpected(MockReporter.TEST_FAILED, expected); } - public void testFailure() throws Exception - { + public void testFailure() throws Exception { final StandardTestRun standardTestRun = new StandardTestRun(); ReportEntry expected = createDefaultReportEntry(); - standardTestRun.run().testError( expected ); - standardTestRun.assertExpected( MockReporter.TEST_ERROR, expected ); + standardTestRun.run().testError(expected); + standardTestRun.assertExpected(MockReporter.TEST_ERROR, expected); } - public void testSkipped() throws Exception - { + public void testSkipped() throws Exception { final StandardTestRun standardTestRun = new StandardTestRun(); ReportEntry expected = createDefaultReportEntry(); - standardTestRun.run().testSkipped( expected ); - standardTestRun.assertExpected( MockReporter.TEST_SKIPPED, expected ); + standardTestRun.run().testSkipped(expected); + standardTestRun.assertExpected(MockReporter.TEST_SKIPPED, expected); } - public void testAssumptionFailure() throws Exception - { + public void testAssumptionFailure() throws Exception { final StandardTestRun standardTestRun = new StandardTestRun(); ReportEntry expected = createDefaultReportEntry(); - standardTestRun.run().testAssumptionFailure( expected ); - standardTestRun.assertExpected( MockReporter.TEST_ASSUMPTION_FAIL, expected ); + standardTestRun.run().testAssumptionFailure(expected); + standardTestRun.assertExpected(MockReporter.TEST_ASSUMPTION_FAIL, expected); } - public void testConsole() throws Exception - { + public void testConsole() throws Exception { final StandardTestRun standardTestRun = new StandardTestRun(); ConsoleLogger directConsoleReporter = standardTestRun.run(); - directConsoleReporter.info( "HeyYou" ); - standardTestRun.assertExpected( MockReporter.CONSOLE_INFO, "HeyYou" ); + directConsoleReporter.info("HeyYou"); + standardTestRun.assertExpected(MockReporter.CONSOLE_INFO, "HeyYou"); } - public void testConsoleOutput() throws Exception - { + public void testConsoleOutput() throws Exception { final StandardTestRun standardTestRun = new StandardTestRun(); TestOutputReceiver directConsoleReporter = standardTestRun.run(); - directConsoleReporter.writeTestOutput( new TestOutputReportEntry( stdOut( "HeyYou" ), NORMAL_RUN, 1L ) ); - standardTestRun.assertExpected( MockReporter.STDOUT, "HeyYou" ); + directConsoleReporter.writeTestOutput(new TestOutputReportEntry(stdOut("HeyYou"), NORMAL_RUN, 1L)); + standardTestRun.assertExpected(MockReporter.STDOUT, "HeyYou"); } - public void testSystemProperties() throws Exception - { + public void testSystemProperties() throws Exception { StandardTestRun standardTestRun = new StandardTestRun(); standardTestRun.run(); @@ -198,37 +180,33 @@ public void testSystemProperties() throws Exception createForkingRunListener(); TestSetMockReporterFactory providerReporterFactory = new TestSetMockReporterFactory(); - ForkClient forkStreamClient = new ForkClient( providerReporterFactory, new MockNotifiableTestStream(), 1 ); - - byte[] cmd = ( ":maven-surefire-event:\u0008:sys-prop:" + (char) 10 + ":normal-run:" - + "\u0001\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0001:" - + "\u0005:UTF-8:" - + "\u0000\u0000\u0000\u0002:k1:\u0000\u0000\u0000\u0002:v1:" ).getBytes(); - for ( Event e : streamToEvent( cmd ) ) - { - forkStreamClient.handleEvent( e ); + ForkClient forkStreamClient = new ForkClient(providerReporterFactory, new MockNotifiableTestStream(), 1); + + byte[] cmd = (":maven-surefire-event:\u0008:sys-prop:" + (char) 10 + ":normal-run:" + + "\u0001\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0001:" + + "\u0005:UTF-8:" + + "\u0000\u0000\u0000\u0002:k1:\u0000\u0000\u0000\u0002:v1:") + .getBytes(); + for (Event e : streamToEvent(cmd)) { + forkStreamClient.handleEvent(e); } - cmd = ( "\n:maven-surefire-event:\u0008:sys-prop:" + (char) 10 + ":normal-run:" - + "\u0001\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0001:" - + "\u0005:UTF-8:" - + "\u0000\u0000\u0000\u0002:k2:\u0000\u0000\u0000\u0002:v2:" ).getBytes(); - for ( Event e : streamToEvent( cmd ) ) - { - forkStreamClient.handleEvent( e ); + cmd = ("\n:maven-surefire-event:\u0008:sys-prop:" + (char) 10 + ":normal-run:" + + "\u0001\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0001:" + + "\u0005:UTF-8:" + + "\u0000\u0000\u0000\u0002:k2:\u0000\u0000\u0000\u0002:v2:") + .getBytes(); + for (Event e : streamToEvent(cmd)) { + forkStreamClient.handleEvent(e); } - assertThat( forkStreamClient.getTestVmSystemProperties() ) - .hasSize( 2 ); + assertThat(forkStreamClient.getTestVmSystemProperties()).hasSize(2); - assertThat( forkStreamClient.getTestVmSystemProperties() ) - .containsEntry( "k1", "v1" ); + assertThat(forkStreamClient.getTestVmSystemProperties()).containsEntry("k1", "v1"); - assertThat( forkStreamClient.getTestVmSystemProperties() ) - .containsEntry( "k2", "v2" ); + assertThat(forkStreamClient.getTestVmSystemProperties()).containsEntry("k2", "v2"); } - public void testMultipleEntries() throws Exception - { + public void testMultipleEntries() throws Exception { StandardTestRun standardTestRun = new StandardTestRun(); standardTestRun.run(); @@ -236,87 +214,75 @@ public void testMultipleEntries() throws Exception RunListener forkingReporter = createForkingRunListener(); TestSetReportEntry reportEntry = createDefaultReportEntry(); - forkingReporter.testSetStarting( reportEntry ); - forkingReporter.testStarting( reportEntry ); - forkingReporter.testSucceeded( reportEntry ); - forkingReporter.testSetCompleted( reportEntry ); + forkingReporter.testSetStarting(reportEntry); + forkingReporter.testStarting(reportEntry); + forkingReporter.testSucceeded(reportEntry); + forkingReporter.testSetCompleted(reportEntry); TestSetMockReporterFactory providerReporterFactory = new TestSetMockReporterFactory(); - ForkClient forkStreamClient = - new ForkClient( providerReporterFactory, new MockNotifiableTestStream(), 1 ); + ForkClient forkStreamClient = new ForkClient(providerReporterFactory, new MockNotifiableTestStream(), 1); - for ( Event e : streamToEvent( content.toByteArray() ) ) - { - forkStreamClient.handleEvent( e ); + for (Event e : streamToEvent(content.toByteArray())) { + forkStreamClient.handleEvent(e); } final MockReporter reporter = (MockReporter) forkStreamClient.getReporter(); final List events = reporter.getEvents(); - assertEquals( MockReporter.SET_STARTING, events.get( 0 ) ); - assertEquals( MockReporter.TEST_STARTING, events.get( 1 ) ); - assertEquals( MockReporter.TEST_SUCCEEDED, events.get( 2 ) ); - assertEquals( MockReporter.SET_COMPLETED, events.get( 3 ) ); + assertEquals(MockReporter.SET_STARTING, events.get(0)); + assertEquals(MockReporter.TEST_STARTING, events.get(1)); + assertEquals(MockReporter.TEST_SUCCEEDED, events.get(2)); + assertEquals(MockReporter.SET_COMPLETED, events.get(3)); } - public void test2DifferentChannels() - throws Exception - { + public void test2DifferentChannels() throws Exception { reset(); ReportEntry expected = createDefaultReportEntry(); SimpleReportEntry secondExpected = createAnotherDefaultReportEntry(); - new ForkingRunListener( new EventChannelEncoder( newBufferedChannel( printStream ) ), false ) - .testStarting( expected ); + new ForkingRunListener(new EventChannelEncoder(newBufferedChannel(printStream)), false).testStarting(expected); - new ForkingRunListener( - new EventChannelEncoder( newBufferedChannel( anotherPrintStream ) ), false ) - .testSkipped( secondExpected ); + new ForkingRunListener(new EventChannelEncoder(newBufferedChannel(anotherPrintStream)), false) + .testSkipped(secondExpected); TestSetMockReporterFactory providerReporterFactory = new TestSetMockReporterFactory(); NotifiableTestStream notifiableTestStream = new MockNotifiableTestStream(); - ForkClient forkStreamClient = new ForkClient( providerReporterFactory, notifiableTestStream, 1 ); - for ( Event e : streamToEvent( content.toByteArray() ) ) - { - forkStreamClient.handleEvent( e ); + ForkClient forkStreamClient = new ForkClient(providerReporterFactory, notifiableTestStream, 1); + for (Event e : streamToEvent(content.toByteArray())) { + forkStreamClient.handleEvent(e); } MockReporter reporter = (MockReporter) forkStreamClient.getReporter(); - assertThat( reporter.getFirstEvent() ).isEqualTo( MockReporter.TEST_STARTING ); - assertThat( reporter.getFirstData() ).isEqualTo( expected ); - assertThat( reporter.getEvents() ).hasSize( 1 ); - - forkStreamClient = new ForkClient( providerReporterFactory, notifiableTestStream, 2 ); - for ( Event e : streamToEvent( anotherContent.toByteArray() ) ) - { - forkStreamClient.handleEvent( e ); + assertThat(reporter.getFirstEvent()).isEqualTo(MockReporter.TEST_STARTING); + assertThat(reporter.getFirstData()).isEqualTo(expected); + assertThat(reporter.getEvents()).hasSize(1); + + forkStreamClient = new ForkClient(providerReporterFactory, notifiableTestStream, 2); + for (Event e : streamToEvent(anotherContent.toByteArray())) { + forkStreamClient.handleEvent(e); } MockReporter reporter2 = (MockReporter) forkStreamClient.getReporter(); - assertThat( reporter2.getFirstEvent() ).isEqualTo( MockReporter.TEST_SKIPPED ); - assertThat( reporter2.getFirstData() ).isEqualTo( secondExpected ); - assertThat( reporter2.getEvents() ).hasSize( 1 ); + assertThat(reporter2.getFirstEvent()).isEqualTo(MockReporter.TEST_SKIPPED); + assertThat(reporter2.getFirstData()).isEqualTo(secondExpected); + assertThat(reporter2.getEvents()).hasSize(1); } - private static List streamToEvent( byte[] stream ) throws Exception - { + private static List streamToEvent(byte[] stream) throws Exception { List events = new ArrayList<>(); EH handler = new EH(); - CountdownCloseable countdown = new CountdownCloseable( mock( Closeable.class ), 1 ); - ConsoleLogger logger = mock( ConsoleLogger.class ); - ForkNodeArgumentsMock arguments = new ForkNodeArgumentsMock( logger, new File( "" ) ); - ReadableByteChannel channel = newChannel( new ByteArrayInputStream( stream ) ); - try ( EventConsumerThread t = new EventConsumerThread( "t", channel, handler, countdown, arguments ) ) - { + CountdownCloseable countdown = new CountdownCloseable(mock(Closeable.class), 1); + ConsoleLogger logger = mock(ConsoleLogger.class); + ForkNodeArgumentsMock arguments = new ForkNodeArgumentsMock(logger, new File("")); + ReadableByteChannel channel = newChannel(new ByteArrayInputStream(stream)); + try (EventConsumerThread t = new EventConsumerThread("t", channel, handler, countdown, arguments)) { t.start(); countdown.awaitClosed(); - verifyZeroInteractions( logger ); - assertThat( arguments.isCalled() ) - .isFalse(); - for ( int i = 0, size = handler.countEventsInCache(); i < size; i++ ) - { - events.add( handler.pullEvent() ); + verifyZeroInteractions(logger); + assertThat(arguments.isCalled()).isFalse(); + for (int i = 0, size = handler.countEventsInCache(); i < size; i++) { + events.add(handler.pullEvent()); } - assertEquals( 0, handler.countEventsInCache() ); + assertEquals(0, handler.countEventsInCache()); return events; } } @@ -324,220 +290,181 @@ private static List streamToEvent( byte[] stream ) throws Exception /** * Threadsafe impl. Mockito and Powermock are not thread-safe. */ - private static class ForkNodeArgumentsMock implements ForkNodeArguments - { + private static class ForkNodeArgumentsMock implements ForkNodeArguments { private final ConcurrentLinkedQueue dumpStreamText = new ConcurrentLinkedQueue<>(); private final ConcurrentLinkedQueue logWarningAtEnd = new ConcurrentLinkedQueue<>(); private final ConsoleLogger logger; private final File dumpStreamTextFile; - ForkNodeArgumentsMock( ConsoleLogger logger, File dumpStreamTextFile ) - { + ForkNodeArgumentsMock(ConsoleLogger logger, File dumpStreamTextFile) { this.logger = logger; this.dumpStreamTextFile = dumpStreamTextFile; } @Nonnull @Override - public String getSessionId() - { + public String getSessionId() { throw new UnsupportedOperationException(); } @Override - public int getForkChannelId() - { + public int getForkChannelId() { return 0; } @Nonnull @Override - public File dumpStreamText( @Nonnull String text ) - { - dumpStreamText.add( text ); + public File dumpStreamText(@Nonnull String text) { + dumpStreamText.add(text); return dumpStreamTextFile; } @Nonnull @Override - public File dumpStreamException( @Nonnull Throwable t ) - { + public File dumpStreamException(@Nonnull Throwable t) { throw new UnsupportedOperationException(); } @Override - public void logWarningAtEnd( @Nonnull String text ) - { - logWarningAtEnd.add( text ); + public void logWarningAtEnd(@Nonnull String text) { + logWarningAtEnd.add(text); } @Nonnull @Override - public ConsoleLogger getConsoleLogger() - { + public ConsoleLogger getConsoleLogger() { return logger; } @Nonnull @Override - public Object getConsoleLock() - { + public Object getConsoleLock() { return logger; } - boolean isCalled() - { + boolean isCalled() { return !dumpStreamText.isEmpty() || !logWarningAtEnd.isEmpty(); } @Override - public File getEventStreamBinaryFile() - { + public File getEventStreamBinaryFile() { return null; } @Override - public File getCommandStreamBinaryFile() - { + public File getCommandStreamBinaryFile() { return null; } } - private static class EH implements EventHandler - { + private static class EH implements EventHandler { private final BlockingQueue cache = new LinkedBlockingQueue<>(); - Event pullEvent() throws InterruptedException - { - return cache.poll( 1, TimeUnit.MINUTES ); + Event pullEvent() throws InterruptedException { + return cache.poll(1, TimeUnit.MINUTES); } - int countEventsInCache() - { + int countEventsInCache() { return cache.size(); } @Override - public void handleEvent( @Nonnull Event event ) - { - cache.add( event ); + public void handleEvent(@Nonnull Event event) { + cache.add(event); } } // Todo: Test weird characters - private SimpleReportEntry createDefaultReportEntry( Map sysProps ) - { - return new SimpleReportEntry( NORMAL_RUN, 1L, - "com.abc.TestClass", null, "testMethod", null, null, 22, sysProps ); + private SimpleReportEntry createDefaultReportEntry(Map sysProps) { + return new SimpleReportEntry(NORMAL_RUN, 1L, "com.abc.TestClass", null, "testMethod", null, null, 22, sysProps); } - private SimpleReportEntry createDefaultReportEntry() - { - return createDefaultReportEntry( Collections.emptyMap() ); + private SimpleReportEntry createDefaultReportEntry() { + return createDefaultReportEntry(Collections.emptyMap()); } - private SimpleReportEntry createAnotherDefaultReportEntry() - { - return new SimpleReportEntry( NORMAL_RUN, 0L, - "com.abc.AnotherTestClass", null, "testAnotherMethod", null, 42 ); + private SimpleReportEntry createAnotherDefaultReportEntry() { + return new SimpleReportEntry(NORMAL_RUN, 0L, "com.abc.AnotherTestClass", null, "testAnotherMethod", null, 42); } - private SimpleReportEntry createReportEntryWithStackTrace() - { - try - { + private SimpleReportEntry createReportEntryWithStackTrace() { + try { throw new RuntimeException(); - } - catch ( RuntimeException e ) - { + } catch (RuntimeException e) { StackTraceWriter stackTraceWriter = - new LegacyPojoStackTraceWriter( "org.apache.tests.TestClass", "testMethod11", e ); - return new CategorizedReportEntry( NORMAL_RUN, 0L, - "com.abc.TestClass", "testMethod", "aGroup", stackTraceWriter, 77 ); + new LegacyPojoStackTraceWriter("org.apache.tests.TestClass", "testMethod11", e); + return new CategorizedReportEntry( + NORMAL_RUN, 0L, "com.abc.TestClass", "testMethod", "aGroup", stackTraceWriter, 77); } } - private SimpleReportEntry createReportEntryWithSpecialMessage( String message ) - { - try - { - throw new RuntimeException( message ); - } - catch ( RuntimeException e ) - { + private SimpleReportEntry createReportEntryWithSpecialMessage(String message) { + try { + throw new RuntimeException(message); + } catch (RuntimeException e) { StackTraceWriter stackTraceWriter = - new LegacyPojoStackTraceWriter( "org.apache.tests.TestClass", "testMethod11", e ); - return new CategorizedReportEntry( NORMAL_RUN, 1L, - "com.abc.TestClass", "testMethod", "aGroup", stackTraceWriter, 77 ); + new LegacyPojoStackTraceWriter("org.apache.tests.TestClass", "testMethod11", e); + return new CategorizedReportEntry( + NORMAL_RUN, 1L, "com.abc.TestClass", "testMethod", "aGroup", stackTraceWriter, 77); } } - private TestReportListener createForkingRunListener() - { - WritableBufferedByteChannel channel = (WritableBufferedByteChannel) newChannel( printStream ); - return new ForkingRunListener( new EventChannelEncoder( channel ), false ); + private TestReportListener createForkingRunListener() { + WritableBufferedByteChannel channel = (WritableBufferedByteChannel) newChannel(printStream); + return new ForkingRunListener(new EventChannelEncoder(channel), false); } - private class StandardTestRun - { + private class StandardTestRun { private MockReporter reporter; - public TestReportListener run() - throws ReporterException - { + public TestReportListener run() throws ReporterException { reset(); return createForkingRunListener(); } - public void clientReceiveContent() throws Exception - { + public void clientReceiveContent() throws Exception { TestSetMockReporterFactory providerReporterFactory = new TestSetMockReporterFactory(); - ForkClient handler = new ForkClient( providerReporterFactory, new MockNotifiableTestStream(), 1 ); - for ( Event e : streamToEvent( content.toByteArray() ) ) - { - handler.handleEvent( e ); + ForkClient handler = new ForkClient(providerReporterFactory, new MockNotifiableTestStream(), 1); + for (Event e : streamToEvent(content.toByteArray())) { + handler.handleEvent(e); } reporter = (MockReporter) handler.getReporter(); } - public String getFirstEvent() - { - return reporter.getEvents().get( 0 ); + public String getFirstEvent() { + return reporter.getEvents().get(0); } - public ReportEntry getFirstData() - { - return (ReportEntry) reporter.getData().get( 0 ); + public ReportEntry getFirstData() { + return (ReportEntry) reporter.getData().get(0); } - private void assertExpected( String actionCode, ReportEntry expected ) throws Exception - { + private void assertExpected(String actionCode, ReportEntry expected) throws Exception { clientReceiveContent(); - assertEquals( actionCode, getFirstEvent() ); + assertEquals(actionCode, getFirstEvent()); final ReportEntry firstData = getFirstData(); - assertEquals( expected.getSourceName(), firstData.getSourceName() ); - assertEquals( expected.getName(), firstData.getName() ); + assertEquals(expected.getSourceName(), firstData.getSourceName()); + assertEquals(expected.getName(), firstData.getName()); //noinspection deprecation - assertEquals( expected.getElapsed(), firstData.getElapsed() ); - assertEquals( expected.getGroup(), firstData.getGroup() ); - if ( expected.getStackTraceWriter() != null ) - { + assertEquals(expected.getElapsed(), firstData.getElapsed()); + assertEquals(expected.getGroup(), firstData.getGroup()); + if (expected.getStackTraceWriter() != null) { //noinspection ThrowableResultOfMethodCallIgnored - assertEquals( expected.getStackTraceWriter().getThrowable().getLocalizedMessage(), - firstData.getStackTraceWriter().getThrowable().getLocalizedMessage() ); - assertEquals( expected.getStackTraceWriter().writeTraceToString(), - firstData.getStackTraceWriter().writeTraceToString() ); + assertEquals( + expected.getStackTraceWriter().getThrowable().getLocalizedMessage(), + firstData.getStackTraceWriter().getThrowable().getLocalizedMessage()); + assertEquals( + expected.getStackTraceWriter().writeTraceToString(), + firstData.getStackTraceWriter().writeTraceToString()); } } - private void assertExpected( String actionCode, String expected ) throws Exception - { + private void assertExpected(String actionCode, String expected) throws Exception { clientReceiveContent(); - assertEquals( actionCode, getFirstEvent() ); - final String firstData = (String) reporter.getData().get( 0 ); - assertEquals( expected, firstData ); + assertEquals(actionCode, getFirstEvent()); + final String firstData = (String) reporter.getData().get(0); + assertEquals(expected, firstData); } - } } diff --git a/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/booterclient/JarManifestForkConfigurationTest.java b/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/booterclient/JarManifestForkConfigurationTest.java index 3564e111f8..23d850de89 100644 --- a/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/booterclient/JarManifestForkConfigurationTest.java +++ b/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/booterclient/JarManifestForkConfigurationTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire.booterclient; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.surefire.booterclient; import java.io.File; import java.net.URI; @@ -28,19 +27,22 @@ import org.apache.maven.plugin.surefire.booterclient.JarManifestForkConfiguration.ClasspathElementUri; import org.apache.maven.plugin.surefire.booterclient.output.InPluginProcessDumpSingleton; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; +import org.powermock.core.classloader.annotations.PowerMockIgnore; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; import static java.nio.charset.StandardCharsets.UTF_8; +import static org.apache.maven.plugin.surefire.booterclient.JarManifestForkConfiguration.escapeUri; import static org.apache.maven.plugin.surefire.booterclient.JarManifestForkConfiguration.relativize; import static org.apache.maven.plugin.surefire.booterclient.JarManifestForkConfiguration.toAbsoluteUri; import static org.apache.maven.plugin.surefire.booterclient.JarManifestForkConfiguration.toClasspathElementUri; -import static org.apache.maven.plugin.surefire.booterclient.JarManifestForkConfiguration.escapeUri; import static org.assertj.core.api.Assertions.assertThat; - -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; - import static org.assertj.core.util.Files.delete; import static org.assertj.core.util.Files.newTemporaryFolder; import static org.mockito.ArgumentMatchers.any; @@ -51,233 +53,184 @@ import static org.powermock.api.mockito.PowerMockito.mockStatic; import static org.powermock.api.mockito.PowerMockito.when; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; - /** * Unit tests for {@link JarManifestForkConfiguration}. */ -@RunWith( PowerMockRunner.class ) -@PrepareForTest( { JarManifestForkConfiguration.class, InPluginProcessDumpSingleton.class } ) -@PowerMockIgnore( { "org.jacoco.agent.rt.*", "com.vladium.emma.rt.*" } ) -public class JarManifestForkConfigurationTest -{ +@RunWith(PowerMockRunner.class) +@PrepareForTest({JarManifestForkConfiguration.class, InPluginProcessDumpSingleton.class}) +@PowerMockIgnore({"org.jacoco.agent.rt.*", "com.vladium.emma.rt.*"}) +public class JarManifestForkConfigurationTest { private static final File TMP = newTemporaryFolder(); private static File dumpDirectory; @BeforeClass - public static void createSystemTemporaryDir() - { - dumpDirectory = new File( TMP, "dump" ); - assertThat( dumpDirectory.mkdir() ) - .isTrue(); + public static void createSystemTemporaryDir() { + dumpDirectory = new File(TMP, "dump"); + assertThat(dumpDirectory.mkdir()).isTrue(); } @AfterClass - public static void deleteSystemTemporaryDir() - { - delete( TMP ); + public static void deleteSystemTemporaryDir() { + delete(TMP); } @Test - public void relativeClasspathUnixSimple() - throws Exception - { - mockStatic( JarManifestForkConfiguration.class ); - Path parent = mock( Path.class ); - when( parent.toString() ).thenReturn( "/home/me/prj/target/surefire" ); - Path classPathElement = mock( Path.class ); - when( classPathElement.toString() ).thenReturn( "/home/me/.m2/repository/grp/art/1.0/art-1.0.jar" ); - when( relativize( parent, classPathElement ) ) - .thenReturn( "../../../.m2/repository/grp/art/1.0/art-1.0.jar" ); - when( toClasspathElementUri( same( parent ), same( classPathElement ), same( dumpDirectory ), anyBoolean() ) ) - .thenCallRealMethod(); - when( escapeUri( anyString(), any( Charset.class ) ) ) + public void relativeClasspathUnixSimple() throws Exception { + mockStatic(JarManifestForkConfiguration.class); + Path parent = mock(Path.class); + when(parent.toString()).thenReturn("/home/me/prj/target/surefire"); + Path classPathElement = mock(Path.class); + when(classPathElement.toString()).thenReturn("/home/me/.m2/repository/grp/art/1.0/art-1.0.jar"); + when(relativize(parent, classPathElement)).thenReturn("../../../.m2/repository/grp/art/1.0/art-1.0.jar"); + when(toClasspathElementUri(same(parent), same(classPathElement), same(dumpDirectory), anyBoolean())) .thenCallRealMethod(); - assertThat( toClasspathElementUri( parent, classPathElement, dumpDirectory, true ).uri ) - .isEqualTo( "../../../.m2/repository/grp/art/1.0/art-1.0.jar" ); + when(escapeUri(anyString(), any(Charset.class))).thenCallRealMethod(); + assertThat(toClasspathElementUri(parent, classPathElement, dumpDirectory, true).uri) + .isEqualTo("../../../.m2/repository/grp/art/1.0/art-1.0.jar"); } @Test - public void relativeClasspathUnixTricky() - throws Exception - { - mockStatic( JarManifestForkConfiguration.class ); - Path parent = mock( Path.class ); - when( parent.toString() ).thenReturn( "/home/me/prj/target/surefire" ); - Path classPathElement = mock( Path.class ); - when( classPathElement.toString() ).thenReturn( "/the Maven repo/grp/art/1.0/art-1.0.jar" ); - when( relativize( parent, classPathElement ) ) - .thenReturn( "../../../../../the Maven repo/grp/art/1.0/art-1.0.jar" ); - when( toClasspathElementUri( same( parent ), same( classPathElement ), same( dumpDirectory ), anyBoolean() ) ) + public void relativeClasspathUnixTricky() throws Exception { + mockStatic(JarManifestForkConfiguration.class); + Path parent = mock(Path.class); + when(parent.toString()).thenReturn("/home/me/prj/target/surefire"); + Path classPathElement = mock(Path.class); + when(classPathElement.toString()).thenReturn("/the Maven repo/grp/art/1.0/art-1.0.jar"); + when(relativize(parent, classPathElement)).thenReturn("../../../../../the Maven repo/grp/art/1.0/art-1.0.jar"); + when(toClasspathElementUri(same(parent), same(classPathElement), same(dumpDirectory), anyBoolean())) .thenCallRealMethod(); - when( escapeUri( anyString(), any( Charset.class ) ) ) - .thenCallRealMethod(); - assertThat( toClasspathElementUri( parent, classPathElement, dumpDirectory, true ).uri ) - .isEqualTo( "../../../../../the%20Maven%20repo/grp/art/1.0/art-1.0.jar" ); + when(escapeUri(anyString(), any(Charset.class))).thenCallRealMethod(); + assertThat(toClasspathElementUri(parent, classPathElement, dumpDirectory, true).uri) + .isEqualTo("../../../../../the%20Maven%20repo/grp/art/1.0/art-1.0.jar"); } @Test - public void relativeClasspathWindowsSimple() - throws Exception - { - mockStatic( JarManifestForkConfiguration.class ); - Path parent = mock( Path.class ); - when( parent.toString() ).thenReturn( "C:\\Windows\\Temp\\surefire" ); - Path classPathElement = mock( Path.class ); - when( classPathElement.toString() ).thenReturn( "C:\\Users\\me\\.m2\\repository\\grp\\art\\1.0\\art-1.0.jar" ); - when( relativize( parent, classPathElement ) ) - .thenReturn( "..\\..\\..\\Users\\me\\.m2\\repository\\grp\\art\\1.0\\art-1.0.jar" ); - when( toClasspathElementUri( same( parent ), same( classPathElement ), same( dumpDirectory ), anyBoolean() ) ) - .thenCallRealMethod(); - when( escapeUri( anyString(), any( Charset.class ) ) ) + public void relativeClasspathWindowsSimple() throws Exception { + mockStatic(JarManifestForkConfiguration.class); + Path parent = mock(Path.class); + when(parent.toString()).thenReturn("C:\\Windows\\Temp\\surefire"); + Path classPathElement = mock(Path.class); + when(classPathElement.toString()).thenReturn("C:\\Users\\me\\.m2\\repository\\grp\\art\\1.0\\art-1.0.jar"); + when(relativize(parent, classPathElement)) + .thenReturn("..\\..\\..\\Users\\me\\.m2\\repository\\grp\\art\\1.0\\art-1.0.jar"); + when(toClasspathElementUri(same(parent), same(classPathElement), same(dumpDirectory), anyBoolean())) .thenCallRealMethod(); - assertThat( toClasspathElementUri( parent, classPathElement, dumpDirectory, true ).uri ) - .isEqualTo( "../../../Users/me/.m2/repository/grp/art/1.0/art-1.0.jar" ); + when(escapeUri(anyString(), any(Charset.class))).thenCallRealMethod(); + assertThat(toClasspathElementUri(parent, classPathElement, dumpDirectory, true).uri) + .isEqualTo("../../../Users/me/.m2/repository/grp/art/1.0/art-1.0.jar"); } @Test - public void relativeClasspathWindowsTricky() - throws Exception - { - mockStatic( JarManifestForkConfiguration.class ); - Path parent = mock( Path.class ); - when( parent.toString() ).thenReturn( "C:\\Windows\\Temp\\surefire" ); - Path classPathElement = mock( Path.class ); - when( classPathElement.toString() ) - .thenReturn( "C:\\Test User\\me\\.m2\\repository\\grp\\art\\1.0\\art-1.0.jar" ); - when( relativize( parent, classPathElement ) ) - .thenReturn( "..\\..\\..\\Test User\\me\\.m2\\repository\\grp\\art\\1.0\\art-1.0.jar" ); - when( toClasspathElementUri( same( parent ), same( classPathElement ), same( dumpDirectory ), anyBoolean() ) ) + public void relativeClasspathWindowsTricky() throws Exception { + mockStatic(JarManifestForkConfiguration.class); + Path parent = mock(Path.class); + when(parent.toString()).thenReturn("C:\\Windows\\Temp\\surefire"); + Path classPathElement = mock(Path.class); + when(classPathElement.toString()).thenReturn("C:\\Test User\\me\\.m2\\repository\\grp\\art\\1.0\\art-1.0.jar"); + when(relativize(parent, classPathElement)) + .thenReturn("..\\..\\..\\Test User\\me\\.m2\\repository\\grp\\art\\1.0\\art-1.0.jar"); + when(toClasspathElementUri(same(parent), same(classPathElement), same(dumpDirectory), anyBoolean())) .thenCallRealMethod(); - when( escapeUri( anyString(), any( Charset.class ) ) ) - .thenCallRealMethod(); - assertThat( toClasspathElementUri( parent, classPathElement, dumpDirectory, true ).uri ) - .isEqualTo( "../../../Test%20User/me/.m2/repository/grp/art/1.0/art-1.0.jar" ); + when(escapeUri(anyString(), any(Charset.class))).thenCallRealMethod(); + assertThat(toClasspathElementUri(parent, classPathElement, dumpDirectory, true).uri) + .isEqualTo("../../../Test%20User/me/.m2/repository/grp/art/1.0/art-1.0.jar"); } @Test - public void crossDriveWindows() - throws Exception - { - mockStatic( JarManifestForkConfiguration.class ); - mockStatic( InPluginProcessDumpSingleton.class ); - when( InPluginProcessDumpSingleton.getSingleton() ).thenReturn( mock( InPluginProcessDumpSingleton.class ) ); - Path parent = mock( Path.class ); - when( parent.toString() ).thenReturn( "C:\\Windows\\Temp\\surefire" ); - Path classPathElement = mock( Path.class ); - when( classPathElement.toString() ).thenReturn( "X:\\Users\\me\\.m2\\repository\\grp\\art\\1.0\\art-1.0.jar" ); - when( classPathElement.toUri() ) - .thenAnswer( new Answer() - { - @Override - public URI answer( InvocationOnMock invocation ) throws URISyntaxException - { - String path = invocation.getMock().toString(); - return new URI( "file", "", "/" + path.replace( '\\', '/' ), null ); - } - } ); - when( relativize( same( parent ), same( classPathElement ) ) ) - .thenThrow( new IllegalArgumentException( "'other' has different root" ) ); - when( toClasspathElementUri( same( parent ), same( classPathElement ), same( dumpDirectory ), anyBoolean() ) ) - .thenCallRealMethod(); - when( escapeUri( anyString(), any( Charset.class ) ) ) + public void crossDriveWindows() throws Exception { + mockStatic(JarManifestForkConfiguration.class); + mockStatic(InPluginProcessDumpSingleton.class); + when(InPluginProcessDumpSingleton.getSingleton()).thenReturn(mock(InPluginProcessDumpSingleton.class)); + Path parent = mock(Path.class); + when(parent.toString()).thenReturn("C:\\Windows\\Temp\\surefire"); + Path classPathElement = mock(Path.class); + when(classPathElement.toString()).thenReturn("X:\\Users\\me\\.m2\\repository\\grp\\art\\1.0\\art-1.0.jar"); + when(classPathElement.toUri()).thenAnswer(new Answer() { + @Override + public URI answer(InvocationOnMock invocation) throws URISyntaxException { + String path = invocation.getMock().toString(); + return new URI("file", "", "/" + path.replace('\\', '/'), null); + } + }); + when(relativize(same(parent), same(classPathElement))) + .thenThrow(new IllegalArgumentException("'other' has different root")); + when(toClasspathElementUri(same(parent), same(classPathElement), same(dumpDirectory), anyBoolean())) .thenCallRealMethod(); - when( toAbsoluteUri( same( classPathElement ) ) ) - .thenCallRealMethod(); - assertThat( toClasspathElementUri( parent, classPathElement, dumpDirectory, true ).uri ) - .isEqualTo( "file:///X:/Users/me/.m2/repository/grp/art/1.0/art-1.0.jar" ); + when(escapeUri(anyString(), any(Charset.class))).thenCallRealMethod(); + when(toAbsoluteUri(same(classPathElement))).thenCallRealMethod(); + assertThat(toClasspathElementUri(parent, classPathElement, dumpDirectory, true).uri) + .isEqualTo("file:///X:/Users/me/.m2/repository/grp/art/1.0/art-1.0.jar"); } @Test - @SuppressWarnings( "checkstyle:magicnumber" ) - public void shouldEscapeUri() - throws Exception - { - assertThat( escapeUri( "a", UTF_8 ) ).isEqualTo( "a" ); - assertThat( escapeUri( " ", UTF_8 ) ).isEqualTo( "%20" ); - assertThat( escapeUri( "%", UTF_8 ) ).isEqualTo( "%25" ); - assertThat( escapeUri( "+", UTF_8 ) ).isEqualTo( "%2B" ); - assertThat( escapeUri( ",", UTF_8 ) ).isEqualTo( "%2C" ); - assertThat( escapeUri( "/", UTF_8 ) ).isEqualTo( "/" ); - assertThat( escapeUri( "7", UTF_8 ) ).isEqualTo( "7" ); - assertThat( escapeUri( ":", UTF_8 ) ).isEqualTo( "%3A" ); - assertThat( escapeUri( "@", UTF_8 ) ).isEqualTo( "%40" ); - assertThat( escapeUri( "A", UTF_8 ) ).isEqualTo( "A" ); - assertThat( escapeUri( "[", UTF_8 ) ).isEqualTo( "%5B" ); - assertThat( escapeUri( "\\", UTF_8 ) ).isEqualTo( "/" ); - assertThat( escapeUri( "]", UTF_8 ) ).isEqualTo( "%5D" ); - assertThat( escapeUri( "`", UTF_8 ) ).isEqualTo( "%60" ); - assertThat( escapeUri( "a", UTF_8 ) ).isEqualTo( "a" ); - assertThat( escapeUri( "{", UTF_8 ) ).isEqualTo( "%7B" ); - assertThat( escapeUri( "" + (char) 0xFF, UTF_8 ) ).isEqualTo( "%C3%BF" ); - - assertThat( escapeUri( "..\\..\\..\\Test : User\\me\\.m2\\repository\\grp\\art\\1.0\\art-1.0.jar", - UTF_8 ) ) - .isEqualTo( "../../../Test%20%3A%20User/me/.m2/repository/grp/art/1.0/art-1.0.jar" ); - - assertThat( escapeUri( "..\\..\\..\\Test : User\\me\\.m2\\repository\\grp\\art\\1.0\\art-1.0.jar", - Charset.defaultCharset() ) ) - .isEqualTo( "../../../Test%20%3A%20User/me/.m2/repository/grp/art/1.0/art-1.0.jar" ); - - assertThat( escapeUri( "../../surefire-its/target/junit-pathWithÜmlaut_1/target/surefire", UTF_8 ) ) - .isEqualTo( "../../surefire-its/target/junit-pathWith%C3%9Cmlaut_1/target/surefire" ); + @SuppressWarnings("checkstyle:magicnumber") + public void shouldEscapeUri() throws Exception { + assertThat(escapeUri("a", UTF_8)).isEqualTo("a"); + assertThat(escapeUri(" ", UTF_8)).isEqualTo("%20"); + assertThat(escapeUri("%", UTF_8)).isEqualTo("%25"); + assertThat(escapeUri("+", UTF_8)).isEqualTo("%2B"); + assertThat(escapeUri(",", UTF_8)).isEqualTo("%2C"); + assertThat(escapeUri("/", UTF_8)).isEqualTo("/"); + assertThat(escapeUri("7", UTF_8)).isEqualTo("7"); + assertThat(escapeUri(":", UTF_8)).isEqualTo("%3A"); + assertThat(escapeUri("@", UTF_8)).isEqualTo("%40"); + assertThat(escapeUri("A", UTF_8)).isEqualTo("A"); + assertThat(escapeUri("[", UTF_8)).isEqualTo("%5B"); + assertThat(escapeUri("\\", UTF_8)).isEqualTo("/"); + assertThat(escapeUri("]", UTF_8)).isEqualTo("%5D"); + assertThat(escapeUri("`", UTF_8)).isEqualTo("%60"); + assertThat(escapeUri("a", UTF_8)).isEqualTo("a"); + assertThat(escapeUri("{", UTF_8)).isEqualTo("%7B"); + assertThat(escapeUri("" + (char) 0xFF, UTF_8)).isEqualTo("%C3%BF"); + + assertThat(escapeUri("..\\..\\..\\Test : User\\me\\.m2\\repository\\grp\\art\\1.0\\art-1.0.jar", UTF_8)) + .isEqualTo("../../../Test%20%3A%20User/me/.m2/repository/grp/art/1.0/art-1.0.jar"); + + assertThat(escapeUri( + "..\\..\\..\\Test : User\\me\\.m2\\repository\\grp\\art\\1.0\\art-1.0.jar", + Charset.defaultCharset())) + .isEqualTo("../../../Test%20%3A%20User/me/.m2/repository/grp/art/1.0/art-1.0.jar"); + + assertThat(escapeUri("../../surefire-its/target/junit-pathWithÜmlaut_1/target/surefire", UTF_8)) + .isEqualTo("../../surefire-its/target/junit-pathWith%C3%9Cmlaut_1/target/surefire"); String source = "../../surefire-its/target/junit-pathWithÜmlaut_1/target/surefire"; - String encoded = escapeUri( "../../surefire-its/target/junit-pathWithÜmlaut_1/target/surefire", UTF_8 ); - String decoded = URLDecoder.decode( encoded, UTF_8.name() ); - assertThat( decoded ) - .isEqualTo( source ); + String encoded = escapeUri("../../surefire-its/target/junit-pathWithÜmlaut_1/target/surefire", UTF_8); + String decoded = URLDecoder.decode(encoded, UTF_8.name()); + assertThat(decoded).isEqualTo(source); } @Test - public void shouldRelativizeOnRealPlatform() - { - Path parentDir = new File( TMP, "test-parent-1" ) - .toPath(); + public void shouldRelativizeOnRealPlatform() { + Path parentDir = new File(TMP, "test-parent-1").toPath(); - Path testDir = new File( TMP, "@1 test with white spaces" ) - .toPath(); + Path testDir = new File(TMP, "@1 test with white spaces").toPath(); - String relativeTestDir = relativize( parentDir, testDir ); + String relativeTestDir = relativize(parentDir, testDir); - assertThat( relativeTestDir ) - .isEqualTo( ".." + File.separator + "@1 test with white spaces" ); + assertThat(relativeTestDir).isEqualTo(".." + File.separator + "@1 test with white spaces"); } @Test - public void shouldMakeAbsoluteUriOnRealPlatform() - throws Exception - { - Path testDir = new File( TMP, "@2 test with white spaces" ) - .toPath(); + public void shouldMakeAbsoluteUriOnRealPlatform() throws Exception { + Path testDir = new File(TMP, "@2 test with white spaces").toPath(); - URI testDirUri = new URI( toAbsoluteUri( testDir ) ); + URI testDirUri = new URI(toAbsoluteUri(testDir)); - assertThat( testDirUri.getScheme() ) - .isEqualTo( "file" ); + assertThat(testDirUri.getScheme()).isEqualTo("file"); - assertThat( testDirUri.getRawPath() ) - .isEqualTo( testDir.toUri().getRawPath() ); + assertThat(testDirUri.getRawPath()).isEqualTo(testDir.toUri().getRawPath()); } @Test - public void shouldMakeRelativeUriOnRealPlatform() - throws Exception - { - Path parentDir = new File( TMP, "test-parent-2" ) - .toPath(); + public void shouldMakeRelativeUriOnRealPlatform() throws Exception { + Path parentDir = new File(TMP, "test-parent-2").toPath(); - Path testDir = new File( TMP, "@3 test with white spaces" ) - .toPath(); + Path testDir = new File(TMP, "@3 test with white spaces").toPath(); - ClasspathElementUri testDirUriPath = toClasspathElementUri( parentDir, testDir, dumpDirectory, true ); + ClasspathElementUri testDirUriPath = toClasspathElementUri(parentDir, testDir, dumpDirectory, true); - assertThat( testDirUriPath.uri ) - .isEqualTo( "../%403%20test%20with%20white%20spaces" ); + assertThat(testDirUriPath.uri).isEqualTo("../%403%20test%20with%20white%20spaces"); } } diff --git a/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/booterclient/MainClass.java b/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/booterclient/MainClass.java index 845897abbf..e24c93f1d3 100644 --- a/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/booterclient/MainClass.java +++ b/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/booterclient/MainClass.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire.booterclient; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,31 +16,26 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.surefire.booterclient; import java.io.IOException; /** * For testing purposes. */ -public class MainClass -{ - public static void main( String... args ) throws IOException - { - if ( "fail".equals( args[0] ) ) - { - System.exit( 1 ); - } - else - { - System.out.println( ":maven-surefire-event:\u0003:bye:" ); +public class MainClass { + public static void main(String... args) throws IOException { + if ("fail".equals(args[0])) { + System.exit(1); + } else { + System.out.println(":maven-surefire-event:\u0003:bye:"); String byeAck = ":maven-surefire-command:\u0007:bye-ack:"; byte[] cmd = new byte[byeAck.length()]; - int len = System.in.read( cmd ); - if ( len != -1 && new String( cmd, 0, len ).equals( byeAck ) ) - { - System.exit( 0 ); + int len = System.in.read(cmd); + if (len != -1 && new String(cmd, 0, len).equals(byeAck)) { + System.exit(0); } - System.exit( 1 ); + System.exit(1); } } } diff --git a/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/booterclient/MockNotifiableTestStream.java b/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/booterclient/MockNotifiableTestStream.java index 0647cc08ad..f39484d403 100644 --- a/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/booterclient/MockNotifiableTestStream.java +++ b/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/booterclient/MockNotifiableTestStream.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire.booterclient; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.surefire.booterclient; import org.apache.maven.plugin.surefire.booterclient.lazytestprovider.NotifiableTestStream; import org.apache.maven.surefire.api.booter.Shutdown; @@ -28,31 +27,19 @@ * @author Tibor Digana (tibor17) * @since 2.19 */ -final class MockNotifiableTestStream - implements NotifiableTestStream -{ +final class MockNotifiableTestStream implements NotifiableTestStream { @Override - public void provideNewTest() - { - } + public void provideNewTest() {} @Override - public void skipSinceNextTest() - { - } + public void skipSinceNextTest() {} @Override - public void shutdown( Shutdown shutdownType ) - { - } + public void shutdown(Shutdown shutdownType) {} @Override - public void noop() - { - } + public void noop() {} @Override - public void acknowledgeByeEventReceived() - { - } + public void acknowledgeByeEventReceived() {} } diff --git a/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/booterclient/MockReporter.java b/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/booterclient/MockReporter.java index c4404306fb..35899c446d 100644 --- a/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/booterclient/MockReporter.java +++ b/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/booterclient/MockReporter.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire.booterclient; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,22 +16,21 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.surefire.booterclient; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.atomic.AtomicInteger; import org.apache.maven.surefire.api.report.ReportEntry; import org.apache.maven.surefire.api.report.TestOutputReportEntry; import org.apache.maven.surefire.api.report.TestReportListener; import org.apache.maven.surefire.api.report.TestSetReportEntry; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.atomic.AtomicInteger; - /** * Internal tests use only. */ -public class MockReporter - implements TestReportListener -{ +public class MockReporter implements TestReportListener { private final List events = new ArrayList<>(); private final List data = new ArrayList<>(); @@ -73,160 +70,135 @@ public class MockReporter private final AtomicInteger testFailed = new AtomicInteger(); @Override - public void testSetStarting( TestSetReportEntry report ) - { - events.add( SET_STARTING ); - data.add( report ); + public void testSetStarting(TestSetReportEntry report) { + events.add(SET_STARTING); + data.add(report); } @Override - public void testSetCompleted( TestSetReportEntry report ) - { - events.add( SET_COMPLETED ); - data.add( report ); + public void testSetCompleted(TestSetReportEntry report) { + events.add(SET_COMPLETED); + data.add(report); } @Override - public void testStarting( ReportEntry report ) - { - events.add( TEST_STARTING ); - data.add( report ); + public void testStarting(ReportEntry report) { + events.add(TEST_STARTING); + data.add(report); } @Override - public void testSucceeded( ReportEntry report ) - { - events.add( TEST_SUCCEEDED ); + public void testSucceeded(ReportEntry report) { + events.add(TEST_SUCCEEDED); testSucceeded.incrementAndGet(); - data.add( report ); + data.add(report); } @Override - public void testError( ReportEntry report ) - { - events.add( TEST_ERROR ); - data.add( report ); + public void testError(ReportEntry report) { + events.add(TEST_ERROR); + data.add(report); testFailed.incrementAndGet(); } @Override - public void testFailed( ReportEntry report ) - { - events.add( TEST_FAILED ); - data.add( report ); + public void testFailed(ReportEntry report) { + events.add(TEST_FAILED); + data.add(report); testFailed.incrementAndGet(); } @Override - public void testSkipped( ReportEntry report ) - { - events.add( TEST_SKIPPED ); - data.add( report ); + public void testSkipped(ReportEntry report) { + events.add(TEST_SKIPPED); + data.add(report); testIgnored.incrementAndGet(); } @Override - public void testExecutionSkippedByUser() - { - } + public void testExecutionSkippedByUser() {} - public List getEvents() - { + public List getEvents() { return events; } - public List getData() - { + public List getData() { return data; } - public String getFirstEvent() - { - return events.get( 0 ); + public String getFirstEvent() { + return events.get(0); } - public ReportEntry getFirstData() - { - return (ReportEntry) data.get( 0 ); + public ReportEntry getFirstData() { + return (ReportEntry) data.get(0); } @Override - public void testAssumptionFailure( ReportEntry report ) - { - events.add( TEST_ASSUMPTION_FAIL ); - data.add( report ); + public void testAssumptionFailure(ReportEntry report) { + events.add(TEST_ASSUMPTION_FAIL); + data.add(report); testIgnored.incrementAndGet(); } @Override - public boolean isDebugEnabled() - { + public boolean isDebugEnabled() { return true; } @Override - public void debug( String message ) - { - events.add( CONSOLE_DEBUG ); - data.add( message ); + public void debug(String message) { + events.add(CONSOLE_DEBUG); + data.add(message); } @Override - public boolean isInfoEnabled() - { + public boolean isInfoEnabled() { return true; } @Override - public void info( String message ) - { - events.add( CONSOLE_INFO ); - data.add( message ); + public void info(String message) { + events.add(CONSOLE_INFO); + data.add(message); } @Override - public boolean isWarnEnabled() - { + public boolean isWarnEnabled() { return true; } @Override - public void warning( String message ) - { - events.add( CONSOLE_WARN ); - data.add( message ); + public void warning(String message) { + events.add(CONSOLE_WARN); + data.add(message); } @Override - public boolean isErrorEnabled() - { + public boolean isErrorEnabled() { return true; } @Override - public void error( String message ) - { - events.add( CONSOLE_ERR ); - data.add( message ); + public void error(String message) { + events.add(CONSOLE_ERR); + data.add(message); } @Override - public void error( String message, Throwable t ) - { - error( message ); + public void error(String message, Throwable t) { + error(message); } @Override - public void error( Throwable t ) - { - error( t.getLocalizedMessage() ); + public void error(Throwable t) { + error(t.getLocalizedMessage()); } @Override - public void writeTestOutput( TestOutputReportEntry reportEntry ) - { - events.add( reportEntry.isStdOut() ? STDOUT : STDERR ); + public void writeTestOutput(TestOutputReportEntry reportEntry) { + events.add(reportEntry.isStdOut() ? STDOUT : STDERR); String output = reportEntry.getLog(); - data.add( reportEntry.isNewLine() ? output + "\n" : output ); + data.add(reportEntry.isNewLine() ? output + "\n" : output); } } diff --git a/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/booterclient/ModularClasspathForkConfigurationTest.java b/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/booterclient/ModularClasspathForkConfigurationTest.java index 7f257c0225..d049efc097 100644 --- a/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/booterclient/ModularClasspathForkConfigurationTest.java +++ b/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/booterclient/ModularClasspathForkConfigurationTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire.booterclient; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,13 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.surefire.booterclient; + +import java.io.File; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.Properties; import org.apache.maven.plugin.surefire.booterclient.lazytestprovider.Commandline; import org.apache.maven.plugin.surefire.log.api.NullConsoleLogger; @@ -31,12 +36,6 @@ import org.apache.maven.surefire.extensions.ForkNodeFactory; import org.junit.Test; -import java.io.File; -import java.util.Collection; -import java.util.Collections; -import java.util.List; -import java.util.Properties; - import static java.io.File.pathSeparatorChar; import static java.io.File.separator; import static java.io.File.separatorChar; @@ -53,113 +52,116 @@ * @author Tibor Digana (tibor17) * @since 2.21.0.Jigsaw */ -public class ModularClasspathForkConfigurationTest -{ +public class ModularClasspathForkConfigurationTest { @Test - @SuppressWarnings( "ResultOfMethodCallIgnored" ) - public void shouldCreateModularArgsFile() throws Exception - { - Classpath booter = new Classpath( asList( "booter.jar", "non-modular.jar" ) ); - File target = new File( "target" ).getCanonicalFile(); - File tmp = new File( target, "surefire" ); + @SuppressWarnings("ResultOfMethodCallIgnored") + public void shouldCreateModularArgsFile() throws Exception { + Classpath booter = new Classpath(asList("booter.jar", "non-modular.jar")); + File target = new File("target").getCanonicalFile(); + File tmp = new File(target, "surefire"); tmp.mkdirs(); - File pwd = new File( "." ).getCanonicalFile(); - - ModularClasspathForkConfiguration config = new ModularClasspathForkConfiguration( booter, tmp, "", pwd, - new Properties(), "", - Collections.emptyMap(), new String[0], true, 1, true, - new Platform(), new NullConsoleLogger(), mock( ForkNodeFactory.class ) ); - - File patchFile = new File( "target" + separatorChar + "test-classes" ); - File descriptor = new File( tmp, "module-info.class" ); + File pwd = new File(".").getCanonicalFile(); + + ModularClasspathForkConfiguration config = new ModularClasspathForkConfiguration( + booter, + tmp, + "", + pwd, + new Properties(), + "", + Collections.emptyMap(), + new String[0], + true, + 1, + true, + new Platform(), + new NullConsoleLogger(), + mock(ForkNodeFactory.class)); + + File patchFile = new File("target" + separatorChar + "test-classes"); + File descriptor = new File(tmp, "module-info.class"); descriptor.createNewFile(); - List modulePath = - asList( "modular.jar", "target" + separatorChar + "classes" ); - List classPath = asList( "booter.jar", "non-modular.jar", patchFile.getPath() ); - Collection packages = singleton( "org.apache.abc" ); + List modulePath = asList("modular.jar", "target" + separatorChar + "classes"); + List classPath = asList("booter.jar", "non-modular.jar", patchFile.getPath()); + Collection packages = singleton("org.apache.abc"); String startClassName = ForkedBooter.class.getName(); - File jigsawArgsFile = config.createArgsFile( "abc", modulePath, classPath, packages, patchFile, - startClassName, true, Collections.emptyList() ); + File jigsawArgsFile = config.createArgsFile( + "abc", + modulePath, + classPath, + packages, + patchFile, + startClassName, + true, + Collections.emptyList()); - assertThat( jigsawArgsFile ) - .isNotNull(); + assertThat(jigsawArgsFile).isNotNull(); - List argsFileLines = readAllLines( jigsawArgsFile.toPath(), UTF_8 ); + List argsFileLines = readAllLines(jigsawArgsFile.toPath(), UTF_8); - assertThat( argsFileLines ) - .hasSize( 13 ); + assertThat(argsFileLines).hasSize(13); - assertThat( argsFileLines.get( 0 ) ) - .isEqualTo( "--module-path" ); + assertThat(argsFileLines.get(0)).isEqualTo("--module-path"); - assertThat( argsFileLines.get( 1 ) ) - .isEqualTo( "\"modular.jar" + assertThat(argsFileLines.get(1)) + .isEqualTo("\"modular.jar" + pathSeparatorChar - + "target" + ( separatorChar == '\\' ? "\\\\" : "/" ) + "classes\"" ); + + "target" + (separatorChar == '\\' ? "\\\\" : "/") + "classes\""); - assertThat( argsFileLines.get( 2 ) ) - .isEqualTo( "--class-path" ); + assertThat(argsFileLines.get(2)).isEqualTo("--class-path"); - assertThat( argsFileLines.get( 3 ) ) - .isEqualTo( "\"booter.jar" + assertThat(argsFileLines.get(3)) + .isEqualTo("\"booter.jar" + pathSeparatorChar + "non-modular.jar" + pathSeparatorChar - + replace( patchFile.getPath(), "\\", "\\\\" ) - + "\"" ); + + replace(patchFile.getPath(), "\\", "\\\\") + + "\""); - assertThat( argsFileLines.get( 4 ) ) - .isEqualTo( "--patch-module" ); + assertThat(argsFileLines.get(4)).isEqualTo("--patch-module"); - assertThat( argsFileLines.get( 5 ) ) - .isEqualTo( "abc=\"" + replace( patchFile.getPath(), "\\", "\\\\" ) + "\"" ); + assertThat(argsFileLines.get(5)).isEqualTo("abc=\"" + replace(patchFile.getPath(), "\\", "\\\\") + "\""); - assertThat( argsFileLines.get( 6 ) ) - .isEqualTo( "--add-opens" ); + assertThat(argsFileLines.get(6)).isEqualTo("--add-opens"); - assertThat( argsFileLines.get( 7 ) ) - .isEqualTo( "abc/org.apache.abc=ALL-UNNAMED" ); + assertThat(argsFileLines.get(7)).isEqualTo("abc/org.apache.abc=ALL-UNNAMED"); - assertThat( argsFileLines.get( 8 ) ) - .isEqualTo( "--add-modules" ); + assertThat(argsFileLines.get(8)).isEqualTo("--add-modules"); - assertThat( argsFileLines.get( 9 ) ) - .isEqualTo( "abc" ); + assertThat(argsFileLines.get(9)).isEqualTo("abc"); - assertThat( argsFileLines.get( 10 ) ) - .isEqualTo( "--add-reads" ); + assertThat(argsFileLines.get(10)).isEqualTo("--add-reads"); - assertThat( argsFileLines.get( 11 ) ) - .isEqualTo( "abc=ALL-UNNAMED" ); + assertThat(argsFileLines.get(11)).isEqualTo("abc=ALL-UNNAMED"); - assertThat( argsFileLines.get( 12 ) ) - .isEqualTo( ForkedBooter.class.getName() ); + assertThat(argsFileLines.get(12)).isEqualTo(ForkedBooter.class.getName()); - ModularClasspath modularClasspath = new ModularClasspath( "abc", modulePath, packages, patchFile, true ); - Classpath testClasspathUrls = new Classpath( singleton( "target" + separator + "test-classes" ) ); + ModularClasspath modularClasspath = new ModularClasspath("abc", modulePath, packages, patchFile, true); + Classpath testClasspathUrls = new Classpath(singleton("target" + separator + "test-classes")); Classpath surefireClasspathUrls = Classpath.emptyClasspath(); - ModularClasspathConfiguration modularClasspathConfiguration = - new ModularClasspathConfiguration( modularClasspath, testClasspathUrls, surefireClasspathUrls, - emptyClasspath(), true, true ); - ClassLoaderConfiguration clc = new ClassLoaderConfiguration( true, true ); - StartupConfiguration startupConfiguration = new StartupConfiguration( "JUnitCoreProvider", - modularClasspathConfiguration, clc, null, Collections.emptyList() ); + ModularClasspathConfiguration modularClasspathConfiguration = new ModularClasspathConfiguration( + modularClasspath, testClasspathUrls, surefireClasspathUrls, emptyClasspath(), true, true); + ClassLoaderConfiguration clc = new ClassLoaderConfiguration(true, true); + StartupConfiguration startupConfiguration = new StartupConfiguration( + "JUnitCoreProvider", modularClasspathConfiguration, clc, null, Collections.emptyList()); Commandline cli = new Commandline(); - config.resolveClasspath( cli, ForkedBooter.class.getName(), startupConfiguration, - SureFireFileManager.createTempFile( "surefire", "surefire-reports" ) ); - - assertThat( cli.getArguments() ).isNotNull(); - assertThat( cli.getArguments() ).hasSize( 1 ); - assertThat( cli.getArguments()[0] ).startsWith( "@" ); - File argFile = new File( cli.getArguments()[0].substring( 1 ) ); - assertThat( argFile ).isFile(); - List argsFileLines2 = readAllLines( argFile.toPath(), UTF_8 ); - assertThat( argsFileLines2 ).hasSize( 13 ); - for ( int i = 0; i < argsFileLines2.size(); i++ ) - { - String line = argsFileLines2.get( i ); - assertThat( line ).isEqualTo( argsFileLines.get( i ) ); + config.resolveClasspath( + cli, + ForkedBooter.class.getName(), + startupConfiguration, + SureFireFileManager.createTempFile("surefire", "surefire-reports")); + + assertThat(cli.getArguments()).isNotNull(); + assertThat(cli.getArguments()).hasSize(1); + assertThat(cli.getArguments()[0]).startsWith("@"); + File argFile = new File(cli.getArguments()[0].substring(1)); + assertThat(argFile).isFile(); + List argsFileLines2 = readAllLines(argFile.toPath(), UTF_8); + assertThat(argsFileLines2).hasSize(13); + for (int i = 0; i < argsFileLines2.size(); i++) { + String line = argsFileLines2.get(i); + assertThat(line).isEqualTo(argsFileLines.get(i)); } } } diff --git a/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/booterclient/TestSetMockReporterFactory.java b/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/booterclient/TestSetMockReporterFactory.java index e46be43e8d..4ab9957395 100644 --- a/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/booterclient/TestSetMockReporterFactory.java +++ b/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/booterclient/TestSetMockReporterFactory.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire.booterclient; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,49 +16,58 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.surefire.booterclient; + +import java.io.File; import org.apache.maven.plugin.surefire.StartupReportConfiguration; import org.apache.maven.plugin.surefire.extensions.SurefireConsoleOutputReporter; import org.apache.maven.plugin.surefire.extensions.SurefireStatelessReporter; import org.apache.maven.plugin.surefire.extensions.SurefireStatelessTestsetInfoReporter; -import org.apache.maven.plugin.surefire.report.DefaultReporterFactory; import org.apache.maven.plugin.surefire.log.api.NullConsoleLogger; +import org.apache.maven.plugin.surefire.report.DefaultReporterFactory; import org.apache.maven.surefire.api.report.TestOutputReportEntry; import org.apache.maven.surefire.api.report.TestReportListener; -import java.io.File; - /** * Internal tests use only. * * @author Kristian Rosenvold */ -public class TestSetMockReporterFactory - extends DefaultReporterFactory -{ - public TestSetMockReporterFactory() - { - super( defaultValue(), new NullConsoleLogger() ); +public class TestSetMockReporterFactory extends DefaultReporterFactory { + public TestSetMockReporterFactory() { + super(defaultValue(), new NullConsoleLogger()); } @Override - public TestReportListener createTestReportListener() - { + public TestReportListener createTestReportListener() { return new MockReporter(); } - /** * For testing purposes only. * * @return StartupReportConfiguration fo testing purposes */ - private static StartupReportConfiguration defaultValue() - { - File target = new File( "./target" ); - File statisticsFile = new File( target, "TESTHASH" ); - return new StartupReportConfiguration( true, true, "PLAIN", false, target, false, null, statisticsFile, - false, 0, null, null, true, new SurefireStatelessReporter(), new SurefireConsoleOutputReporter(), - new SurefireStatelessTestsetInfoReporter() ); + private static StartupReportConfiguration defaultValue() { + File target = new File("./target"); + File statisticsFile = new File(target, "TESTHASH"); + return new StartupReportConfiguration( + true, + true, + "PLAIN", + false, + target, + false, + null, + statisticsFile, + false, + 0, + null, + null, + true, + new SurefireStatelessReporter(), + new SurefireConsoleOutputReporter(), + new SurefireStatelessTestsetInfoReporter()); } } diff --git a/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/booterclient/lazytestprovider/CommandlineTest.java b/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/booterclient/lazytestprovider/CommandlineTest.java index 86d3f3c224..2ebcd3e859 100644 --- a/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/booterclient/lazytestprovider/CommandlineTest.java +++ b/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/booterclient/lazytestprovider/CommandlineTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire.booterclient.lazytestprovider; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.surefire.booterclient.lazytestprovider; import org.apache.maven.surefire.shared.utils.cli.CommandLineException; import org.assertj.core.api.Condition; @@ -29,75 +28,60 @@ /** * */ -public class CommandlineTest -{ +public class CommandlineTest { @Test - public void shouldGetEnvironmentVariables() - { + public void shouldGetEnvironmentVariables() { Commandline cli = new Commandline(); String[] env = cli.getEnvironmentVariables(); - assertThat( env ) - .doesNotHaveDuplicates() - .satisfies( new ContainsAnyStartsWith( "JAVA_HOME=" ) ); + assertThat(env).doesNotHaveDuplicates().satisfies(new ContainsAnyStartsWith("JAVA_HOME=")); - String[] excluded = { "JAVA_HOME" }; - cli = new Commandline( excluded ); + String[] excluded = {"JAVA_HOME"}; + cli = new Commandline(excluded); env = cli.getEnvironmentVariables(); - assertThat( env ) - .doesNotHaveDuplicates() - .satisfies( new NotContainsAnyStartsWith( "JAVA_HOME=" ) ); + assertThat(env).doesNotHaveDuplicates().satisfies(new NotContainsAnyStartsWith("JAVA_HOME=")); } @Test - public void shouldExecute() throws CommandLineException - { + public void shouldExecute() throws CommandLineException { Commandline cli = new Commandline(); - cli.getShell().setWorkingDirectory( System.getProperty( "user.dir" ) ); - cli.getShell().setExecutable( IS_OS_WINDOWS ? "dir" : "ls" ); + cli.getShell().setWorkingDirectory(System.getProperty("user.dir")); + cli.getShell().setExecutable(IS_OS_WINDOWS ? "dir" : "ls"); cli.execute(); } - private static final class ContainsAnyStartsWith extends Condition - { + private static final class ContainsAnyStartsWith extends Condition { private final String expected; - ContainsAnyStartsWith( String expected ) - { + ContainsAnyStartsWith(String expected) { this.expected = expected; } @Override - public boolean matches( Object[] values ) - { + public boolean matches(Object[] values) { boolean matches = false; - for ( Object value : values ) - { - assertThat( value ).isInstanceOf( String.class ); - matches |= ( (String) value ).startsWith( expected ); + for (Object value : values) { + assertThat(value).isInstanceOf(String.class); + matches |= ((String) value).startsWith(expected); } return matches; } } - private static final class NotContainsAnyStartsWith extends Condition - { + private static final class NotContainsAnyStartsWith extends Condition { private final String expected; - NotContainsAnyStartsWith( String expected ) - { + NotContainsAnyStartsWith(String expected) { this.expected = expected; } @Override - public boolean matches( Object[] values ) - { + public boolean matches(Object[] values) { boolean matches = false; - for ( Object value : values ) - { - assertThat( value ).isInstanceOf( String.class ); - matches |= ( (String) value ).startsWith( expected ); + for (Object value : values) { + assertThat(value).isInstanceOf(String.class); + matches |= ((String) value).startsWith(expected); } return !matches; } diff --git a/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/booterclient/lazytestprovider/TestLessInputStreamBuilderTest.java b/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/booterclient/lazytestprovider/TestLessInputStreamBuilderTest.java index 87bad45480..fc3287efba 100644 --- a/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/booterclient/lazytestprovider/TestLessInputStreamBuilderTest.java +++ b/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/booterclient/lazytestprovider/TestLessInputStreamBuilderTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire.booterclient.lazytestprovider; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,12 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.surefire.booterclient.lazytestprovider; + +import java.io.IOException; +import java.io.InputStream; +import java.util.Iterator; +import java.util.NoSuchElementException; import org.apache.maven.surefire.api.booter.Command; import org.apache.maven.surefire.api.booter.MasterProcessChannelDecoder; @@ -27,11 +31,6 @@ import org.junit.Test; import org.junit.rules.ExpectedException; -import java.io.IOException; -import java.io.InputStream; -import java.util.Iterator; -import java.util.NoSuchElementException; - import static java.nio.channels.Channels.newChannel; import static java.nio.charset.StandardCharsets.UTF_8; import static org.apache.maven.plugin.surefire.booterclient.lazytestprovider.TestLessInputStream.TestLessInputStreamBuilder; @@ -53,196 +52,170 @@ * @author Tibor Digana (tibor17) * @since 2.19 */ -public class TestLessInputStreamBuilderTest -{ +public class TestLessInputStreamBuilderTest { @Rule public final ExpectedException e = ExpectedException.none(); @Test - public void cachableCommandsShouldBeIterableWithStillOpenIterator() - { + public void cachableCommandsShouldBeIterableWithStillOpenIterator() { TestLessInputStreamBuilder builder = new TestLessInputStreamBuilder(); TestLessInputStream is = builder.build(); Iterator iterator = builder.getIterableCachable().iterator(); - assertFalse( iterator.hasNext() ); + assertFalse(iterator.hasNext()); builder.getCachableCommands().skipSinceNextTest(); - assertTrue( iterator.hasNext() ); - assertThat( iterator.next(), is( SKIP_SINCE_NEXT_TEST ) ); + assertTrue(iterator.hasNext()); + assertThat(iterator.next(), is(SKIP_SINCE_NEXT_TEST)); - assertFalse( iterator.hasNext() ); + assertFalse(iterator.hasNext()); - builder.getCachableCommands().shutdown( KILL ); - assertTrue( iterator.hasNext() ); - assertThat( iterator.next(), is( new Command( SHUTDOWN, "KILL" ) ) ); + builder.getCachableCommands().shutdown(KILL); + assertTrue(iterator.hasNext()); + assertThat(iterator.next(), is(new Command(SHUTDOWN, "KILL"))); - builder.removeStream( is ); + builder.removeStream(is); } @Test - public void immediateCommands() - throws IOException - { + public void immediateCommands() throws IOException { TestLessInputStreamBuilder builder = new TestLessInputStreamBuilder(); TestLessInputStream is = builder.build(); - assertThat( is.availablePermits(), is( 0 ) ); + assertThat(is.availablePermits(), is(0)); is.noop(); - assertThat( is.availablePermits(), is( 1 ) ); + assertThat(is.availablePermits(), is(1)); is.beforeNextCommand(); - assertThat( is.availablePermits(), is( 0 ) ); - assertThat( is.nextCommand(), is( Command.NOOP ) ); - assertThat( is.availablePermits(), is( 0 ) ); - e.expect( NoSuchElementException.class ); + assertThat(is.availablePermits(), is(0)); + assertThat(is.nextCommand(), is(Command.NOOP)); + assertThat(is.availablePermits(), is(0)); + e.expect(NoSuchElementException.class); is.nextCommand(); } @Test - public void combinedCommands() - throws IOException - { + public void combinedCommands() throws IOException { TestLessInputStreamBuilder builder = new TestLessInputStreamBuilder(); TestLessInputStream is = builder.build(); - assertThat( is.availablePermits(), is( 0 ) ); + assertThat(is.availablePermits(), is(0)); builder.getCachableCommands().skipSinceNextTest(); is.noop(); - assertThat( is.availablePermits(), is( 2 ) ); + assertThat(is.availablePermits(), is(2)); is.beforeNextCommand(); - assertThat( is.availablePermits(), is( 1 ) ); - assertThat( is.nextCommand(), is( Command.NOOP ) ); - assertThat( is.availablePermits(), is( 1 ) ); + assertThat(is.availablePermits(), is(1)); + assertThat(is.nextCommand(), is(Command.NOOP)); + assertThat(is.availablePermits(), is(1)); builder.getCachableCommands().skipSinceNextTest(); - assertThat( is.availablePermits(), is( 1 ) ); - builder.getImmediateCommands().shutdown( EXIT ); - assertThat( is.availablePermits(), is( 2 ) ); + assertThat(is.availablePermits(), is(1)); + builder.getImmediateCommands().shutdown(EXIT); + assertThat(is.availablePermits(), is(2)); is.beforeNextCommand(); - assertThat( is.nextCommand().getCommandType(), is( SHUTDOWN ) ); - assertThat( is.availablePermits(), is( 1 ) ); + assertThat(is.nextCommand().getCommandType(), is(SHUTDOWN)); + assertThat(is.availablePermits(), is(1)); is.beforeNextCommand(); - assertThat( is.nextCommand(), is( SKIP_SINCE_NEXT_TEST ) ); - assertThat( is.availablePermits(), is( 0 ) ); + assertThat(is.nextCommand(), is(SKIP_SINCE_NEXT_TEST)); + assertThat(is.availablePermits(), is(0)); builder.getImmediateCommands().noop(); - assertThat( is.availablePermits(), is( 1 ) ); - builder.getCachableCommands().shutdown( EXIT ); - builder.getCachableCommands().shutdown( EXIT ); - assertThat( is.availablePermits(), is( 2 ) ); + assertThat(is.availablePermits(), is(1)); + builder.getCachableCommands().shutdown(EXIT); + builder.getCachableCommands().shutdown(EXIT); + assertThat(is.availablePermits(), is(2)); is.beforeNextCommand(); - assertThat( is.nextCommand(), is( Command.NOOP ) ); - assertThat( is.availablePermits(), is( 1 ) ); + assertThat(is.nextCommand(), is(Command.NOOP)); + assertThat(is.availablePermits(), is(1)); is.beforeNextCommand(); - assertThat( is.nextCommand().getCommandType(), is( SHUTDOWN ) ); - assertThat( is.availablePermits(), is( 0 ) ); - e.expect( NoSuchElementException.class ); + assertThat(is.nextCommand().getCommandType(), is(SHUTDOWN)); + assertThat(is.availablePermits(), is(0)); + e.expect(NoSuchElementException.class); is.nextCommand(); } @Test - public void shouldDecodeTwoCommands() - throws IOException - { + public void shouldDecodeTwoCommands() throws IOException { TestLessInputStreamBuilder builder = new TestLessInputStreamBuilder(); final TestLessInputStream pluginIs = builder.build(); - InputStream is = new InputStream() - { + InputStream is = new InputStream() { private byte[] buffer; private int idx; private boolean isLastBuffer; @Override - public int read() throws IOException - { - if ( buffer == null ) - { + public int read() throws IOException { + if (buffer == null) { idx = 0; Command cmd = pluginIs.readNextCommand(); - if ( cmd != null ) - { - if ( cmd.getCommandType() == SHUTDOWN ) - { - buffer = ( ":maven-surefire-command:\u0008:shutdown:\u0005:UTF-8:\u0000\u0000\u0000\u0004:" - + cmd.toShutdownData().getParam() + ":" ).getBytes( UTF_8 ); - } - else if ( cmd.getCommandType() == NOOP ) - { - buffer = ":maven-surefire-command:\u0004:noop:".getBytes( UTF_8 ); + if (cmd != null) { + if (cmd.getCommandType() == SHUTDOWN) { + buffer = (":maven-surefire-command:\u0008:shutdown:\u0005:UTF-8:\u0000\u0000\u0000\u0004:" + + cmd.toShutdownData().getParam() + ":") + .getBytes(UTF_8); + } else if (cmd.getCommandType() == NOOP) { + buffer = ":maven-surefire-command:\u0004:noop:".getBytes(UTF_8); isLastBuffer = true; - } - else - { + } else { fail(); } } } - if ( buffer != null ) - { + if (buffer != null) { byte b = buffer[idx++]; - if ( idx == buffer.length ) - { + if (idx == buffer.length) { buffer = null; idx = 0; } return b; } - if ( isLastBuffer ) - { + if (isLastBuffer) { return -1; } throw new IOException(); } }; - MasterProcessChannelDecoder decoder = - new CommandChannelDecoder( newChannel( is ), new ForkedNodeArg( 1, false ) ); - builder.getImmediateCommands().shutdown( KILL ); + MasterProcessChannelDecoder decoder = new CommandChannelDecoder(newChannel(is), new ForkedNodeArg(1, false)); + builder.getImmediateCommands().shutdown(KILL); builder.getImmediateCommands().noop(); Command bye = decoder.decode(); - assertThat( bye, is( notNullValue() ) ); - assertThat( bye.getCommandType(), is( SHUTDOWN ) ); - assertThat( bye.getData(), is( KILL.name() ) ); + assertThat(bye, is(notNullValue())); + assertThat(bye.getCommandType(), is(SHUTDOWN)); + assertThat(bye.getData(), is(KILL.name())); Command noop = decoder.decode(); - assertThat( noop, is( notNullValue() ) ); - assertThat( noop.getCommandType(), is( NOOP ) ); + assertThat(noop, is(notNullValue())); + assertThat(noop.getCommandType(), is(NOOP)); } - @Test( expected = UnsupportedOperationException.class ) - public void shouldThrowUnsupportedException1() - { + @Test(expected = UnsupportedOperationException.class) + public void shouldThrowUnsupportedException1() { TestLessInputStreamBuilder builder = new TestLessInputStreamBuilder(); builder.getImmediateCommands().provideNewTest(); } - @Test( expected = UnsupportedOperationException.class ) - public void shouldThrowUnsupportedException2() - { + @Test(expected = UnsupportedOperationException.class) + public void shouldThrowUnsupportedException2() { TestLessInputStreamBuilder builder = new TestLessInputStreamBuilder(); builder.getImmediateCommands().skipSinceNextTest(); } - @Test( expected = UnsupportedOperationException.class ) - public void shouldThrowUnsupportedException3() - { + @Test(expected = UnsupportedOperationException.class) + public void shouldThrowUnsupportedException3() { TestLessInputStreamBuilder builder = new TestLessInputStreamBuilder(); builder.getImmediateCommands().acknowledgeByeEventReceived(); } - @Test( expected = UnsupportedOperationException.class ) - public void shouldThrowUnsupportedException4() - { + @Test(expected = UnsupportedOperationException.class) + public void shouldThrowUnsupportedException4() { TestLessInputStreamBuilder builder = new TestLessInputStreamBuilder(); builder.getCachableCommands().acknowledgeByeEventReceived(); } - @Test( expected = UnsupportedOperationException.class ) - public void shouldThrowUnsupportedException5() - { + @Test(expected = UnsupportedOperationException.class) + public void shouldThrowUnsupportedException5() { TestLessInputStreamBuilder builder = new TestLessInputStreamBuilder(); builder.getCachableCommands().provideNewTest(); } - @Test( expected = UnsupportedOperationException.class ) - public void shouldThrowUnsupportedException6() - { + @Test(expected = UnsupportedOperationException.class) + public void shouldThrowUnsupportedException6() { TestLessInputStreamBuilder builder = new TestLessInputStreamBuilder(); builder.getCachableCommands().noop(); } diff --git a/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/booterclient/lazytestprovider/TestProvidingInputStreamTest.java b/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/booterclient/lazytestprovider/TestProvidingInputStreamTest.java index 29a5745718..be578375eb 100644 --- a/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/booterclient/lazytestprovider/TestProvidingInputStreamTest.java +++ b/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/booterclient/lazytestprovider/TestProvidingInputStreamTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire.booterclient.lazytestprovider; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,12 +16,7 @@ * specific language governing permissions and limitations * under the License. */ - -import org.apache.maven.surefire.api.booter.Command; -import org.apache.maven.surefire.api.booter.MasterProcessChannelDecoder; -import org.apache.maven.surefire.booter.ForkedNodeArg; -import org.apache.maven.surefire.booter.spi.CommandChannelDecoder; -import org.junit.Test; +package org.apache.maven.plugin.surefire.booterclient.lazytestprovider; import java.io.IOException; import java.io.InputStream; @@ -35,6 +28,12 @@ import java.util.concurrent.FutureTask; import java.util.concurrent.TimeUnit; +import org.apache.maven.surefire.api.booter.Command; +import org.apache.maven.surefire.api.booter.MasterProcessChannelDecoder; +import org.apache.maven.surefire.booter.ForkedNodeArg; +import org.apache.maven.surefire.booter.spi.CommandChannelDecoder; +import org.junit.Test; + import static java.nio.channels.Channels.newChannel; import static java.nio.charset.StandardCharsets.UTF_8; import static org.apache.maven.surefire.api.booter.Command.TEST_SET_FINISHED; @@ -53,134 +52,108 @@ * @author Tibor Digana (tibor17) * @since 2.19 */ -public class TestProvidingInputStreamTest -{ +public class TestProvidingInputStreamTest { private static final int WAIT_LOOPS = 100; + @Test - public void closedStreamShouldReturnNullAsEndOfStream() - throws IOException - { + public void closedStreamShouldReturnNullAsEndOfStream() throws IOException { Queue commands = new ArrayDeque<>(); - TestProvidingInputStream is = new TestProvidingInputStream( commands ); + TestProvidingInputStream is = new TestProvidingInputStream(commands); is.close(); - assertThat( is.readNextCommand(), is( nullValue() ) ); + assertThat(is.readNextCommand(), is(nullValue())); } @Test - public void emptyStreamShouldWaitUntilClosed() - throws Exception - { + public void emptyStreamShouldWaitUntilClosed() throws Exception { Queue commands = new ArrayDeque<>(); - final TestProvidingInputStream is = new TestProvidingInputStream( commands ); + final TestProvidingInputStream is = new TestProvidingInputStream(commands); final Thread streamThread = Thread.currentThread(); - FutureTask futureTask = new FutureTask<>( new Callable() - { + FutureTask futureTask = new FutureTask<>(new Callable() { @Override - public State call() - { - sleep( 1000L ); + public State call() { + sleep(1000L); State state = streamThread.getState(); is.close(); return state; } - } ); - Thread assertionThread = new Thread( futureTask ); + }); + Thread assertionThread = new Thread(futureTask); assertionThread.start(); - assertThat( is.readNextCommand(), is( nullValue() ) ); + assertThat(is.readNextCommand(), is(nullValue())); State state = futureTask.get(); - assertThat( state, is( State.WAITING ) ); + assertThat(state, is(State.WAITING)); } @Test - public void finishedTestsetShouldNotBlock() - throws IOException - { - final TestProvidingInputStream is = new TestProvidingInputStream( new ArrayDeque() ); + public void finishedTestsetShouldNotBlock() throws IOException { + final TestProvidingInputStream is = new TestProvidingInputStream(new ArrayDeque()); is.testSetFinished(); - new Thread( new Runnable() - { - @Override - public void run() - { - is.provideNewTest(); - } - } ).start(); + new Thread(new Runnable() { + @Override + public void run() { + is.provideNewTest(); + } + }) + .start(); - for ( int i = 0; i < 2; i++ ) - { + for (int i = 0; i < 2; i++) { Command cmd = is.readNextCommand(); - assertThat( cmd.getData(), is( nullValue() ) ); - assertThat( cmd, is( TEST_SET_FINISHED ) ); + assertThat(cmd.getData(), is(nullValue())); + assertThat(cmd, is(TEST_SET_FINISHED)); } - boolean emptyStream = isInputStreamEmpty( is ); + boolean emptyStream = isInputStreamEmpty(is); is.close(); - assertTrue( emptyStream ); - assertThat( is.readNextCommand(), is( nullValue() ) ); + assertTrue(emptyStream); + assertThat(is.readNextCommand(), is(nullValue())); } @Test - public void shouldReadTest() - throws IOException - { + public void shouldReadTest() throws IOException { Queue commands = new ArrayDeque<>(); - commands.add( "Test" ); - final TestProvidingInputStream is = new TestProvidingInputStream( commands ); - new Thread( new Runnable() - { - @Override - public void run() - { - is.provideNewTest(); - } - } ).start(); + commands.add("Test"); + final TestProvidingInputStream is = new TestProvidingInputStream(commands); + new Thread(new Runnable() { + @Override + public void run() { + is.provideNewTest(); + } + }) + .start(); Command cmd = is.readNextCommand(); - assertThat( cmd.getData(), is( "Test" ) ); + assertThat(cmd.getData(), is("Test")); is.close(); } @Test - public void shouldDecodeTwoCommands() - throws IOException - { - final TestProvidingInputStream pluginIs = new TestProvidingInputStream( new ConcurrentLinkedQueue() ); - InputStream is = new InputStream() - { + public void shouldDecodeTwoCommands() throws IOException { + final TestProvidingInputStream pluginIs = new TestProvidingInputStream(new ConcurrentLinkedQueue()); + InputStream is = new InputStream() { private byte[] buffer; private int idx; @Override - public int read() throws IOException - { - if ( buffer == null ) - { + public int read() throws IOException { + if (buffer == null) { idx = 0; Command cmd = pluginIs.readNextCommand(); - if ( cmd != null ) - { - if ( cmd.getCommandType() == BYE_ACK ) - { - buffer = ":maven-surefire-command:\u0007:bye-ack:".getBytes( UTF_8 ); - } - else if ( cmd.getCommandType() == NOOP ) - { - buffer = ":maven-surefire-command:\u0004:noop:".getBytes( UTF_8 ); - } - else - { + if (cmd != null) { + if (cmd.getCommandType() == BYE_ACK) { + buffer = ":maven-surefire-command:\u0007:bye-ack:".getBytes(UTF_8); + } else if (cmd.getCommandType() == NOOP) { + buffer = ":maven-surefire-command:\u0004:noop:".getBytes(UTF_8); + } else { fail(); } } } - if ( buffer != null ) - { + if (buffer != null) { byte b = buffer[idx++]; - if ( idx == buffer.length ) - { + if (idx == buffer.length) { buffer = null; idx = 0; } @@ -189,26 +162,21 @@ else if ( cmd.getCommandType() == NOOP ) throw new IOException(); } }; - MasterProcessChannelDecoder decoder = - new CommandChannelDecoder( newChannel( is ), new ForkedNodeArg( 1, false ) ); + MasterProcessChannelDecoder decoder = new CommandChannelDecoder(newChannel(is), new ForkedNodeArg(1, false)); pluginIs.acknowledgeByeEventReceived(); pluginIs.noop(); Command bye = decoder.decode(); - assertThat( bye, is( notNullValue() ) ); - assertThat( bye.getCommandType(), is( BYE_ACK ) ); + assertThat(bye, is(notNullValue())); + assertThat(bye.getCommandType(), is(BYE_ACK)); Command noop = decoder.decode(); - assertThat( noop, is( notNullValue() ) ); - assertThat( noop.getCommandType(), is( NOOP ) ); + assertThat(noop, is(notNullValue())); + assertThat(noop.getCommandType(), is(NOOP)); } - private static void sleep( long millis ) - { - try - { - TimeUnit.MILLISECONDS.sleep( millis ); - } - catch ( InterruptedException e ) - { + private static void sleep(long millis) { + try { + TimeUnit.MILLISECONDS.sleep(millis); + } catch (InterruptedException e) { // do nothing } } @@ -218,37 +186,28 @@ private static void sleep( long millis ) * @param is examined stream * @return {@code true} if the {@link InputStream#read()} is waiting for a new byte. */ - private static boolean isInputStreamEmpty( final TestProvidingInputStream is ) - { - Thread t = new Thread( new Runnable() - { + private static boolean isInputStreamEmpty(final TestProvidingInputStream is) { + Thread t = new Thread(new Runnable() { @Override - public void run() - { - try - { + public void run() { + try { is.readNextCommand(); - } - catch ( IOException e ) - { + } catch (IOException e) { Throwable cause = e.getCause(); Throwable err = cause == null ? e : cause; - if ( !( err instanceof InterruptedException ) ) - { - System.err.println( err.toString() ); + if (!(err instanceof InterruptedException)) { + System.err.println(err.toString()); } } } - } ); + }); t.start(); State state; int loops = 0; - do - { - sleep( 100L ); + do { + sleep(100L); state = t.getState(); - } - while ( state == State.NEW && loops++ < WAIT_LOOPS ); + } while (state == State.NEW && loops++ < WAIT_LOOPS); t.interrupt(); return state == State.WAITING || state == State.TIMED_WAITING; } diff --git a/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/booterclient/output/ForkClientTest.java b/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/booterclient/output/ForkClientTest.java index 393d5c9e8b..4013cb0747 100644 --- a/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/booterclient/output/ForkClientTest.java +++ b/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/booterclient/output/ForkClientTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire.booterclient.output; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,18 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.surefire.booterclient.output; + +import javax.annotation.Nonnull; + +import java.io.ByteArrayInputStream; +import java.io.Closeable; +import java.io.File; +import java.nio.channels.ReadableByteChannel; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.TimeUnit; import org.apache.maven.plugin.surefire.booterclient.MockReporter; import org.apache.maven.plugin.surefire.booterclient.lazytestprovider.NotifiableTestStream; @@ -46,26 +56,16 @@ import org.apache.maven.surefire.api.event.TestSucceededEvent; import org.apache.maven.surefire.api.event.TestsetCompletedEvent; import org.apache.maven.surefire.api.event.TestsetStartingEvent; +import org.apache.maven.surefire.api.fork.ForkNodeArguments; import org.apache.maven.surefire.api.report.ReportEntry; import org.apache.maven.surefire.api.report.SafeThrowable; import org.apache.maven.surefire.api.report.SimpleReportEntry; import org.apache.maven.surefire.api.report.StackTraceWriter; import org.apache.maven.surefire.api.report.TestSetReportEntry; import org.apache.maven.surefire.extensions.EventHandler; -import org.apache.maven.surefire.api.fork.ForkNodeArguments; import org.apache.maven.surefire.extensions.util.CountdownCloseable; import org.junit.Test; -import javax.annotation.Nonnull; -import java.io.ByteArrayInputStream; -import java.io.Closeable; -import java.io.File; -import java.nio.channels.ReadableByteChannel; -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.ConcurrentLinkedQueue; -import java.util.concurrent.LinkedBlockingQueue; -import java.util.concurrent.TimeUnit; - import static java.nio.channels.Channels.newChannel; import static org.apache.maven.plugin.surefire.booterclient.MockReporter.CONSOLE_DEBUG; import static org.apache.maven.plugin.surefire.booterclient.MockReporter.CONSOLE_ERR; @@ -101,1820 +101,1406 @@ * @author Tibor Digana (tibor17) * @since 3.0.0-M4 */ -public class ForkClientTest -{ +public class ForkClientTest { private static final int ELAPSED_TIME = 102; - @Test( expected = NullPointerException.class ) - public void shouldFailOnNPE() - { - String cwd = System.getProperty( "user.dir" ); - File target = new File( cwd, "target" ); - DefaultReporterFactory factory = mock( DefaultReporterFactory.class ); - when( factory.getReportsDirectory() ) - .thenReturn( new File( target, "surefire-reports" ) ); - ForkClient client = new ForkClient( factory, null, 0 ); - client.handleEvent( null ); + @Test(expected = NullPointerException.class) + public void shouldFailOnNPE() { + String cwd = System.getProperty("user.dir"); + File target = new File(cwd, "target"); + DefaultReporterFactory factory = mock(DefaultReporterFactory.class); + when(factory.getReportsDirectory()).thenReturn(new File(target, "surefire-reports")); + ForkClient client = new ForkClient(factory, null, 0); + client.handleEvent(null); } @Test - public void shouldLogJvmMessage() throws Exception - { + public void shouldLogJvmMessage() throws Exception { String nativeStream = "Listening for transport dt_socket at address: bla"; EH eventHandler = new EH(); - CountdownCloseable countdown = new CountdownCloseable( mock( Closeable.class ), 1 ); - ConsoleLoggerMock logger = new ConsoleLoggerMock( false, true, true, true ); - ForkNodeArgumentsMock arguments = new ForkNodeArgumentsMock( logger, new File( "" ) ); - ReadableByteChannel channel = newChannel( new ByteArrayInputStream( nativeStream.getBytes() ) ); - try ( EventConsumerThread t = new EventConsumerThread( "t", channel, eventHandler, countdown, arguments ) ) - { + CountdownCloseable countdown = new CountdownCloseable(mock(Closeable.class), 1); + ConsoleLoggerMock logger = new ConsoleLoggerMock(false, true, true, true); + ForkNodeArgumentsMock arguments = new ForkNodeArgumentsMock(logger, new File("")); + ReadableByteChannel channel = newChannel(new ByteArrayInputStream(nativeStream.getBytes())); + try (EventConsumerThread t = new EventConsumerThread("t", channel, eventHandler, countdown, arguments)) { t.start(); countdown.awaitClosed(); - assertThat( logger.info ) - .hasSize( 1 ) - .contains( "Listening for transport dt_socket at address: bla" ); + assertThat(logger.info).hasSize(1).contains("Listening for transport dt_socket at address: bla"); } - assertThat( eventHandler.sizeOfEventCache() ) - .isEqualTo( 0 ); + assertThat(eventHandler.sizeOfEventCache()).isEqualTo(0); - assertThat( logger.isDebugEnabledCalled ) - .isTrue(); + assertThat(logger.isDebugEnabledCalled).isTrue(); - assertThat( logger.isInfoEnabledCalled ) - .isTrue(); + assertThat(logger.isInfoEnabledCalled).isTrue(); } @Test - public void shouldLogJvmError1() throws Exception - { + public void shouldLogJvmError1() throws Exception { String nativeStream = "\nCould not create the Java Virtual Machine\n"; EH eventHandler = new EH(); - CountdownCloseable countdown = new CountdownCloseable( mock( Closeable.class ), 1 ); - ConsoleLoggerMock logger = new ConsoleLoggerMock( false, false, false, false ); - ForkNodeArgumentsMock arguments = new ForkNodeArgumentsMock( logger, new File( "" ) ); - ReadableByteChannel channel = newChannel( new ByteArrayInputStream( nativeStream.getBytes() ) ); - try ( EventConsumerThread t = new EventConsumerThread( "t", channel, eventHandler, countdown, arguments ) ) - { + CountdownCloseable countdown = new CountdownCloseable(mock(Closeable.class), 1); + ConsoleLoggerMock logger = new ConsoleLoggerMock(false, false, false, false); + ForkNodeArgumentsMock arguments = new ForkNodeArgumentsMock(logger, new File("")); + ReadableByteChannel channel = newChannel(new ByteArrayInputStream(nativeStream.getBytes())); + try (EventConsumerThread t = new EventConsumerThread("t", channel, eventHandler, countdown, arguments)) { t.start(); countdown.awaitClosed(); - assertThat( logger.error ) - .hasSize( 1 ) - .contains( "Could not create the Java Virtual Machine" ); + assertThat(logger.error).hasSize(1).contains("Could not create the Java Virtual Machine"); } - assertThat( eventHandler.sizeOfEventCache() ) - .isEqualTo( 0 ); + assertThat(eventHandler.sizeOfEventCache()).isEqualTo(0); } @Test - public void shouldLogJvmError2() throws Exception - { + public void shouldLogJvmError2() throws Exception { String nativeStream = "\nError occurred during initialization of VM\n"; EH eventHandler = new EH(); - CountdownCloseable countdown = new CountdownCloseable( mock( Closeable.class ), 1 ); - ConsoleLoggerMock logger = new ConsoleLoggerMock( false, false, false, false ); - ForkNodeArgumentsMock arguments = new ForkNodeArgumentsMock( logger, new File( "" ) ); - ReadableByteChannel channel = newChannel( new ByteArrayInputStream( nativeStream.getBytes() ) ); - try ( EventConsumerThread t = new EventConsumerThread( "t", channel, eventHandler, countdown, arguments ) ) - { + CountdownCloseable countdown = new CountdownCloseable(mock(Closeable.class), 1); + ConsoleLoggerMock logger = new ConsoleLoggerMock(false, false, false, false); + ForkNodeArgumentsMock arguments = new ForkNodeArgumentsMock(logger, new File("")); + ReadableByteChannel channel = newChannel(new ByteArrayInputStream(nativeStream.getBytes())); + try (EventConsumerThread t = new EventConsumerThread("t", channel, eventHandler, countdown, arguments)) { t.start(); countdown.awaitClosed(); - assertThat( logger.error ) - .hasSize( 1 ) - .contains( "Error occurred during initialization of VM" ); + assertThat(logger.error).hasSize(1).contains("Error occurred during initialization of VM"); } - assertThat( eventHandler.sizeOfEventCache() ) - .isEqualTo( 0 ); + assertThat(eventHandler.sizeOfEventCache()).isEqualTo(0); } @Test - public void shouldLogJvmError3() throws Exception - { + public void shouldLogJvmError3() throws Exception { String nativeStream = "\nError: A fatal exception has occurred. Program will exit.\n"; EH eventHandler = new EH(); - CountdownCloseable countdown = new CountdownCloseable( mock( Closeable.class ), 1 ); - ConsoleLoggerMock logger = new ConsoleLoggerMock( false, false, false, false ); - ForkNodeArgumentsMock arguments = new ForkNodeArgumentsMock( logger, new File( "" ) ); - ReadableByteChannel channel = newChannel( new ByteArrayInputStream( nativeStream.getBytes() ) ); - try ( EventConsumerThread t = new EventConsumerThread( "t", channel, eventHandler, countdown, arguments ) ) - { + CountdownCloseable countdown = new CountdownCloseable(mock(Closeable.class), 1); + ConsoleLoggerMock logger = new ConsoleLoggerMock(false, false, false, false); + ForkNodeArgumentsMock arguments = new ForkNodeArgumentsMock(logger, new File("")); + ReadableByteChannel channel = newChannel(new ByteArrayInputStream(nativeStream.getBytes())); + try (EventConsumerThread t = new EventConsumerThread("t", channel, eventHandler, countdown, arguments)) { t.start(); countdown.awaitClosed(); - assertThat( logger.error ) - .hasSize( 1 ) - .contains( "Error: A fatal exception has occurred. Program will exit." ); + assertThat(logger.error).hasSize(1).contains("Error: A fatal exception has occurred. Program will exit."); } - assertThat( eventHandler.sizeOfEventCache() ) - .isEqualTo( 0 ); + assertThat(eventHandler.sizeOfEventCache()).isEqualTo(0); } @Test - public void shouldLogJvmError4() throws Exception - { + public void shouldLogJvmError4() throws Exception { String nativeStream = "\nCould not reserve enough space for object heap\n"; EH eventHandler = new EH(); - CountdownCloseable countdown = new CountdownCloseable( mock( Closeable.class ), 1 ); - ConsoleLoggerMock logger = new ConsoleLoggerMock( false, false, false, false ); - ForkNodeArgumentsMock arguments = new ForkNodeArgumentsMock( logger, new File( "" ) ); - ReadableByteChannel channel = newChannel( new ByteArrayInputStream( nativeStream.getBytes() ) ); - try ( EventConsumerThread t = new EventConsumerThread( "t", channel, eventHandler, countdown, arguments ) ) - { + CountdownCloseable countdown = new CountdownCloseable(mock(Closeable.class), 1); + ConsoleLoggerMock logger = new ConsoleLoggerMock(false, false, false, false); + ForkNodeArgumentsMock arguments = new ForkNodeArgumentsMock(logger, new File("")); + ReadableByteChannel channel = newChannel(new ByteArrayInputStream(nativeStream.getBytes())); + try (EventConsumerThread t = new EventConsumerThread("t", channel, eventHandler, countdown, arguments)) { t.start(); countdown.awaitClosed(); - assertThat( logger.error ) - .hasSize( 1 ) - .contains( "Could not reserve enough space for object heap" ); + assertThat(logger.error).hasSize(1).contains("Could not reserve enough space for object heap"); } - assertThat( eventHandler.sizeOfEventCache() ) - .isEqualTo( 0 ); + assertThat(eventHandler.sizeOfEventCache()).isEqualTo(0); } @Test - public void shouldLogJvmError5() throws Exception - { + public void shouldLogJvmError5() throws Exception { String nativeStream = "\njava.lang.module.FindException: Module java.ws.rs not found, required by com.foo.api"; EH eventHandler = new EH(); - CountdownCloseable countdown = new CountdownCloseable( mock( Closeable.class ), 1 ); - ConsoleLoggerMock logger = new ConsoleLoggerMock( false, false, false, false ); - ForkNodeArgumentsMock arguments = new ForkNodeArgumentsMock( logger, new File( "" ) ); - ReadableByteChannel channel = newChannel( new ByteArrayInputStream( nativeStream.getBytes() ) ); - try ( EventConsumerThread t = new EventConsumerThread( "t", channel, eventHandler, countdown, arguments ) ) - { + CountdownCloseable countdown = new CountdownCloseable(mock(Closeable.class), 1); + ConsoleLoggerMock logger = new ConsoleLoggerMock(false, false, false, false); + ForkNodeArgumentsMock arguments = new ForkNodeArgumentsMock(logger, new File("")); + ReadableByteChannel channel = newChannel(new ByteArrayInputStream(nativeStream.getBytes())); + try (EventConsumerThread t = new EventConsumerThread("t", channel, eventHandler, countdown, arguments)) { t.start(); countdown.awaitClosed(); - assertThat( logger.error ) - .hasSize( 1 ) - .contains( "java.lang.module.FindException: Module java.ws.rs not found, required by com.foo.api" ); + assertThat(logger.error) + .hasSize(1) + .contains("java.lang.module.FindException: Module java.ws.rs not found, required by com.foo.api"); } - assertThat( eventHandler.sizeOfEventCache() ) - .isEqualTo( 0 ); + assertThat(eventHandler.sizeOfEventCache()).isEqualTo(0); } @Test - public void shouldLogJvmError6() throws Exception - { + public void shouldLogJvmError6() throws Exception { String nativeStream = "\njava.lang.module.FindException: Module java.ws.rs not found, required by com.foo.api"; EH eventHandler = new EH(); - CountdownCloseable countdown = new CountdownCloseable( mock( Closeable.class ), 1 ); - ConsoleLoggerMock logger = new ConsoleLoggerMock( false, false, false, false ); - ForkNodeArgumentsMock arguments = new ForkNodeArgumentsMock( logger, new File( "" ) ); - ReadableByteChannel channel = newChannel( new ByteArrayInputStream( nativeStream.getBytes() ) ); - try ( EventConsumerThread t = new EventConsumerThread( "t", channel, eventHandler, countdown, arguments ) ) - { + CountdownCloseable countdown = new CountdownCloseable(mock(Closeable.class), 1); + ConsoleLoggerMock logger = new ConsoleLoggerMock(false, false, false, false); + ForkNodeArgumentsMock arguments = new ForkNodeArgumentsMock(logger, new File("")); + ReadableByteChannel channel = newChannel(new ByteArrayInputStream(nativeStream.getBytes())); + try (EventConsumerThread t = new EventConsumerThread("t", channel, eventHandler, countdown, arguments)) { t.start(); countdown.awaitClosed(); - assertThat( logger.error ) - .hasSize( 1 ) - .contains( "java.lang.module.FindException: Module java.ws.rs not found, required by com.foo.api" ); + assertThat(logger.error) + .hasSize(1) + .contains("java.lang.module.FindException: Module java.ws.rs not found, required by com.foo.api"); } - assertThat( eventHandler.sizeOfEventCache() ) - .isEqualTo( 0 ); + assertThat(eventHandler.sizeOfEventCache()).isEqualTo(0); } @Test - public void shouldLogUnorderedErrors() throws Exception - { + public void shouldLogUnorderedErrors() throws Exception { String nativeStream = "unordered error"; EH eventHandler = new EH(); - CountdownCloseable countdown = new CountdownCloseable( mock( Closeable.class ), 1 ); - ConsoleLoggerMock logger = new ConsoleLoggerMock( true, true, true, true ); - ForkNodeArgumentsMock arguments = new ForkNodeArgumentsMock( logger, new File( "" ) ); - ReadableByteChannel channel = newChannel( new ByteArrayInputStream( nativeStream.getBytes() ) ); - try ( EventConsumerThread t = new EventConsumerThread( "t", channel, eventHandler, countdown, arguments ) ) - { + CountdownCloseable countdown = new CountdownCloseable(mock(Closeable.class), 1); + ConsoleLoggerMock logger = new ConsoleLoggerMock(true, true, true, true); + ForkNodeArgumentsMock arguments = new ForkNodeArgumentsMock(logger, new File("")); + ReadableByteChannel channel = newChannel(new ByteArrayInputStream(nativeStream.getBytes())); + try (EventConsumerThread t = new EventConsumerThread("t", channel, eventHandler, countdown, arguments)) { t.start(); countdown.awaitClosed(); - assertThat( logger.debug ) - .hasSize( 1 ) - .contains( "unordered error" ); + assertThat(logger.debug).hasSize(1).contains("unordered error"); } - assertThat( eventHandler.sizeOfEventCache() ) - .isEqualTo( 0 ); + assertThat(eventHandler.sizeOfEventCache()).isEqualTo(0); - assertThat( logger.isDebugEnabledCalled ) - .isTrue(); + assertThat(logger.isDebugEnabledCalled).isTrue(); String msg = - "Corrupted channel by directly writing to native stream in forked JVM 0. Stream 'unordered error'."; - assertThat( arguments.dumpStreamText ) - .hasSize( 1 ) - .contains( msg ); - - assertThat( arguments.logWarningAtEnd ) - .hasSize( 1 ); - assertThat( arguments.logWarningAtEnd.peek() ) - .startsWith( "Corrupted channel by directly writing to native stream in forked JVM 0. " - + "See FAQ web page and the dump file" ); + "Corrupted channel by directly writing to native stream in forked JVM 0. Stream 'unordered error'."; + assertThat(arguments.dumpStreamText).hasSize(1).contains(msg); + + assertThat(arguments.logWarningAtEnd).hasSize(1); + assertThat(arguments.logWarningAtEnd.peek()) + .startsWith("Corrupted channel by directly writing to native stream in forked JVM 0. " + + "See FAQ web page and the dump file"); } @Test - public void shouldLogJvmMessageAndProcessEvent() throws Exception - { + public void shouldLogJvmMessageAndProcessEvent() throws Exception { String nativeStream = "Listening for transport dt_socket at address: bla\n:maven-surefire-event:\u0003:bye:\n"; EH eventHandler = new EH(); - CountdownCloseable countdown = new CountdownCloseable( mock( Closeable.class ), 1 ); - ConsoleLoggerMock logger = new ConsoleLoggerMock( true, true, true, true ); - ForkNodeArgumentsMock arguments = new ForkNodeArgumentsMock( logger, new File( "" ) ); - ReadableByteChannel channel = newChannel( new ByteArrayInputStream( nativeStream.getBytes() ) ); - try ( EventConsumerThread t = new EventConsumerThread( "t", channel, eventHandler, countdown, arguments ) ) - { + CountdownCloseable countdown = new CountdownCloseable(mock(Closeable.class), 1); + ConsoleLoggerMock logger = new ConsoleLoggerMock(true, true, true, true); + ForkNodeArgumentsMock arguments = new ForkNodeArgumentsMock(logger, new File("")); + ReadableByteChannel channel = newChannel(new ByteArrayInputStream(nativeStream.getBytes())); + try (EventConsumerThread t = new EventConsumerThread("t", channel, eventHandler, countdown, arguments)) { t.start(); Event event = eventHandler.pullEvent(); - assertThat( event ) - .isNotNull(); - assertThat( event.isControlCategory() ) - .isTrue(); - assertThat( event.getEventType() ) - .isEqualTo( BOOTERCODE_BYE ); + assertThat(event).isNotNull(); + assertThat(event.isControlCategory()).isTrue(); + assertThat(event.getEventType()).isEqualTo(BOOTERCODE_BYE); - assertThat( logger.debug ) - .hasSize( 1 ) - .contains( "Listening for transport dt_socket at address: bla" ); + assertThat(logger.debug).hasSize(1).contains("Listening for transport dt_socket at address: bla"); countdown.awaitClosed(); } - assertThat( eventHandler.sizeOfEventCache() ) - .isEqualTo( 0 ); + assertThat(eventHandler.sizeOfEventCache()).isEqualTo(0); - assertThat( logger.isDebugEnabledCalled ) - .isTrue(); + assertThat(logger.isDebugEnabledCalled).isTrue(); } @Test - public void shouldBePossibleToKill() - { - NotifiableTestStream notifiableTestStream = mock( NotifiableTestStream.class ); + public void shouldBePossibleToKill() { + NotifiableTestStream notifiableTestStream = mock(NotifiableTestStream.class); - ForkClient client = new ForkClient( null, notifiableTestStream, 0 ); + ForkClient client = new ForkClient(null, notifiableTestStream, 0); client.kill(); - verify( notifiableTestStream, times( 1 ) ) - .shutdown( eq( Shutdown.KILL ) ); + verify(notifiableTestStream, times(1)).shutdown(eq(Shutdown.KILL)); } @Test - public void shouldAcquireNextTest() - { - String cwd = System.getProperty( "user.dir" ); - File target = new File( cwd, "target" ); - DefaultReporterFactory factory = mock( DefaultReporterFactory.class ); - when( factory.getReportsDirectory() ) - .thenReturn( new File( target, "surefire-reports" ) ); - NotifiableTestStream notifiableTestStream = mock( NotifiableTestStream.class ); - ForkClient client = new ForkClient( factory, notifiableTestStream, 0 ); - client.handleEvent( new ControlNextTestEvent() ); - verify( notifiableTestStream, times( 1 ) ) - .provideNewTest(); - verifyNoMoreInteractions( notifiableTestStream ); - verifyZeroInteractions( factory ); - assertThat( client.isSaidGoodBye() ) - .isFalse(); - assertThat( client.getErrorInFork() ) - .isNull(); - assertThat( client.isErrorInFork() ) - .isFalse(); - assertThat( client.hadTimeout() ) - .isFalse(); - assertThat( client.hasTestsInProgress() ) - .isFalse(); - assertThat( client.testsInProgress() ) - .isEmpty(); - assertThat( client.getTestVmSystemProperties() ) - .isEmpty(); + public void shouldAcquireNextTest() { + String cwd = System.getProperty("user.dir"); + File target = new File(cwd, "target"); + DefaultReporterFactory factory = mock(DefaultReporterFactory.class); + when(factory.getReportsDirectory()).thenReturn(new File(target, "surefire-reports")); + NotifiableTestStream notifiableTestStream = mock(NotifiableTestStream.class); + ForkClient client = new ForkClient(factory, notifiableTestStream, 0); + client.handleEvent(new ControlNextTestEvent()); + verify(notifiableTestStream, times(1)).provideNewTest(); + verifyNoMoreInteractions(notifiableTestStream); + verifyZeroInteractions(factory); + assertThat(client.isSaidGoodBye()).isFalse(); + assertThat(client.getErrorInFork()).isNull(); + assertThat(client.isErrorInFork()).isFalse(); + assertThat(client.hadTimeout()).isFalse(); + assertThat(client.hasTestsInProgress()).isFalse(); + assertThat(client.testsInProgress()).isEmpty(); + assertThat(client.getTestVmSystemProperties()).isEmpty(); } @Test - public void shouldNotifyWithBye() - { - String cwd = System.getProperty( "user.dir" ); - File target = new File( cwd, "target" ); - DefaultReporterFactory factory = mock( DefaultReporterFactory.class ); - when( factory.getReportsDirectory() ) - .thenReturn( new File( target, "surefire-reports" ) ); - NotifiableTestStream notifiableTestStream = mock( NotifiableTestStream.class ); - - ForkClient client = new ForkClient( factory, notifiableTestStream, 0 ); - client.handleEvent( new ControlByeEvent() ); + public void shouldNotifyWithBye() { + String cwd = System.getProperty("user.dir"); + File target = new File(cwd, "target"); + DefaultReporterFactory factory = mock(DefaultReporterFactory.class); + when(factory.getReportsDirectory()).thenReturn(new File(target, "surefire-reports")); + NotifiableTestStream notifiableTestStream = mock(NotifiableTestStream.class); + + ForkClient client = new ForkClient(factory, notifiableTestStream, 0); + client.handleEvent(new ControlByeEvent()); client.kill(); - verify( notifiableTestStream, times( 1 ) ) - .acknowledgeByeEventReceived(); - verify( notifiableTestStream, never() ) - .shutdown( any( Shutdown.class ) ); - verifyNoMoreInteractions( notifiableTestStream ); - verifyZeroInteractions( factory ); - assertThat( client.isSaidGoodBye() ) - .isTrue(); - assertThat( client.getErrorInFork() ) - .isNull(); - assertThat( client.isErrorInFork() ) - .isFalse(); - assertThat( client.hadTimeout() ) - .isFalse(); - assertThat( client.hasTestsInProgress() ) - .isFalse(); - assertThat( client.testsInProgress() ) - .isEmpty(); - assertThat( client.getTestVmSystemProperties() ) - .isEmpty(); + verify(notifiableTestStream, times(1)).acknowledgeByeEventReceived(); + verify(notifiableTestStream, never()).shutdown(any(Shutdown.class)); + verifyNoMoreInteractions(notifiableTestStream); + verifyZeroInteractions(factory); + assertThat(client.isSaidGoodBye()).isTrue(); + assertThat(client.getErrorInFork()).isNull(); + assertThat(client.isErrorInFork()).isFalse(); + assertThat(client.hadTimeout()).isFalse(); + assertThat(client.hasTestsInProgress()).isFalse(); + assertThat(client.testsInProgress()).isEmpty(); + assertThat(client.getTestVmSystemProperties()).isEmpty(); } @Test - public void shouldStopOnNextTest() - { - String cwd = System.getProperty( "user.dir" ); - File target = new File( cwd, "target" ); - DefaultReporterFactory factory = mock( DefaultReporterFactory.class ); - when( factory.getReportsDirectory() ) - .thenReturn( new File( target, "surefire-reports" ) ); - NotifiableTestStream notifiableTestStream = mock( NotifiableTestStream.class ); + public void shouldStopOnNextTest() { + String cwd = System.getProperty("user.dir"); + File target = new File(cwd, "target"); + DefaultReporterFactory factory = mock(DefaultReporterFactory.class); + when(factory.getReportsDirectory()).thenReturn(new File(target, "surefire-reports")); + NotifiableTestStream notifiableTestStream = mock(NotifiableTestStream.class); final boolean[] verified = {false}; - ForkClient client = new ForkClient( factory, notifiableTestStream, 0 ); - client.setStopOnNextTestListener( () -> verified[0] = true ); - client.handleEvent( new ControlStopOnNextTestEvent() ); - verifyZeroInteractions( notifiableTestStream ); - verifyZeroInteractions( factory ); - assertThat( verified[0] ) - .isTrue(); - assertThat( client.isSaidGoodBye() ) - .isFalse(); - assertThat( client.getErrorInFork() ) - .isNull(); - assertThat( client.isErrorInFork() ) - .isFalse(); - assertThat( client.hadTimeout() ) - .isFalse(); - assertThat( client.hasTestsInProgress() ) - .isFalse(); - assertThat( client.testsInProgress() ) - .isEmpty(); - assertThat( client.getTestVmSystemProperties() ) - .isEmpty(); + ForkClient client = new ForkClient(factory, notifiableTestStream, 0); + client.setStopOnNextTestListener(() -> verified[0] = true); + client.handleEvent(new ControlStopOnNextTestEvent()); + verifyZeroInteractions(notifiableTestStream); + verifyZeroInteractions(factory); + assertThat(verified[0]).isTrue(); + assertThat(client.isSaidGoodBye()).isFalse(); + assertThat(client.getErrorInFork()).isNull(); + assertThat(client.isErrorInFork()).isFalse(); + assertThat(client.hadTimeout()).isFalse(); + assertThat(client.hasTestsInProgress()).isFalse(); + assertThat(client.testsInProgress()).isEmpty(); + assertThat(client.getTestVmSystemProperties()).isEmpty(); } @Test - public void shouldReceiveStdOut() - { - String cwd = System.getProperty( "user.dir" ); - File target = new File( cwd, "target" ); - DefaultReporterFactory factory = mock( DefaultReporterFactory.class ); - when( factory.getReportsDirectory() ) - .thenReturn( new File( target, "surefire-reports" ) ); + public void shouldReceiveStdOut() { + String cwd = System.getProperty("user.dir"); + File target = new File(cwd, "target"); + DefaultReporterFactory factory = mock(DefaultReporterFactory.class); + when(factory.getReportsDirectory()).thenReturn(new File(target, "surefire-reports")); MockReporter receiver = new MockReporter(); - when( factory.createTestReportListener() ) - .thenReturn( receiver ); - NotifiableTestStream notifiableTestStream = mock( NotifiableTestStream.class ); - ForkClient client = new ForkClient( factory, notifiableTestStream, 0 ); - client.handleEvent( new StandardStreamOutEvent( NORMAL_RUN, 1L, "msg" ) ); - verifyZeroInteractions( notifiableTestStream ); - verify( factory, times( 1 ) ) - .createTestReportListener(); - verifyNoMoreInteractions( factory ); - assertThat( client.getReporter() ) - .isNotNull(); - assertThat( receiver.getEvents() ) - .hasSize( 1 ) - .contains( STDOUT ); - assertThat( receiver.getData() ) - .hasSize( 1 ) - .contains( "msg" ); - assertThat( client.isSaidGoodBye() ) - .isFalse(); - assertThat( client.getErrorInFork() ) - .isNull(); - assertThat( client.isErrorInFork() ) - .isFalse(); - assertThat( client.hadTimeout() ) - .isFalse(); - assertThat( client.hasTestsInProgress() ) - .isFalse(); - assertThat( client.testsInProgress() ) - .isEmpty(); - assertThat( client.getTestVmSystemProperties() ) - .isEmpty(); + when(factory.createTestReportListener()).thenReturn(receiver); + NotifiableTestStream notifiableTestStream = mock(NotifiableTestStream.class); + ForkClient client = new ForkClient(factory, notifiableTestStream, 0); + client.handleEvent(new StandardStreamOutEvent(NORMAL_RUN, 1L, "msg")); + verifyZeroInteractions(notifiableTestStream); + verify(factory, times(1)).createTestReportListener(); + verifyNoMoreInteractions(factory); + assertThat(client.getReporter()).isNotNull(); + assertThat(receiver.getEvents()).hasSize(1).contains(STDOUT); + assertThat(receiver.getData()).hasSize(1).contains("msg"); + assertThat(client.isSaidGoodBye()).isFalse(); + assertThat(client.getErrorInFork()).isNull(); + assertThat(client.isErrorInFork()).isFalse(); + assertThat(client.hadTimeout()).isFalse(); + assertThat(client.hasTestsInProgress()).isFalse(); + assertThat(client.testsInProgress()).isEmpty(); + assertThat(client.getTestVmSystemProperties()).isEmpty(); } @Test - public void shouldReceiveStdOutNewLine() - { - String cwd = System.getProperty( "user.dir" ); - File target = new File( cwd, "target" ); - DefaultReporterFactory factory = mock( DefaultReporterFactory.class ); - when( factory.getReportsDirectory() ) - .thenReturn( new File( target, "surefire-reports" ) ); + public void shouldReceiveStdOutNewLine() { + String cwd = System.getProperty("user.dir"); + File target = new File(cwd, "target"); + DefaultReporterFactory factory = mock(DefaultReporterFactory.class); + when(factory.getReportsDirectory()).thenReturn(new File(target, "surefire-reports")); MockReporter receiver = new MockReporter(); - when( factory.createTestReportListener() ) - .thenReturn( receiver ); - NotifiableTestStream notifiableTestStream = mock( NotifiableTestStream.class ); - ForkClient client = new ForkClient( factory, notifiableTestStream, 0 ); - client.handleEvent( new StandardStreamOutWithNewLineEvent( NORMAL_RUN, 1L, "msg" ) ); - verifyZeroInteractions( notifiableTestStream ); - verify( factory, times( 1 ) ) - .createTestReportListener(); - verifyNoMoreInteractions( factory ); - assertThat( client.getReporter() ) - .isNotNull(); - assertThat( receiver.getEvents() ) - .hasSize( 1 ) - .contains( STDOUT ); - assertThat( receiver.getData() ) - .hasSize( 1 ) - .contains( "msg\n" ); - assertThat( client.isSaidGoodBye() ) - .isFalse(); - assertThat( client.getErrorInFork() ) - .isNull(); - assertThat( client.isErrorInFork() ) - .isFalse(); - assertThat( client.hadTimeout() ) - .isFalse(); - assertThat( client.hasTestsInProgress() ) - .isFalse(); - assertThat( client.testsInProgress() ) - .isEmpty(); - assertThat( client.getTestVmSystemProperties() ) - .isEmpty(); + when(factory.createTestReportListener()).thenReturn(receiver); + NotifiableTestStream notifiableTestStream = mock(NotifiableTestStream.class); + ForkClient client = new ForkClient(factory, notifiableTestStream, 0); + client.handleEvent(new StandardStreamOutWithNewLineEvent(NORMAL_RUN, 1L, "msg")); + verifyZeroInteractions(notifiableTestStream); + verify(factory, times(1)).createTestReportListener(); + verifyNoMoreInteractions(factory); + assertThat(client.getReporter()).isNotNull(); + assertThat(receiver.getEvents()).hasSize(1).contains(STDOUT); + assertThat(receiver.getData()).hasSize(1).contains("msg\n"); + assertThat(client.isSaidGoodBye()).isFalse(); + assertThat(client.getErrorInFork()).isNull(); + assertThat(client.isErrorInFork()).isFalse(); + assertThat(client.hadTimeout()).isFalse(); + assertThat(client.hasTestsInProgress()).isFalse(); + assertThat(client.testsInProgress()).isEmpty(); + assertThat(client.getTestVmSystemProperties()).isEmpty(); } @Test - public void shouldReceiveStdErr() - { - String cwd = System.getProperty( "user.dir" ); - File target = new File( cwd, "target" ); - DefaultReporterFactory factory = mock( DefaultReporterFactory.class ); - when( factory.getReportsDirectory() ) - .thenReturn( new File( target, "surefire-reports" ) ); + public void shouldReceiveStdErr() { + String cwd = System.getProperty("user.dir"); + File target = new File(cwd, "target"); + DefaultReporterFactory factory = mock(DefaultReporterFactory.class); + when(factory.getReportsDirectory()).thenReturn(new File(target, "surefire-reports")); MockReporter receiver = new MockReporter(); - when( factory.createTestReportListener() ) - .thenReturn( receiver ); - NotifiableTestStream notifiableTestStream = mock( NotifiableTestStream.class ); - ForkClient client = new ForkClient( factory, notifiableTestStream, 0 ); - client.handleEvent( new StandardStreamErrEvent( NORMAL_RUN, 1L, "msg" ) ); - verifyZeroInteractions( notifiableTestStream ); - verify( factory, times( 1 ) ) - .createTestReportListener(); - verifyNoMoreInteractions( factory ); - assertThat( client.getReporter() ) - .isNotNull(); - assertThat( receiver.getEvents() ) - .hasSize( 1 ) - .contains( STDERR ); - assertThat( receiver.getData() ) - .hasSize( 1 ) - .contains( "msg" ); - assertThat( client.isSaidGoodBye() ) - .isFalse(); - assertThat( client.getErrorInFork() ) - .isNull(); - assertThat( client.isErrorInFork() ) - .isFalse(); - assertThat( client.hadTimeout() ) - .isFalse(); - assertThat( client.hasTestsInProgress() ) - .isFalse(); - assertThat( client.testsInProgress() ) - .isEmpty(); - assertThat( client.getTestVmSystemProperties() ) - .isEmpty(); + when(factory.createTestReportListener()).thenReturn(receiver); + NotifiableTestStream notifiableTestStream = mock(NotifiableTestStream.class); + ForkClient client = new ForkClient(factory, notifiableTestStream, 0); + client.handleEvent(new StandardStreamErrEvent(NORMAL_RUN, 1L, "msg")); + verifyZeroInteractions(notifiableTestStream); + verify(factory, times(1)).createTestReportListener(); + verifyNoMoreInteractions(factory); + assertThat(client.getReporter()).isNotNull(); + assertThat(receiver.getEvents()).hasSize(1).contains(STDERR); + assertThat(receiver.getData()).hasSize(1).contains("msg"); + assertThat(client.isSaidGoodBye()).isFalse(); + assertThat(client.getErrorInFork()).isNull(); + assertThat(client.isErrorInFork()).isFalse(); + assertThat(client.hadTimeout()).isFalse(); + assertThat(client.hasTestsInProgress()).isFalse(); + assertThat(client.testsInProgress()).isEmpty(); + assertThat(client.getTestVmSystemProperties()).isEmpty(); } @Test - public void shouldReceiveStdErrNewLine() - { - String cwd = System.getProperty( "user.dir" ); - File target = new File( cwd, "target" ); - DefaultReporterFactory factory = mock( DefaultReporterFactory.class ); - when( factory.getReportsDirectory() ) - .thenReturn( new File( target, "surefire-reports" ) ); + public void shouldReceiveStdErrNewLine() { + String cwd = System.getProperty("user.dir"); + File target = new File(cwd, "target"); + DefaultReporterFactory factory = mock(DefaultReporterFactory.class); + when(factory.getReportsDirectory()).thenReturn(new File(target, "surefire-reports")); MockReporter receiver = new MockReporter(); - when( factory.createTestReportListener() ) - .thenReturn( receiver ); - NotifiableTestStream notifiableTestStream = mock( NotifiableTestStream.class ); - ForkClient client = new ForkClient( factory, notifiableTestStream, 0 ); - client.handleEvent( new StandardStreamErrWithNewLineEvent( NORMAL_RUN, 1L, "msg" ) ); - verifyZeroInteractions( notifiableTestStream ); - verify( factory, times( 1 ) ) - .createTestReportListener(); - verifyNoMoreInteractions( factory ); - assertThat( client.getReporter() ) - .isNotNull(); - assertThat( receiver.getEvents() ) - .hasSize( 1 ) - .contains( STDERR ); - assertThat( receiver.getData() ) - .hasSize( 1 ) - .contains( "msg\n" ); - assertThat( client.isSaidGoodBye() ) - .isFalse(); - assertThat( client.getErrorInFork() ) - .isNull(); - assertThat( client.isErrorInFork() ) - .isFalse(); - assertThat( client.hadTimeout() ) - .isFalse(); - assertThat( client.hasTestsInProgress() ) - .isFalse(); - assertThat( client.testsInProgress() ) - .isEmpty(); - assertThat( client.getTestVmSystemProperties() ) - .isEmpty(); + when(factory.createTestReportListener()).thenReturn(receiver); + NotifiableTestStream notifiableTestStream = mock(NotifiableTestStream.class); + ForkClient client = new ForkClient(factory, notifiableTestStream, 0); + client.handleEvent(new StandardStreamErrWithNewLineEvent(NORMAL_RUN, 1L, "msg")); + verifyZeroInteractions(notifiableTestStream); + verify(factory, times(1)).createTestReportListener(); + verifyNoMoreInteractions(factory); + assertThat(client.getReporter()).isNotNull(); + assertThat(receiver.getEvents()).hasSize(1).contains(STDERR); + assertThat(receiver.getData()).hasSize(1).contains("msg\n"); + assertThat(client.isSaidGoodBye()).isFalse(); + assertThat(client.getErrorInFork()).isNull(); + assertThat(client.isErrorInFork()).isFalse(); + assertThat(client.hadTimeout()).isFalse(); + assertThat(client.hasTestsInProgress()).isFalse(); + assertThat(client.testsInProgress()).isEmpty(); + assertThat(client.getTestVmSystemProperties()).isEmpty(); } @Test - public void shouldLogConsoleError() - { - DefaultReporterFactory factory = mock( DefaultReporterFactory.class ); + public void shouldLogConsoleError() { + DefaultReporterFactory factory = mock(DefaultReporterFactory.class); MockReporter receiver = new MockReporter(); - when( factory.createTestReportListener() ) - .thenReturn( receiver ); - NotifiableTestStream notifiableTestStream = mock( NotifiableTestStream.class ); - ForkClient client = new ForkClient( factory, notifiableTestStream, 0 ); + when(factory.createTestReportListener()).thenReturn(receiver); + NotifiableTestStream notifiableTestStream = mock(NotifiableTestStream.class); + ForkClient client = new ForkClient(factory, notifiableTestStream, 0); StackTraceWriter stackTrace = - new DeserializedStacktraceWriter( "Listening for transport dt_socket at address: 5005", null, null ); - Event event = new ConsoleErrorEvent( stackTrace ); - client.handleEvent( event ); - verifyZeroInteractions( notifiableTestStream ); - verify( factory, times( 1 ) ) - .createTestReportListener(); - verify( factory, times( 1 ) ) - .getReportsDirectory(); - verifyNoMoreInteractions( factory ); - assertThat( client.getReporter() ) - .isNotNull(); - assertThat( receiver.getEvents() ) - .isNotEmpty(); - assertThat( receiver.getEvents() ) - .contains( CONSOLE_ERR ); - assertThat( receiver.getData() ) - .isNotEmpty(); - assertThat( receiver.getData() ) - .contains( "Listening for transport dt_socket at address: 5005" ); - assertThat( client.isSaidGoodBye() ) - .isFalse(); - assertThat( client.isErrorInFork() ) - .isFalse(); - assertThat( client.getErrorInFork() ) - .isNull(); - assertThat( client.hadTimeout() ) - .isFalse(); - assertThat( client.hasTestsInProgress() ) - .isFalse(); - assertThat( client.testsInProgress() ) - .isEmpty(); - assertThat( client.getTestVmSystemProperties() ) - .isEmpty(); + new DeserializedStacktraceWriter("Listening for transport dt_socket at address: 5005", null, null); + Event event = new ConsoleErrorEvent(stackTrace); + client.handleEvent(event); + verifyZeroInteractions(notifiableTestStream); + verify(factory, times(1)).createTestReportListener(); + verify(factory, times(1)).getReportsDirectory(); + verifyNoMoreInteractions(factory); + assertThat(client.getReporter()).isNotNull(); + assertThat(receiver.getEvents()).isNotEmpty(); + assertThat(receiver.getEvents()).contains(CONSOLE_ERR); + assertThat(receiver.getData()).isNotEmpty(); + assertThat(receiver.getData()).contains("Listening for transport dt_socket at address: 5005"); + assertThat(client.isSaidGoodBye()).isFalse(); + assertThat(client.isErrorInFork()).isFalse(); + assertThat(client.getErrorInFork()).isNull(); + assertThat(client.hadTimeout()).isFalse(); + assertThat(client.hasTestsInProgress()).isFalse(); + assertThat(client.testsInProgress()).isEmpty(); + assertThat(client.getTestVmSystemProperties()).isEmpty(); } @Test - public void shouldLogConsoleErrorWithStackTrace() throws Exception - { + public void shouldLogConsoleErrorWithStackTrace() throws Exception { String nativeStream = ":maven-surefire-event:\u0011:console-error-log:\u0005:UTF-8" - + ":\u0000\u0000\u0000\u0032:Listening for transport dt_socket at address: 5005" - + ":\u0000\u0000\u0000\u0002:s1:\u0000\u0000\u0000\u0002:s2:"; + + ":\u0000\u0000\u0000\u0032:Listening for transport dt_socket at address: 5005" + + ":\u0000\u0000\u0000\u0002:s1:\u0000\u0000\u0000\u0002:s2:"; EH eventHandler = new EH(); - CountdownCloseable countdown = new CountdownCloseable( mock( Closeable.class ), 1 ); - ConsoleLoggerMock logger = new ConsoleLoggerMock( false, false, false, false ); - ForkNodeArgumentsMock arguments = new ForkNodeArgumentsMock( logger, new File( "" ) ); - ReadableByteChannel channel = newChannel( new ByteArrayInputStream( nativeStream.getBytes() ) ); - try ( EventConsumerThread t = new EventConsumerThread( "t", channel, eventHandler, countdown, arguments ) ) - { + CountdownCloseable countdown = new CountdownCloseable(mock(Closeable.class), 1); + ConsoleLoggerMock logger = new ConsoleLoggerMock(false, false, false, false); + ForkNodeArgumentsMock arguments = new ForkNodeArgumentsMock(logger, new File("")); + ReadableByteChannel channel = newChannel(new ByteArrayInputStream(nativeStream.getBytes())); + try (EventConsumerThread t = new EventConsumerThread("t", channel, eventHandler, countdown, arguments)) { t.start(); Event event = eventHandler.pullEvent(); - assertThat( event.isConsoleErrorCategory() ) - .isTrue(); - assertThat( event.isConsoleCategory() ) - .isTrue(); - assertThat( event.getEventType() ) - .isEqualTo( BOOTERCODE_CONSOLE_ERROR ); + assertThat(event.isConsoleErrorCategory()).isTrue(); + assertThat(event.isConsoleCategory()).isTrue(); + assertThat(event.getEventType()).isEqualTo(BOOTERCODE_CONSOLE_ERROR); ConsoleErrorEvent consoleEvent = (ConsoleErrorEvent) event; - assertThat( consoleEvent.getStackTraceWriter() ) - .isNotNull(); - assertThat( consoleEvent.getStackTraceWriter().getThrowable().getMessage() ) - .isEqualTo( "Listening for transport dt_socket at address: 5005" ); - assertThat( consoleEvent.getStackTraceWriter().smartTrimmedStackTrace() ) - .isEqualTo( "s1" ); - assertThat( consoleEvent.getStackTraceWriter().writeTraceToString() ) - .isEqualTo( "s2" ); + assertThat(consoleEvent.getStackTraceWriter()).isNotNull(); + assertThat(consoleEvent.getStackTraceWriter().getThrowable().getMessage()) + .isEqualTo("Listening for transport dt_socket at address: 5005"); + assertThat(consoleEvent.getStackTraceWriter().smartTrimmedStackTrace()) + .isEqualTo("s1"); + assertThat(consoleEvent.getStackTraceWriter().writeTraceToString()).isEqualTo("s2"); countdown.awaitClosed(); - assertThat( logger.isCalled() ) - .isFalse(); + assertThat(logger.isCalled()).isFalse(); } - assertThat( eventHandler.sizeOfEventCache() ) - .isEqualTo( 0 ); + assertThat(eventHandler.sizeOfEventCache()).isEqualTo(0); } @Test - public void shouldLogConsoleWarning() - { - String cwd = System.getProperty( "user.dir" ); - File target = new File( cwd, "target" ); - DefaultReporterFactory factory = mock( DefaultReporterFactory.class ); - when( factory.getReportsDirectory() ) - .thenReturn( new File( target, "surefire-reports" ) ); + public void shouldLogConsoleWarning() { + String cwd = System.getProperty("user.dir"); + File target = new File(cwd, "target"); + DefaultReporterFactory factory = mock(DefaultReporterFactory.class); + when(factory.getReportsDirectory()).thenReturn(new File(target, "surefire-reports")); MockReporter receiver = new MockReporter(); - when( factory.createTestReportListener() ) - .thenReturn( receiver ); - NotifiableTestStream notifiableTestStream = mock( NotifiableTestStream.class ); - ForkClient client = new ForkClient( factory, notifiableTestStream, 0 ); - client.handleEvent( new ConsoleWarningEvent( "s1" ) ); - verifyZeroInteractions( notifiableTestStream ); - verify( factory, times( 1 ) ) - .createTestReportListener(); - verifyNoMoreInteractions( factory ); - assertThat( client.getReporter() ) - .isNotNull(); - assertThat( receiver.getEvents() ) - .hasSize( 1 ) - .contains( CONSOLE_WARN ); - assertThat( receiver.getData() ) - .hasSize( 1 ) - .contains( "s1" ); - assertThat( client.isSaidGoodBye() ) - .isFalse(); - assertThat( client.isErrorInFork() ) - .isFalse(); - assertThat( client.getErrorInFork() ) - .isNull(); - assertThat( client.hadTimeout() ) - .isFalse(); - assertThat( client.hasTestsInProgress() ) - .isFalse(); - assertThat( client.testsInProgress() ) - .isEmpty(); - assertThat( client.getTestVmSystemProperties() ) - .isEmpty(); + when(factory.createTestReportListener()).thenReturn(receiver); + NotifiableTestStream notifiableTestStream = mock(NotifiableTestStream.class); + ForkClient client = new ForkClient(factory, notifiableTestStream, 0); + client.handleEvent(new ConsoleWarningEvent("s1")); + verifyZeroInteractions(notifiableTestStream); + verify(factory, times(1)).createTestReportListener(); + verifyNoMoreInteractions(factory); + assertThat(client.getReporter()).isNotNull(); + assertThat(receiver.getEvents()).hasSize(1).contains(CONSOLE_WARN); + assertThat(receiver.getData()).hasSize(1).contains("s1"); + assertThat(client.isSaidGoodBye()).isFalse(); + assertThat(client.isErrorInFork()).isFalse(); + assertThat(client.getErrorInFork()).isNull(); + assertThat(client.hadTimeout()).isFalse(); + assertThat(client.hasTestsInProgress()).isFalse(); + assertThat(client.testsInProgress()).isEmpty(); + assertThat(client.getTestVmSystemProperties()).isEmpty(); } @Test - public void shouldLogConsoleDebug() - { - String cwd = System.getProperty( "user.dir" ); - File target = new File( cwd, "target" ); - DefaultReporterFactory factory = mock( DefaultReporterFactory.class ); - when( factory.getReportsDirectory() ) - .thenReturn( new File( target, "surefire-reports" ) ); + public void shouldLogConsoleDebug() { + String cwd = System.getProperty("user.dir"); + File target = new File(cwd, "target"); + DefaultReporterFactory factory = mock(DefaultReporterFactory.class); + when(factory.getReportsDirectory()).thenReturn(new File(target, "surefire-reports")); MockReporter receiver = new MockReporter(); - when( factory.createTestReportListener() ) - .thenReturn( receiver ); - NotifiableTestStream notifiableTestStream = mock( NotifiableTestStream.class ); - ForkClient client = new ForkClient( factory, notifiableTestStream, 0 ); - client.handleEvent( new ConsoleDebugEvent( "s1" ) ); - verifyZeroInteractions( notifiableTestStream ); - verify( factory, times( 1 ) ) - .createTestReportListener(); - verifyNoMoreInteractions( factory ); - assertThat( client.getReporter() ) - .isNotNull(); - assertThat( receiver.getEvents() ) - .hasSize( 1 ) - .contains( CONSOLE_DEBUG ); - assertThat( receiver.getData() ) - .hasSize( 1 ) - .contains( "s1" ); - assertThat( client.isSaidGoodBye() ) - .isFalse(); - assertThat( client.isErrorInFork() ) - .isFalse(); - assertThat( client.getErrorInFork() ) - .isNull(); - assertThat( client.hadTimeout() ) - .isFalse(); - assertThat( client.hasTestsInProgress() ) - .isFalse(); - assertThat( client.testsInProgress() ) - .isEmpty(); - assertThat( client.getTestVmSystemProperties() ) - .isEmpty(); + when(factory.createTestReportListener()).thenReturn(receiver); + NotifiableTestStream notifiableTestStream = mock(NotifiableTestStream.class); + ForkClient client = new ForkClient(factory, notifiableTestStream, 0); + client.handleEvent(new ConsoleDebugEvent("s1")); + verifyZeroInteractions(notifiableTestStream); + verify(factory, times(1)).createTestReportListener(); + verifyNoMoreInteractions(factory); + assertThat(client.getReporter()).isNotNull(); + assertThat(receiver.getEvents()).hasSize(1).contains(CONSOLE_DEBUG); + assertThat(receiver.getData()).hasSize(1).contains("s1"); + assertThat(client.isSaidGoodBye()).isFalse(); + assertThat(client.isErrorInFork()).isFalse(); + assertThat(client.getErrorInFork()).isNull(); + assertThat(client.hadTimeout()).isFalse(); + assertThat(client.hasTestsInProgress()).isFalse(); + assertThat(client.testsInProgress()).isEmpty(); + assertThat(client.getTestVmSystemProperties()).isEmpty(); } @Test - public void shouldLogConsoleInfo() - { - String cwd = System.getProperty( "user.dir" ); - File target = new File( cwd, "target" ); - DefaultReporterFactory factory = mock( DefaultReporterFactory.class ); - when( factory.getReportsDirectory() ) - .thenReturn( new File( target, "surefire-reports" ) ); + public void shouldLogConsoleInfo() { + String cwd = System.getProperty("user.dir"); + File target = new File(cwd, "target"); + DefaultReporterFactory factory = mock(DefaultReporterFactory.class); + when(factory.getReportsDirectory()).thenReturn(new File(target, "surefire-reports")); MockReporter receiver = new MockReporter(); - when( factory.createTestReportListener() ) - .thenReturn( receiver ); - NotifiableTestStream notifiableTestStream = mock( NotifiableTestStream.class ); - ForkClient client = new ForkClient( factory, notifiableTestStream, 0 ); - client.handleEvent( new ConsoleInfoEvent( "s1" ) ); - verifyZeroInteractions( notifiableTestStream ); - verify( factory, times( 1 ) ) - .createTestReportListener(); - verifyNoMoreInteractions( factory ); - assertThat( client.getReporter() ) - .isNotNull(); - assertThat( receiver.getEvents() ) - .hasSize( 1 ) - .contains( CONSOLE_INFO ); - assertThat( receiver.getData() ) - .hasSize( 1 ) - .contains( "s1" ); - assertThat( client.isSaidGoodBye() ) - .isFalse(); - assertThat( client.isErrorInFork() ) - .isFalse(); - assertThat( client.getErrorInFork() ) - .isNull(); - assertThat( client.hadTimeout() ) - .isFalse(); - assertThat( client.hasTestsInProgress() ) - .isFalse(); - assertThat( client.testsInProgress() ) - .isEmpty(); - assertThat( client.getTestVmSystemProperties() ) - .isEmpty(); + when(factory.createTestReportListener()).thenReturn(receiver); + NotifiableTestStream notifiableTestStream = mock(NotifiableTestStream.class); + ForkClient client = new ForkClient(factory, notifiableTestStream, 0); + client.handleEvent(new ConsoleInfoEvent("s1")); + verifyZeroInteractions(notifiableTestStream); + verify(factory, times(1)).createTestReportListener(); + verifyNoMoreInteractions(factory); + assertThat(client.getReporter()).isNotNull(); + assertThat(receiver.getEvents()).hasSize(1).contains(CONSOLE_INFO); + assertThat(receiver.getData()).hasSize(1).contains("s1"); + assertThat(client.isSaidGoodBye()).isFalse(); + assertThat(client.isErrorInFork()).isFalse(); + assertThat(client.getErrorInFork()).isNull(); + assertThat(client.hadTimeout()).isFalse(); + assertThat(client.hasTestsInProgress()).isFalse(); + assertThat(client.testsInProgress()).isEmpty(); + assertThat(client.getTestVmSystemProperties()).isEmpty(); } @Test - public void shouldSendSystemProperty() - { - String cwd = System.getProperty( "user.dir" ); - File target = new File( cwd, "target" ); - DefaultReporterFactory factory = mock( DefaultReporterFactory.class ); - when( factory.getReportsDirectory() ) - .thenReturn( new File( target, "surefire-reports" ) ); + public void shouldSendSystemProperty() { + String cwd = System.getProperty("user.dir"); + File target = new File(cwd, "target"); + DefaultReporterFactory factory = mock(DefaultReporterFactory.class); + when(factory.getReportsDirectory()).thenReturn(new File(target, "surefire-reports")); MockReporter receiver = new MockReporter(); - when( factory.createTestReportListener() ) - .thenReturn( receiver ); - NotifiableTestStream notifiableTestStream = mock( NotifiableTestStream.class ); - ForkClient client = new ForkClient( factory, notifiableTestStream, 0 ); - client.handleEvent( new SystemPropertyEvent( NORMAL_RUN, 1L, "k1", "v1" ) ); - verifyZeroInteractions( notifiableTestStream ); - verifyZeroInteractions( factory ); - assertThat( client.getReporter() ) - .isNotNull(); - assertThat( receiver.getEvents() ) - .isEmpty(); - assertThat( receiver.getData() ) - .isEmpty(); - assertThat( client.isSaidGoodBye() ) - .isFalse(); - assertThat( client.isErrorInFork() ) - .isFalse(); - assertThat( client.getErrorInFork() ) - .isNull(); - assertThat( client.hadTimeout() ) - .isFalse(); - assertThat( client.hasTestsInProgress() ) - .isFalse(); - assertThat( client.testsInProgress() ) - .isEmpty(); - assertThat( client.getTestVmSystemProperties() ) - .hasSize( 1 ); - assertThat( client.getTestVmSystemProperties() ) - .containsEntry( "k1", "v1" ); + when(factory.createTestReportListener()).thenReturn(receiver); + NotifiableTestStream notifiableTestStream = mock(NotifiableTestStream.class); + ForkClient client = new ForkClient(factory, notifiableTestStream, 0); + client.handleEvent(new SystemPropertyEvent(NORMAL_RUN, 1L, "k1", "v1")); + verifyZeroInteractions(notifiableTestStream); + verifyZeroInteractions(factory); + assertThat(client.getReporter()).isNotNull(); + assertThat(receiver.getEvents()).isEmpty(); + assertThat(receiver.getData()).isEmpty(); + assertThat(client.isSaidGoodBye()).isFalse(); + assertThat(client.isErrorInFork()).isFalse(); + assertThat(client.getErrorInFork()).isNull(); + assertThat(client.hadTimeout()).isFalse(); + assertThat(client.hasTestsInProgress()).isFalse(); + assertThat(client.testsInProgress()).isEmpty(); + assertThat(client.getTestVmSystemProperties()).hasSize(1); + assertThat(client.getTestVmSystemProperties()).containsEntry("k1", "v1"); } @Test - public void shouldSendTestsetStartingKilled() - { - String cwd = System.getProperty( "user.dir" ); - File target = new File( cwd, "target" ); - DefaultReporterFactory factory = mock( DefaultReporterFactory.class ); - when( factory.getReportsDirectory() ) - .thenReturn( new File( target, "surefire-reports" ) ); + public void shouldSendTestsetStartingKilled() { + String cwd = System.getProperty("user.dir"); + File target = new File(cwd, "target"); + DefaultReporterFactory factory = mock(DefaultReporterFactory.class); + when(factory.getReportsDirectory()).thenReturn(new File(target, "surefire-reports")); MockReporter receiver = new MockReporter(); - when( factory.createTestReportListener() ) - .thenReturn( receiver ); - NotifiableTestStream notifiableTestStream = mock( NotifiableTestStream.class ); + when(factory.createTestReportListener()).thenReturn(receiver); + NotifiableTestStream notifiableTestStream = mock(NotifiableTestStream.class); final String exceptionMessage = "msg"; final String smartStackTrace = "MyTest:86 >> Error"; final String stackTrace = "trace line 1\ntrace line 2"; final String trimmedStackTrace = "trace line 1"; - SafeThrowable safeThrowable = new SafeThrowable( new Exception( exceptionMessage ) ); - StackTraceWriter stackTraceWriter = mock( StackTraceWriter.class ); - when( stackTraceWriter.getThrowable() ).thenReturn( safeThrowable ); - when( stackTraceWriter.smartTrimmedStackTrace() ).thenReturn( smartStackTrace ); - when( stackTraceWriter.writeTrimmedTraceToString() ).thenReturn( trimmedStackTrace ); - when( stackTraceWriter.writeTraceToString() ).thenReturn( stackTrace ); - - TestSetReportEntry reportEntry = mock( TestSetReportEntry.class ); - when( reportEntry.getRunMode() ).thenReturn( NORMAL_RUN ); - when( reportEntry.getTestRunId() ).thenReturn( 1L ); - when( reportEntry.getElapsed() ).thenReturn( ELAPSED_TIME ); - when( reportEntry.getGroup() ).thenReturn( "this group" ); - when( reportEntry.getMessage() ).thenReturn( "some test" ); - when( reportEntry.getName() ).thenReturn( "my test" ); - when( reportEntry.getNameWithGroup() ).thenReturn( "name with group" ); - when( reportEntry.getSourceName() ).thenReturn( "pkg.MyTest" ); - when( reportEntry.getStackTraceWriter() ).thenReturn( stackTraceWriter ); - - ForkClient client = new ForkClient( factory, notifiableTestStream, 0 ); - client.handleEvent( new TestsetStartingEvent( reportEntry ) ); - - client.tryToTimeout( System.currentTimeMillis() + 1000L, 1 ); - - verify( notifiableTestStream ) - .shutdown( Shutdown.KILL ); - verifyNoMoreInteractions( notifiableTestStream ); - verify( factory ).createTestReportListener(); - verifyNoMoreInteractions( factory ); - assertThat( client.getReporter() ) - .isNotNull(); - assertThat( receiver.getEvents() ) - .hasSize( 1 ); - assertThat( receiver.getEvents() ) - .contains( SET_STARTING ); - assertThat( receiver.getData() ) - .hasSize( 1 ); - assertThat( ( (ReportEntry) receiver.getData().get( 0 ) ).getSourceName() ) - .isEqualTo( "pkg.MyTest" ); - assertThat( ( (ReportEntry) receiver.getData().get( 0 ) ).getSourceText() ) - .isNull(); - assertThat( ( (ReportEntry) receiver.getData().get( 0 ) ).getName() ) - .isEqualTo( "my test" ); - assertThat( ( (ReportEntry) receiver.getData().get( 0 ) ).getNameText() ) - .isNull(); - assertThat( ( (ReportEntry) receiver.getData().get( 0 ) ).getElapsed() ) - .isEqualTo( ELAPSED_TIME ); - assertThat( ( (ReportEntry) receiver.getData().get( 0 ) ).getMessage() ) - .isEqualTo( "some test" ); - assertThat( ( (ReportEntry) receiver.getData().get( 0 ) ).getGroup() ) - .isEqualTo( "this group" ); - assertThat( ( (ReportEntry) receiver.getData().get( 0 ) ).getStackTraceWriter() ) + SafeThrowable safeThrowable = new SafeThrowable(new Exception(exceptionMessage)); + StackTraceWriter stackTraceWriter = mock(StackTraceWriter.class); + when(stackTraceWriter.getThrowable()).thenReturn(safeThrowable); + when(stackTraceWriter.smartTrimmedStackTrace()).thenReturn(smartStackTrace); + when(stackTraceWriter.writeTrimmedTraceToString()).thenReturn(trimmedStackTrace); + when(stackTraceWriter.writeTraceToString()).thenReturn(stackTrace); + + TestSetReportEntry reportEntry = mock(TestSetReportEntry.class); + when(reportEntry.getRunMode()).thenReturn(NORMAL_RUN); + when(reportEntry.getTestRunId()).thenReturn(1L); + when(reportEntry.getElapsed()).thenReturn(ELAPSED_TIME); + when(reportEntry.getGroup()).thenReturn("this group"); + when(reportEntry.getMessage()).thenReturn("some test"); + when(reportEntry.getName()).thenReturn("my test"); + when(reportEntry.getNameWithGroup()).thenReturn("name with group"); + when(reportEntry.getSourceName()).thenReturn("pkg.MyTest"); + when(reportEntry.getStackTraceWriter()).thenReturn(stackTraceWriter); + + ForkClient client = new ForkClient(factory, notifiableTestStream, 0); + client.handleEvent(new TestsetStartingEvent(reportEntry)); + + client.tryToTimeout(System.currentTimeMillis() + 1000L, 1); + + verify(notifiableTestStream).shutdown(Shutdown.KILL); + verifyNoMoreInteractions(notifiableTestStream); + verify(factory).createTestReportListener(); + verifyNoMoreInteractions(factory); + assertThat(client.getReporter()).isNotNull(); + assertThat(receiver.getEvents()).hasSize(1); + assertThat(receiver.getEvents()).contains(SET_STARTING); + assertThat(receiver.getData()).hasSize(1); + assertThat(((ReportEntry) receiver.getData().get(0)).getSourceName()).isEqualTo("pkg.MyTest"); + assertThat(((ReportEntry) receiver.getData().get(0)).getSourceText()).isNull(); + assertThat(((ReportEntry) receiver.getData().get(0)).getName()).isEqualTo("my test"); + assertThat(((ReportEntry) receiver.getData().get(0)).getNameText()).isNull(); + assertThat(((ReportEntry) receiver.getData().get(0)).getElapsed()).isEqualTo(ELAPSED_TIME); + assertThat(((ReportEntry) receiver.getData().get(0)).getMessage()).isEqualTo("some test"); + assertThat(((ReportEntry) receiver.getData().get(0)).getGroup()).isEqualTo("this group"); + assertThat(((ReportEntry) receiver.getData().get(0)).getStackTraceWriter()) .isNotNull(); - assertThat( ( (ReportEntry) receiver.getData().get( 0 ) ) - .getStackTraceWriter().getThrowable().getLocalizedMessage() ) - .isEqualTo( exceptionMessage ); - assertThat( ( (ReportEntry) receiver.getData().get( 0 ) ).getStackTraceWriter().smartTrimmedStackTrace() ) - .isEqualTo( smartStackTrace ); - assertThat( ( (ReportEntry) receiver.getData().get( 0 ) ).getStackTraceWriter().writeTraceToString() ) - .isEqualTo( stackTrace ); - assertThat( ( (ReportEntry) receiver.getData().get( 0 ) ).getStackTraceWriter().writeTrimmedTraceToString() ) - .isEqualTo( trimmedStackTrace ); - assertThat( client.isSaidGoodBye() ) - .isFalse(); - assertThat( client.isErrorInFork() ) - .isFalse(); - assertThat( client.getErrorInFork() ) - .isNull(); - assertThat( client.hadTimeout() ) - .isTrue(); - assertThat( client.hasTestsInProgress() ) - .isFalse(); - assertThat( client.testsInProgress() ) - .isEmpty(); - assertThat( client.getTestVmSystemProperties() ) - .isEmpty(); - assertThat( client.getTestVmSystemProperties() ) - .isEmpty(); + assertThat(((ReportEntry) receiver.getData().get(0)) + .getStackTraceWriter() + .getThrowable() + .getLocalizedMessage()) + .isEqualTo(exceptionMessage); + assertThat(((ReportEntry) receiver.getData().get(0)) + .getStackTraceWriter() + .smartTrimmedStackTrace()) + .isEqualTo(smartStackTrace); + assertThat(((ReportEntry) receiver.getData().get(0)) + .getStackTraceWriter() + .writeTraceToString()) + .isEqualTo(stackTrace); + assertThat(((ReportEntry) receiver.getData().get(0)) + .getStackTraceWriter() + .writeTrimmedTraceToString()) + .isEqualTo(trimmedStackTrace); + assertThat(client.isSaidGoodBye()).isFalse(); + assertThat(client.isErrorInFork()).isFalse(); + assertThat(client.getErrorInFork()).isNull(); + assertThat(client.hadTimeout()).isTrue(); + assertThat(client.hasTestsInProgress()).isFalse(); + assertThat(client.testsInProgress()).isEmpty(); + assertThat(client.getTestVmSystemProperties()).isEmpty(); + assertThat(client.getTestVmSystemProperties()).isEmpty(); } @Test - public void shouldSendTestsetStarting() - { - String cwd = System.getProperty( "user.dir" ); - File target = new File( cwd, "target" ); - DefaultReporterFactory factory = mock( DefaultReporterFactory.class ); - when( factory.getReportsDirectory() ) - .thenReturn( new File( target, "surefire-reports" ) ); + public void shouldSendTestsetStarting() { + String cwd = System.getProperty("user.dir"); + File target = new File(cwd, "target"); + DefaultReporterFactory factory = mock(DefaultReporterFactory.class); + when(factory.getReportsDirectory()).thenReturn(new File(target, "surefire-reports")); MockReporter receiver = new MockReporter(); - when( factory.createTestReportListener() ) - .thenReturn( receiver ); - NotifiableTestStream notifiableTestStream = mock( NotifiableTestStream.class ); + when(factory.createTestReportListener()).thenReturn(receiver); + NotifiableTestStream notifiableTestStream = mock(NotifiableTestStream.class); final String exceptionMessage = "msg"; final String smartStackTrace = "MyTest:86 >> Error"; final String stackTrace = "trace line 1\ntrace line 2"; final String trimmedStackTrace = "trace line 1"; - SafeThrowable safeThrowable = new SafeThrowable( new Exception( exceptionMessage ) ); - StackTraceWriter stackTraceWriter = mock( StackTraceWriter.class ); - when( stackTraceWriter.getThrowable() ).thenReturn( safeThrowable ); - when( stackTraceWriter.smartTrimmedStackTrace() ).thenReturn( smartStackTrace ); - when( stackTraceWriter.writeTrimmedTraceToString() ).thenReturn( trimmedStackTrace ); - when( stackTraceWriter.writeTraceToString() ).thenReturn( stackTrace ); - - TestSetReportEntry reportEntry = mock( TestSetReportEntry.class ); - when( reportEntry.getRunMode() ).thenReturn( NORMAL_RUN ); - when( reportEntry.getTestRunId() ).thenReturn( 1L ); - when( reportEntry.getElapsed() ).thenReturn( ELAPSED_TIME ); - when( reportEntry.getGroup() ).thenReturn( "this group" ); - when( reportEntry.getMessage() ).thenReturn( "some test" ); - when( reportEntry.getName() ).thenReturn( "my test" ); - when( reportEntry.getNameText() ).thenReturn( "dn2" ); - when( reportEntry.getNameWithGroup() ).thenReturn( "name with group" ); - when( reportEntry.getSourceName() ).thenReturn( "pkg.MyTest" ); - when( reportEntry.getSourceText() ).thenReturn( "dn1" ); - when( reportEntry.getStackTraceWriter() ).thenReturn( stackTraceWriter ); - - ForkClient client = new ForkClient( factory, notifiableTestStream, 0 ); - client.handleEvent( new TestsetStartingEvent( reportEntry ) ); - client.tryToTimeout( System.currentTimeMillis(), 1 ); - - verifyZeroInteractions( notifiableTestStream ); - verify( factory ).createTestReportListener(); - verifyNoMoreInteractions( factory ); - assertThat( client.getReporter() ) - .isNotNull(); - assertThat( receiver.getEvents() ) - .hasSize( 1 ); - assertThat( receiver.getEvents() ) - .contains( SET_STARTING ); - assertThat( receiver.getData() ) - .hasSize( 1 ); - assertThat( ( (ReportEntry) receiver.getData().get( 0 ) ).getSourceName() ) - .isEqualTo( "pkg.MyTest" ); - assertThat( ( (ReportEntry) receiver.getData().get( 0 ) ).getSourceText() ) - .isEqualTo( "dn1" ); - assertThat( ( (ReportEntry) receiver.getData().get( 0 ) ).getName() ) - .isEqualTo( "my test" ); - assertThat( ( (ReportEntry) receiver.getData().get( 0 ) ).getNameText() ) - .isEqualTo( "dn2" ); - assertThat( ( (ReportEntry) receiver.getData().get( 0 ) ).getElapsed() ) - .isEqualTo( ELAPSED_TIME ); - assertThat( ( (ReportEntry) receiver.getData().get( 0 ) ).getMessage() ) - .isEqualTo( "some test" ); - assertThat( ( (ReportEntry) receiver.getData().get( 0 ) ).getGroup() ) - .isEqualTo( "this group" ); - assertThat( ( (ReportEntry) receiver.getData().get( 0 ) ).getStackTraceWriter() ) + SafeThrowable safeThrowable = new SafeThrowable(new Exception(exceptionMessage)); + StackTraceWriter stackTraceWriter = mock(StackTraceWriter.class); + when(stackTraceWriter.getThrowable()).thenReturn(safeThrowable); + when(stackTraceWriter.smartTrimmedStackTrace()).thenReturn(smartStackTrace); + when(stackTraceWriter.writeTrimmedTraceToString()).thenReturn(trimmedStackTrace); + when(stackTraceWriter.writeTraceToString()).thenReturn(stackTrace); + + TestSetReportEntry reportEntry = mock(TestSetReportEntry.class); + when(reportEntry.getRunMode()).thenReturn(NORMAL_RUN); + when(reportEntry.getTestRunId()).thenReturn(1L); + when(reportEntry.getElapsed()).thenReturn(ELAPSED_TIME); + when(reportEntry.getGroup()).thenReturn("this group"); + when(reportEntry.getMessage()).thenReturn("some test"); + when(reportEntry.getName()).thenReturn("my test"); + when(reportEntry.getNameText()).thenReturn("dn2"); + when(reportEntry.getNameWithGroup()).thenReturn("name with group"); + when(reportEntry.getSourceName()).thenReturn("pkg.MyTest"); + when(reportEntry.getSourceText()).thenReturn("dn1"); + when(reportEntry.getStackTraceWriter()).thenReturn(stackTraceWriter); + + ForkClient client = new ForkClient(factory, notifiableTestStream, 0); + client.handleEvent(new TestsetStartingEvent(reportEntry)); + client.tryToTimeout(System.currentTimeMillis(), 1); + + verifyZeroInteractions(notifiableTestStream); + verify(factory).createTestReportListener(); + verifyNoMoreInteractions(factory); + assertThat(client.getReporter()).isNotNull(); + assertThat(receiver.getEvents()).hasSize(1); + assertThat(receiver.getEvents()).contains(SET_STARTING); + assertThat(receiver.getData()).hasSize(1); + assertThat(((ReportEntry) receiver.getData().get(0)).getSourceName()).isEqualTo("pkg.MyTest"); + assertThat(((ReportEntry) receiver.getData().get(0)).getSourceText()).isEqualTo("dn1"); + assertThat(((ReportEntry) receiver.getData().get(0)).getName()).isEqualTo("my test"); + assertThat(((ReportEntry) receiver.getData().get(0)).getNameText()).isEqualTo("dn2"); + assertThat(((ReportEntry) receiver.getData().get(0)).getElapsed()).isEqualTo(ELAPSED_TIME); + assertThat(((ReportEntry) receiver.getData().get(0)).getMessage()).isEqualTo("some test"); + assertThat(((ReportEntry) receiver.getData().get(0)).getGroup()).isEqualTo("this group"); + assertThat(((ReportEntry) receiver.getData().get(0)).getStackTraceWriter()) .isNotNull(); - assertThat( ( (ReportEntry) receiver.getData().get( 0 ) ) - .getStackTraceWriter().getThrowable().getLocalizedMessage() ) - .isEqualTo( "msg" ); - assertThat( ( (ReportEntry) receiver.getData().get( 0 ) ).getStackTraceWriter().smartTrimmedStackTrace() ) - .isEqualTo( smartStackTrace ); - assertThat( ( (ReportEntry) receiver.getData().get( 0 ) ).getStackTraceWriter().writeTraceToString() ) - .isEqualTo( stackTrace ); - assertThat( ( (ReportEntry) receiver.getData().get( 0 ) ).getStackTraceWriter().writeTrimmedTraceToString() ) - .isEqualTo( trimmedStackTrace ); - assertThat( client.isSaidGoodBye() ) - .isFalse(); - assertThat( client.isErrorInFork() ) - .isFalse(); - assertThat( client.getErrorInFork() ) - .isNull(); - assertThat( client.hadTimeout() ) - .isFalse(); - assertThat( client.hasTestsInProgress() ) - .isFalse(); - assertThat( client.testsInProgress() ) - .isEmpty(); - assertThat( client.getTestVmSystemProperties() ) - .isEmpty(); - assertThat( client.getTestVmSystemProperties() ) - .isEmpty(); - assertThat( client.getDefaultReporterFactory() ) - .isSameAs( factory ); + assertThat(((ReportEntry) receiver.getData().get(0)) + .getStackTraceWriter() + .getThrowable() + .getLocalizedMessage()) + .isEqualTo("msg"); + assertThat(((ReportEntry) receiver.getData().get(0)) + .getStackTraceWriter() + .smartTrimmedStackTrace()) + .isEqualTo(smartStackTrace); + assertThat(((ReportEntry) receiver.getData().get(0)) + .getStackTraceWriter() + .writeTraceToString()) + .isEqualTo(stackTrace); + assertThat(((ReportEntry) receiver.getData().get(0)) + .getStackTraceWriter() + .writeTrimmedTraceToString()) + .isEqualTo(trimmedStackTrace); + assertThat(client.isSaidGoodBye()).isFalse(); + assertThat(client.isErrorInFork()).isFalse(); + assertThat(client.getErrorInFork()).isNull(); + assertThat(client.hadTimeout()).isFalse(); + assertThat(client.hasTestsInProgress()).isFalse(); + assertThat(client.testsInProgress()).isEmpty(); + assertThat(client.getTestVmSystemProperties()).isEmpty(); + assertThat(client.getTestVmSystemProperties()).isEmpty(); + assertThat(client.getDefaultReporterFactory()).isSameAs(factory); } @Test - public void shouldSendTestsetCompleted() - { - String cwd = System.getProperty( "user.dir" ); - File target = new File( cwd, "target" ); - DefaultReporterFactory factory = mock( DefaultReporterFactory.class ); - when( factory.getReportsDirectory() ) - .thenReturn( new File( target, "surefire-reports" ) ); + public void shouldSendTestsetCompleted() { + String cwd = System.getProperty("user.dir"); + File target = new File(cwd, "target"); + DefaultReporterFactory factory = mock(DefaultReporterFactory.class); + when(factory.getReportsDirectory()).thenReturn(new File(target, "surefire-reports")); MockReporter receiver = new MockReporter(); - when( factory.createTestReportListener() ) - .thenReturn( receiver ); - NotifiableTestStream notifiableTestStream = mock( NotifiableTestStream.class ); + when(factory.createTestReportListener()).thenReturn(receiver); + NotifiableTestStream notifiableTestStream = mock(NotifiableTestStream.class); final String exceptionMessage = "msg"; final String smartStackTrace = "MyTest:86 >> Error"; final String stackTrace = "trace line 1\ntrace line 2"; final String trimmedStackTrace = "trace line 1"; - SafeThrowable safeThrowable = new SafeThrowable( new Exception( exceptionMessage ) ); - StackTraceWriter stackTraceWriter = mock( StackTraceWriter.class ); - when( stackTraceWriter.getThrowable() ).thenReturn( safeThrowable ); - when( stackTraceWriter.smartTrimmedStackTrace() ).thenReturn( smartStackTrace ); - when( stackTraceWriter.writeTrimmedTraceToString() ).thenReturn( trimmedStackTrace ); - when( stackTraceWriter.writeTraceToString() ).thenReturn( stackTrace ); - - TestSetReportEntry reportEntry = mock( TestSetReportEntry.class ); - when( reportEntry.getRunMode() ).thenReturn( NORMAL_RUN ); - when( reportEntry.getTestRunId() ).thenReturn( 1L ); - when( reportEntry.getElapsed() ).thenReturn( ELAPSED_TIME ); - when( reportEntry.getGroup() ).thenReturn( "this group" ); - when( reportEntry.getMessage() ).thenReturn( "some test" ); - when( reportEntry.getName() ).thenReturn( "my test" ); - when( reportEntry.getNameWithGroup() ).thenReturn( "name with group" ); - when( reportEntry.getSourceName() ).thenReturn( "pkg.MyTest" ); - when( reportEntry.getStackTraceWriter() ).thenReturn( stackTraceWriter ); - - ForkClient client = new ForkClient( factory, notifiableTestStream, 0 ); - client.handleEvent( new TestsetCompletedEvent( reportEntry ) ); - - verifyZeroInteractions( notifiableTestStream ); - verify( factory ).createTestReportListener(); - verifyNoMoreInteractions( factory ); - assertThat( client.getReporter() ) + SafeThrowable safeThrowable = new SafeThrowable(new Exception(exceptionMessage)); + StackTraceWriter stackTraceWriter = mock(StackTraceWriter.class); + when(stackTraceWriter.getThrowable()).thenReturn(safeThrowable); + when(stackTraceWriter.smartTrimmedStackTrace()).thenReturn(smartStackTrace); + when(stackTraceWriter.writeTrimmedTraceToString()).thenReturn(trimmedStackTrace); + when(stackTraceWriter.writeTraceToString()).thenReturn(stackTrace); + + TestSetReportEntry reportEntry = mock(TestSetReportEntry.class); + when(reportEntry.getRunMode()).thenReturn(NORMAL_RUN); + when(reportEntry.getTestRunId()).thenReturn(1L); + when(reportEntry.getElapsed()).thenReturn(ELAPSED_TIME); + when(reportEntry.getGroup()).thenReturn("this group"); + when(reportEntry.getMessage()).thenReturn("some test"); + when(reportEntry.getName()).thenReturn("my test"); + when(reportEntry.getNameWithGroup()).thenReturn("name with group"); + when(reportEntry.getSourceName()).thenReturn("pkg.MyTest"); + when(reportEntry.getStackTraceWriter()).thenReturn(stackTraceWriter); + + ForkClient client = new ForkClient(factory, notifiableTestStream, 0); + client.handleEvent(new TestsetCompletedEvent(reportEntry)); + + verifyZeroInteractions(notifiableTestStream); + verify(factory).createTestReportListener(); + verifyNoMoreInteractions(factory); + assertThat(client.getReporter()).isNotNull(); + assertThat(receiver.getEvents()).hasSize(1); + assertThat(receiver.getEvents()).contains(SET_COMPLETED); + assertThat(receiver.getData()).hasSize(1); + assertThat(((ReportEntry) receiver.getData().get(0)).getSourceName()).isEqualTo("pkg.MyTest"); + assertThat(((ReportEntry) receiver.getData().get(0)).getSourceText()).isNull(); + assertThat(((ReportEntry) receiver.getData().get(0)).getName()).isEqualTo("my test"); + assertThat(((ReportEntry) receiver.getData().get(0)).getNameText()).isNull(); + assertThat(((ReportEntry) receiver.getData().get(0)).getElapsed()).isEqualTo(ELAPSED_TIME); + assertThat(((ReportEntry) receiver.getData().get(0)).getMessage()).isEqualTo("some test"); + assertThat(((ReportEntry) receiver.getData().get(0)).getGroup()).isEqualTo("this group"); + assertThat(((ReportEntry) receiver.getData().get(0)).getStackTraceWriter()) .isNotNull(); - assertThat( receiver.getEvents() ) - .hasSize( 1 ); - assertThat( receiver.getEvents() ) - .contains( SET_COMPLETED ); - assertThat( receiver.getData() ) - .hasSize( 1 ); - assertThat( ( (ReportEntry) receiver.getData().get( 0 ) ).getSourceName() ) - .isEqualTo( "pkg.MyTest" ); - assertThat( ( (ReportEntry) receiver.getData().get( 0 ) ).getSourceText() ) - .isNull(); - assertThat( ( (ReportEntry) receiver.getData().get( 0 ) ).getName() ) - .isEqualTo( "my test" ); - assertThat( ( (ReportEntry) receiver.getData().get( 0 ) ).getNameText() ) - .isNull(); - assertThat( ( (ReportEntry) receiver.getData().get( 0 ) ).getElapsed() ) - .isEqualTo( ELAPSED_TIME ); - assertThat( ( (ReportEntry) receiver.getData().get( 0 ) ).getMessage() ) - .isEqualTo( "some test" ); - assertThat( ( (ReportEntry) receiver.getData().get( 0 ) ).getGroup() ) - .isEqualTo( "this group" ); - assertThat( ( (ReportEntry) receiver.getData().get( 0 ) ).getStackTraceWriter() ) - .isNotNull(); - assertThat( ( (ReportEntry) receiver.getData().get( 0 ) ) - .getStackTraceWriter().getThrowable().getLocalizedMessage() ) - .isEqualTo( "msg" ); - assertThat( ( (ReportEntry) receiver.getData().get( 0 ) ).getStackTraceWriter().smartTrimmedStackTrace() ) - .isEqualTo( "MyTest:86 >> Error" ); - assertThat( ( (ReportEntry) receiver.getData().get( 0 ) ).getStackTraceWriter().writeTraceToString() ) - .isEqualTo( stackTrace ); - assertThat( ( (ReportEntry) receiver.getData().get( 0 ) ).getStackTraceWriter().writeTrimmedTraceToString() ) - .isEqualTo( trimmedStackTrace ); - assertThat( client.isSaidGoodBye() ) - .isFalse(); - assertThat( client.isErrorInFork() ) - .isFalse(); - assertThat( client.getErrorInFork() ) - .isNull(); - assertThat( client.hadTimeout() ) - .isFalse(); - assertThat( client.hasTestsInProgress() ) - .isFalse(); - assertThat( client.testsInProgress() ) - .isEmpty(); - assertThat( client.getTestVmSystemProperties() ) - .isEmpty(); - assertThat( client.getTestVmSystemProperties() ) - .isEmpty(); - assertThat( client.getDefaultReporterFactory() ) - .isSameAs( factory ); + assertThat(((ReportEntry) receiver.getData().get(0)) + .getStackTraceWriter() + .getThrowable() + .getLocalizedMessage()) + .isEqualTo("msg"); + assertThat(((ReportEntry) receiver.getData().get(0)) + .getStackTraceWriter() + .smartTrimmedStackTrace()) + .isEqualTo("MyTest:86 >> Error"); + assertThat(((ReportEntry) receiver.getData().get(0)) + .getStackTraceWriter() + .writeTraceToString()) + .isEqualTo(stackTrace); + assertThat(((ReportEntry) receiver.getData().get(0)) + .getStackTraceWriter() + .writeTrimmedTraceToString()) + .isEqualTo(trimmedStackTrace); + assertThat(client.isSaidGoodBye()).isFalse(); + assertThat(client.isErrorInFork()).isFalse(); + assertThat(client.getErrorInFork()).isNull(); + assertThat(client.hadTimeout()).isFalse(); + assertThat(client.hasTestsInProgress()).isFalse(); + assertThat(client.testsInProgress()).isEmpty(); + assertThat(client.getTestVmSystemProperties()).isEmpty(); + assertThat(client.getTestVmSystemProperties()).isEmpty(); + assertThat(client.getDefaultReporterFactory()).isSameAs(factory); } @Test - public void shouldSendTestStarting() - { - String cwd = System.getProperty( "user.dir" ); - File target = new File( cwd, "target" ); - DefaultReporterFactory factory = mock( DefaultReporterFactory.class ); - when( factory.getReportsDirectory() ) - .thenReturn( new File( target, "surefire-reports" ) ); + public void shouldSendTestStarting() { + String cwd = System.getProperty("user.dir"); + File target = new File(cwd, "target"); + DefaultReporterFactory factory = mock(DefaultReporterFactory.class); + when(factory.getReportsDirectory()).thenReturn(new File(target, "surefire-reports")); MockReporter receiver = new MockReporter(); - when( factory.createTestReportListener() ) - .thenReturn( receiver ); - NotifiableTestStream notifiableTestStream = mock( NotifiableTestStream.class ); + when(factory.createTestReportListener()).thenReturn(receiver); + NotifiableTestStream notifiableTestStream = mock(NotifiableTestStream.class); final String exceptionMessage = "msg"; final String smartStackTrace = "MyTest:86 >> Error"; final String stackTrace = "trace line 1\ntrace line 2"; final String trimmedStackTrace = "trace line 1"; - SafeThrowable safeThrowable = new SafeThrowable( new Exception( exceptionMessage ) ); - StackTraceWriter stackTraceWriter = mock( StackTraceWriter.class ); - when( stackTraceWriter.getThrowable() ).thenReturn( safeThrowable ); - when( stackTraceWriter.smartTrimmedStackTrace() ).thenReturn( smartStackTrace ); - when( stackTraceWriter.writeTrimmedTraceToString() ).thenReturn( trimmedStackTrace ); - when( stackTraceWriter.writeTraceToString() ).thenReturn( stackTrace ); - - ReportEntry reportEntry = mock( ReportEntry.class ); - when( reportEntry.getRunMode() ).thenReturn( NORMAL_RUN ); - when( reportEntry.getTestRunId() ).thenReturn( 1L ); - when( reportEntry.getElapsed() ).thenReturn( ELAPSED_TIME ); - when( reportEntry.getGroup() ).thenReturn( "this group" ); - when( reportEntry.getMessage() ).thenReturn( "some test" ); - when( reportEntry.getName() ).thenReturn( "my test" ); - when( reportEntry.getNameWithGroup() ).thenReturn( "name with group" ); - when( reportEntry.getSourceName() ).thenReturn( "pkg.MyTest" ); - when( reportEntry.getStackTraceWriter() ).thenReturn( stackTraceWriter ); - - ForkClient client = new ForkClient( factory, notifiableTestStream, 0 ); - client.handleEvent( new TestStartingEvent( reportEntry ) ); - - verifyZeroInteractions( notifiableTestStream ); - verify( factory ).createTestReportListener(); - verifyNoMoreInteractions( factory ); - assertThat( client.hasTestsInProgress() ) - .isTrue(); - assertThat( client.testsInProgress() ) - .hasSize( 1 ) - .contains( "pkg.MyTest" ); - assertThat( client.getReporter() ) - .isNotNull(); - assertThat( receiver.getEvents() ) - .hasSize( 1 ); - assertThat( receiver.getEvents() ) - .contains( TEST_STARTING ); - assertThat( receiver.getData() ) - .hasSize( 1 ); - assertThat( ( (ReportEntry) receiver.getData().get( 0 ) ).getSourceName() ) - .isEqualTo( "pkg.MyTest" ); - assertThat( ( (ReportEntry) receiver.getData().get( 0 ) ).getSourceText() ) - .isNull(); - assertThat( ( (ReportEntry) receiver.getData().get( 0 ) ).getName() ) - .isEqualTo( "my test" ); - assertThat( ( (ReportEntry) receiver.getData().get( 0 ) ).getNameText() ) - .isNull(); - assertThat( ( (ReportEntry) receiver.getData().get( 0 ) ).getElapsed() ) - .isEqualTo( ELAPSED_TIME ); - assertThat( ( (ReportEntry) receiver.getData().get( 0 ) ).getMessage() ) - .isEqualTo( "some test" ); - assertThat( ( (ReportEntry) receiver.getData().get( 0 ) ).getGroup() ) - .isEqualTo( "this group" ); - assertThat( ( (ReportEntry) receiver.getData().get( 0 ) ).getStackTraceWriter() ) + SafeThrowable safeThrowable = new SafeThrowable(new Exception(exceptionMessage)); + StackTraceWriter stackTraceWriter = mock(StackTraceWriter.class); + when(stackTraceWriter.getThrowable()).thenReturn(safeThrowable); + when(stackTraceWriter.smartTrimmedStackTrace()).thenReturn(smartStackTrace); + when(stackTraceWriter.writeTrimmedTraceToString()).thenReturn(trimmedStackTrace); + when(stackTraceWriter.writeTraceToString()).thenReturn(stackTrace); + + ReportEntry reportEntry = mock(ReportEntry.class); + when(reportEntry.getRunMode()).thenReturn(NORMAL_RUN); + when(reportEntry.getTestRunId()).thenReturn(1L); + when(reportEntry.getElapsed()).thenReturn(ELAPSED_TIME); + when(reportEntry.getGroup()).thenReturn("this group"); + when(reportEntry.getMessage()).thenReturn("some test"); + when(reportEntry.getName()).thenReturn("my test"); + when(reportEntry.getNameWithGroup()).thenReturn("name with group"); + when(reportEntry.getSourceName()).thenReturn("pkg.MyTest"); + when(reportEntry.getStackTraceWriter()).thenReturn(stackTraceWriter); + + ForkClient client = new ForkClient(factory, notifiableTestStream, 0); + client.handleEvent(new TestStartingEvent(reportEntry)); + + verifyZeroInteractions(notifiableTestStream); + verify(factory).createTestReportListener(); + verifyNoMoreInteractions(factory); + assertThat(client.hasTestsInProgress()).isTrue(); + assertThat(client.testsInProgress()).hasSize(1).contains("pkg.MyTest"); + assertThat(client.getReporter()).isNotNull(); + assertThat(receiver.getEvents()).hasSize(1); + assertThat(receiver.getEvents()).contains(TEST_STARTING); + assertThat(receiver.getData()).hasSize(1); + assertThat(((ReportEntry) receiver.getData().get(0)).getSourceName()).isEqualTo("pkg.MyTest"); + assertThat(((ReportEntry) receiver.getData().get(0)).getSourceText()).isNull(); + assertThat(((ReportEntry) receiver.getData().get(0)).getName()).isEqualTo("my test"); + assertThat(((ReportEntry) receiver.getData().get(0)).getNameText()).isNull(); + assertThat(((ReportEntry) receiver.getData().get(0)).getElapsed()).isEqualTo(ELAPSED_TIME); + assertThat(((ReportEntry) receiver.getData().get(0)).getMessage()).isEqualTo("some test"); + assertThat(((ReportEntry) receiver.getData().get(0)).getGroup()).isEqualTo("this group"); + assertThat(((ReportEntry) receiver.getData().get(0)).getStackTraceWriter()) .isNotNull(); - assertThat( ( (ReportEntry) receiver.getData().get( 0 ) ) - .getStackTraceWriter().getThrowable().getLocalizedMessage() ) - .isEqualTo( "msg" ); - assertThat( ( (ReportEntry) receiver.getData().get( 0 ) ).getStackTraceWriter().smartTrimmedStackTrace() ) - .isEqualTo( smartStackTrace ); - assertThat( ( (ReportEntry) receiver.getData().get( 0 ) ).getStackTraceWriter().writeTraceToString() ) - .isEqualTo( stackTrace ); - assertThat( ( (ReportEntry) receiver.getData().get( 0 ) ).getStackTraceWriter().writeTrimmedTraceToString() ) - .isEqualTo( trimmedStackTrace ); - assertThat( client.isSaidGoodBye() ) - .isFalse(); - assertThat( client.isErrorInFork() ) - .isFalse(); - assertThat( client.getErrorInFork() ) - .isNull(); - assertThat( client.hadTimeout() ) - .isFalse(); - assertThat( client.getTestVmSystemProperties() ) - .isEmpty(); - assertThat( client.getTestVmSystemProperties() ) - .isEmpty(); - assertThat( client.getDefaultReporterFactory() ) - .isSameAs( factory ); + assertThat(((ReportEntry) receiver.getData().get(0)) + .getStackTraceWriter() + .getThrowable() + .getLocalizedMessage()) + .isEqualTo("msg"); + assertThat(((ReportEntry) receiver.getData().get(0)) + .getStackTraceWriter() + .smartTrimmedStackTrace()) + .isEqualTo(smartStackTrace); + assertThat(((ReportEntry) receiver.getData().get(0)) + .getStackTraceWriter() + .writeTraceToString()) + .isEqualTo(stackTrace); + assertThat(((ReportEntry) receiver.getData().get(0)) + .getStackTraceWriter() + .writeTrimmedTraceToString()) + .isEqualTo(trimmedStackTrace); + assertThat(client.isSaidGoodBye()).isFalse(); + assertThat(client.isErrorInFork()).isFalse(); + assertThat(client.getErrorInFork()).isNull(); + assertThat(client.hadTimeout()).isFalse(); + assertThat(client.getTestVmSystemProperties()).isEmpty(); + assertThat(client.getTestVmSystemProperties()).isEmpty(); + assertThat(client.getDefaultReporterFactory()).isSameAs(factory); } @Test - public void shouldSendTestSucceeded() - { - String cwd = System.getProperty( "user.dir" ); - File target = new File( cwd, "target" ); - DefaultReporterFactory factory = mock( DefaultReporterFactory.class ); - when( factory.getReportsDirectory() ) - .thenReturn( new File( target, "surefire-reports" ) ); + public void shouldSendTestSucceeded() { + String cwd = System.getProperty("user.dir"); + File target = new File(cwd, "target"); + DefaultReporterFactory factory = mock(DefaultReporterFactory.class); + when(factory.getReportsDirectory()).thenReturn(new File(target, "surefire-reports")); MockReporter receiver = new MockReporter(); - when( factory.createTestReportListener() ) - .thenReturn( receiver ); - NotifiableTestStream notifiableTestStream = mock( NotifiableTestStream.class ); + when(factory.createTestReportListener()).thenReturn(receiver); + NotifiableTestStream notifiableTestStream = mock(NotifiableTestStream.class); final String exceptionMessage = "msg"; final String smartStackTrace = "MyTest:86 >> Error"; final String stackTrace = "trace line 1\ntrace line 2"; final String trimmedStackTrace = "trace line 1"; - SafeThrowable safeThrowable = new SafeThrowable( new Exception( exceptionMessage ) ); - StackTraceWriter stackTraceWriter = mock( StackTraceWriter.class ); - when( stackTraceWriter.getThrowable() ).thenReturn( safeThrowable ); - when( stackTraceWriter.smartTrimmedStackTrace() ).thenReturn( smartStackTrace ); - when( stackTraceWriter.writeTrimmedTraceToString() ).thenReturn( trimmedStackTrace ); - when( stackTraceWriter.writeTraceToString() ).thenReturn( stackTrace ); - - ReportEntry reportEntry = mock( ReportEntry.class ); - when( reportEntry.getRunMode() ).thenReturn( NORMAL_RUN ); - when( reportEntry.getTestRunId() ).thenReturn( 1L ); - when( reportEntry.getElapsed() ).thenReturn( ELAPSED_TIME ); - when( reportEntry.getGroup() ).thenReturn( "this group" ); - when( reportEntry.getMessage() ).thenReturn( "some test" ); - when( reportEntry.getName() ).thenReturn( "my test" ); - when( reportEntry.getNameWithGroup() ).thenReturn( "name with group" ); - when( reportEntry.getSourceName() ).thenReturn( "pkg.MyTest" ); - when( reportEntry.getStackTraceWriter() ).thenReturn( stackTraceWriter ); - - ForkClient client = new ForkClient( factory, notifiableTestStream, 0 ); + SafeThrowable safeThrowable = new SafeThrowable(new Exception(exceptionMessage)); + StackTraceWriter stackTraceWriter = mock(StackTraceWriter.class); + when(stackTraceWriter.getThrowable()).thenReturn(safeThrowable); + when(stackTraceWriter.smartTrimmedStackTrace()).thenReturn(smartStackTrace); + when(stackTraceWriter.writeTrimmedTraceToString()).thenReturn(trimmedStackTrace); + when(stackTraceWriter.writeTraceToString()).thenReturn(stackTrace); + + ReportEntry reportEntry = mock(ReportEntry.class); + when(reportEntry.getRunMode()).thenReturn(NORMAL_RUN); + when(reportEntry.getTestRunId()).thenReturn(1L); + when(reportEntry.getElapsed()).thenReturn(ELAPSED_TIME); + when(reportEntry.getGroup()).thenReturn("this group"); + when(reportEntry.getMessage()).thenReturn("some test"); + when(reportEntry.getName()).thenReturn("my test"); + when(reportEntry.getNameWithGroup()).thenReturn("name with group"); + when(reportEntry.getSourceName()).thenReturn("pkg.MyTest"); + when(reportEntry.getStackTraceWriter()).thenReturn(stackTraceWriter); + + ForkClient client = new ForkClient(factory, notifiableTestStream, 0); SimpleReportEntry testStarted = - new SimpleReportEntry( NORMAL_RUN, 1L, reportEntry.getSourceName(), null, null, null ); - client.handleEvent( new TestStartingEvent( testStarted ) ); - - assertThat( client.testsInProgress() ) - .hasSize( 1 ) - .contains( "pkg.MyTest" ); - - client.handleEvent( new TestSucceededEvent( reportEntry ) ); - - verifyZeroInteractions( notifiableTestStream ); - verify( factory ).createTestReportListener(); - verifyNoMoreInteractions( factory ); - assertThat( client.getReporter() ) - .isNotNull(); - assertThat( receiver.getEvents() ) - .hasSize( 2 ); - assertThat( receiver.getEvents() ) - .contains( TEST_STARTING, TEST_SUCCEEDED ); - assertThat( receiver.getData() ) - .hasSize( 2 ); - assertThat( ( (ReportEntry) receiver.getData().get( 0 ) ).getSourceName() ) - .isEqualTo( "pkg.MyTest" ); - assertThat( ( (ReportEntry) receiver.getData().get( 0 ) ).getSourceText() ) - .isNull(); - assertThat( ( (ReportEntry) receiver.getData().get( 0 ) ).getName() ) - .isNull(); - assertThat( ( (ReportEntry) receiver.getData().get( 0 ) ).getNameText() ) - .isNull(); - assertThat( ( (ReportEntry) receiver.getData().get( 1 ) ).getSourceName() ) - .isEqualTo( "pkg.MyTest" ); - assertThat( ( (ReportEntry) receiver.getData().get( 1 ) ).getName() ) - .isEqualTo( "my test" ); - assertThat( ( (ReportEntry) receiver.getData().get( 1 ) ).getElapsed() ) - .isEqualTo( ELAPSED_TIME ); - assertThat( ( (ReportEntry) receiver.getData().get( 1 ) ).getMessage() ) - .isEqualTo( "some test" ); - assertThat( ( (ReportEntry) receiver.getData().get( 1 ) ).getGroup() ) - .isEqualTo( "this group" ); - assertThat( ( (ReportEntry) receiver.getData().get( 1 ) ).getStackTraceWriter() ) + new SimpleReportEntry(NORMAL_RUN, 1L, reportEntry.getSourceName(), null, null, null); + client.handleEvent(new TestStartingEvent(testStarted)); + + assertThat(client.testsInProgress()).hasSize(1).contains("pkg.MyTest"); + + client.handleEvent(new TestSucceededEvent(reportEntry)); + + verifyZeroInteractions(notifiableTestStream); + verify(factory).createTestReportListener(); + verifyNoMoreInteractions(factory); + assertThat(client.getReporter()).isNotNull(); + assertThat(receiver.getEvents()).hasSize(2); + assertThat(receiver.getEvents()).contains(TEST_STARTING, TEST_SUCCEEDED); + assertThat(receiver.getData()).hasSize(2); + assertThat(((ReportEntry) receiver.getData().get(0)).getSourceName()).isEqualTo("pkg.MyTest"); + assertThat(((ReportEntry) receiver.getData().get(0)).getSourceText()).isNull(); + assertThat(((ReportEntry) receiver.getData().get(0)).getName()).isNull(); + assertThat(((ReportEntry) receiver.getData().get(0)).getNameText()).isNull(); + assertThat(((ReportEntry) receiver.getData().get(1)).getSourceName()).isEqualTo("pkg.MyTest"); + assertThat(((ReportEntry) receiver.getData().get(1)).getName()).isEqualTo("my test"); + assertThat(((ReportEntry) receiver.getData().get(1)).getElapsed()).isEqualTo(ELAPSED_TIME); + assertThat(((ReportEntry) receiver.getData().get(1)).getMessage()).isEqualTo("some test"); + assertThat(((ReportEntry) receiver.getData().get(1)).getGroup()).isEqualTo("this group"); + assertThat(((ReportEntry) receiver.getData().get(1)).getStackTraceWriter()) .isNotNull(); - assertThat( ( (ReportEntry) receiver.getData().get( 1 ) ) - .getStackTraceWriter().getThrowable().getLocalizedMessage() ) - .isEqualTo( "msg" ); - assertThat( ( (ReportEntry) receiver.getData().get( 1 ) ).getStackTraceWriter().smartTrimmedStackTrace() ) - .isEqualTo( smartStackTrace ); - assertThat( ( (ReportEntry) receiver.getData().get( 1 ) ).getStackTraceWriter().writeTraceToString() ) - .isEqualTo( stackTrace ); - assertThat( ( (ReportEntry) receiver.getData().get( 1 ) ).getStackTraceWriter().writeTrimmedTraceToString() ) - .isEqualTo( trimmedStackTrace ); - assertThat( client.isSaidGoodBye() ) - .isFalse(); - assertThat( client.isErrorInFork() ) - .isFalse(); - assertThat( client.getErrorInFork() ) - .isNull(); - assertThat( client.hadTimeout() ) - .isFalse(); - assertThat( client.hasTestsInProgress() ) - .isFalse(); - assertThat( client.testsInProgress() ) - .isEmpty(); - assertThat( client.getTestVmSystemProperties() ) - .isEmpty(); - assertThat( client.getTestVmSystemProperties() ) - .isEmpty(); - assertThat( client.getDefaultReporterFactory() ) - .isSameAs( factory ); + assertThat(((ReportEntry) receiver.getData().get(1)) + .getStackTraceWriter() + .getThrowable() + .getLocalizedMessage()) + .isEqualTo("msg"); + assertThat(((ReportEntry) receiver.getData().get(1)) + .getStackTraceWriter() + .smartTrimmedStackTrace()) + .isEqualTo(smartStackTrace); + assertThat(((ReportEntry) receiver.getData().get(1)) + .getStackTraceWriter() + .writeTraceToString()) + .isEqualTo(stackTrace); + assertThat(((ReportEntry) receiver.getData().get(1)) + .getStackTraceWriter() + .writeTrimmedTraceToString()) + .isEqualTo(trimmedStackTrace); + assertThat(client.isSaidGoodBye()).isFalse(); + assertThat(client.isErrorInFork()).isFalse(); + assertThat(client.getErrorInFork()).isNull(); + assertThat(client.hadTimeout()).isFalse(); + assertThat(client.hasTestsInProgress()).isFalse(); + assertThat(client.testsInProgress()).isEmpty(); + assertThat(client.getTestVmSystemProperties()).isEmpty(); + assertThat(client.getTestVmSystemProperties()).isEmpty(); + assertThat(client.getDefaultReporterFactory()).isSameAs(factory); } @Test - public void shouldSendTestFailed() - { - String cwd = System.getProperty( "user.dir" ); - File target = new File( cwd, "target" ); - DefaultReporterFactory factory = mock( DefaultReporterFactory.class ); - when( factory.getReportsDirectory() ) - .thenReturn( new File( target, "surefire-reports" ) ); + public void shouldSendTestFailed() { + String cwd = System.getProperty("user.dir"); + File target = new File(cwd, "target"); + DefaultReporterFactory factory = mock(DefaultReporterFactory.class); + when(factory.getReportsDirectory()).thenReturn(new File(target, "surefire-reports")); MockReporter receiver = new MockReporter(); - when( factory.createTestReportListener() ) - .thenReturn( receiver ); - NotifiableTestStream notifiableTestStream = mock( NotifiableTestStream.class ); + when(factory.createTestReportListener()).thenReturn(receiver); + NotifiableTestStream notifiableTestStream = mock(NotifiableTestStream.class); final String exceptionMessage = "msg"; final String smartStackTrace = "MyTest:86 >> Error"; final String stackTrace = "trace line 1\ntrace line 2"; final String trimmedStackTrace = "trace line 1"; - SafeThrowable safeThrowable = new SafeThrowable( new Exception( exceptionMessage ) ); - StackTraceWriter stackTraceWriter = mock( StackTraceWriter.class ); - when( stackTraceWriter.getThrowable() ).thenReturn( safeThrowable ); - when( stackTraceWriter.smartTrimmedStackTrace() ).thenReturn( smartStackTrace ); - when( stackTraceWriter.writeTrimmedTraceToString() ).thenReturn( trimmedStackTrace ); - when( stackTraceWriter.writeTraceToString() ).thenReturn( stackTrace ); - - ReportEntry reportEntry = mock( ReportEntry.class ); - when( reportEntry.getRunMode() ).thenReturn( NORMAL_RUN ); - when( reportEntry.getTestRunId() ).thenReturn( 1L ); - when( reportEntry.getElapsed() ).thenReturn( ELAPSED_TIME ); - when( reportEntry.getGroup() ).thenReturn( "this group" ); - when( reportEntry.getMessage() ).thenReturn( "some test" ); - when( reportEntry.getName() ).thenReturn( "my test" ); - when( reportEntry.getNameWithGroup() ).thenReturn( "name with group" ); - when( reportEntry.getSourceName() ).thenReturn( "pkg.MyTest" ); - when( reportEntry.getStackTraceWriter() ).thenReturn( stackTraceWriter ); - - ForkClient client = new ForkClient( factory, notifiableTestStream, 0 ); + SafeThrowable safeThrowable = new SafeThrowable(new Exception(exceptionMessage)); + StackTraceWriter stackTraceWriter = mock(StackTraceWriter.class); + when(stackTraceWriter.getThrowable()).thenReturn(safeThrowable); + when(stackTraceWriter.smartTrimmedStackTrace()).thenReturn(smartStackTrace); + when(stackTraceWriter.writeTrimmedTraceToString()).thenReturn(trimmedStackTrace); + when(stackTraceWriter.writeTraceToString()).thenReturn(stackTrace); + + ReportEntry reportEntry = mock(ReportEntry.class); + when(reportEntry.getRunMode()).thenReturn(NORMAL_RUN); + when(reportEntry.getTestRunId()).thenReturn(1L); + when(reportEntry.getElapsed()).thenReturn(ELAPSED_TIME); + when(reportEntry.getGroup()).thenReturn("this group"); + when(reportEntry.getMessage()).thenReturn("some test"); + when(reportEntry.getName()).thenReturn("my test"); + when(reportEntry.getNameWithGroup()).thenReturn("name with group"); + when(reportEntry.getSourceName()).thenReturn("pkg.MyTest"); + when(reportEntry.getStackTraceWriter()).thenReturn(stackTraceWriter); + + ForkClient client = new ForkClient(factory, notifiableTestStream, 0); SimpleReportEntry testClass = - new SimpleReportEntry( NORMAL_RUN, 1L, reportEntry.getSourceName(), null, null, null ); - client.handleEvent( new TestStartingEvent( testClass ) ); - - assertThat( client.testsInProgress() ) - .hasSize( 1 ) - .contains( "pkg.MyTest" ); - - client.handleEvent( new TestFailedEvent( reportEntry ) ); - - verifyZeroInteractions( notifiableTestStream ); - verify( factory ).createTestReportListener(); - verifyNoMoreInteractions( factory ); - assertThat( client.getReporter() ) - .isNotNull(); - assertThat( receiver.getEvents() ) - .hasSize( 2 ); - assertThat( receiver.getEvents() ) - .contains( TEST_STARTING, TEST_FAILED ); - assertThat( receiver.getData() ) - .hasSize( 2 ); - assertThat( ( (ReportEntry) receiver.getData().get( 0 ) ).getSourceName() ) - .isEqualTo( "pkg.MyTest" ); - assertThat( ( (ReportEntry) receiver.getData().get( 0 ) ).getSourceText() ) - .isNull(); - assertThat( ( (ReportEntry) receiver.getData().get( 0 ) ).getName() ) + new SimpleReportEntry(NORMAL_RUN, 1L, reportEntry.getSourceName(), null, null, null); + client.handleEvent(new TestStartingEvent(testClass)); + + assertThat(client.testsInProgress()).hasSize(1).contains("pkg.MyTest"); + + client.handleEvent(new TestFailedEvent(reportEntry)); + + verifyZeroInteractions(notifiableTestStream); + verify(factory).createTestReportListener(); + verifyNoMoreInteractions(factory); + assertThat(client.getReporter()).isNotNull(); + assertThat(receiver.getEvents()).hasSize(2); + assertThat(receiver.getEvents()).contains(TEST_STARTING, TEST_FAILED); + assertThat(receiver.getData()).hasSize(2); + assertThat(((ReportEntry) receiver.getData().get(0)).getSourceName()).isEqualTo("pkg.MyTest"); + assertThat(((ReportEntry) receiver.getData().get(0)).getSourceText()).isNull(); + assertThat(((ReportEntry) receiver.getData().get(0)).getName()).isNull(); + assertThat(((ReportEntry) receiver.getData().get(0)).getNameText()).isNull(); + assertThat(((ReportEntry) receiver.getData().get(0)).getStackTraceWriter()) .isNull(); - assertThat( ( (ReportEntry) receiver.getData().get( 0 ) ).getNameText() ) - .isNull(); - assertThat( ( (ReportEntry) receiver.getData().get( 0 ) ).getStackTraceWriter() ) - .isNull(); - assertThat( ( (ReportEntry) receiver.getData().get( 1 ) ).getSourceName() ) - .isEqualTo( "pkg.MyTest" ); - assertThat( ( (ReportEntry) receiver.getData().get( 1 ) ).getSourceText() ) - .isNull(); - assertThat( ( (ReportEntry) receiver.getData().get( 1 ) ).getName() ) - .isEqualTo( "my test" ); - assertThat( ( (ReportEntry) receiver.getData().get( 1 ) ).getNameText() ) - .isNull(); - assertThat( ( (ReportEntry) receiver.getData().get( 1 ) ).getElapsed() ) - .isEqualTo( ELAPSED_TIME ); - assertThat( ( (ReportEntry) receiver.getData().get( 1 ) ).getMessage() ) - .isEqualTo( "some test" ); - assertThat( ( (ReportEntry) receiver.getData().get( 1 ) ).getGroup() ) - .isEqualTo( "this group" ); - assertThat( ( (ReportEntry) receiver.getData().get( 1 ) ).getStackTraceWriter() ) + assertThat(((ReportEntry) receiver.getData().get(1)).getSourceName()).isEqualTo("pkg.MyTest"); + assertThat(((ReportEntry) receiver.getData().get(1)).getSourceText()).isNull(); + assertThat(((ReportEntry) receiver.getData().get(1)).getName()).isEqualTo("my test"); + assertThat(((ReportEntry) receiver.getData().get(1)).getNameText()).isNull(); + assertThat(((ReportEntry) receiver.getData().get(1)).getElapsed()).isEqualTo(ELAPSED_TIME); + assertThat(((ReportEntry) receiver.getData().get(1)).getMessage()).isEqualTo("some test"); + assertThat(((ReportEntry) receiver.getData().get(1)).getGroup()).isEqualTo("this group"); + assertThat(((ReportEntry) receiver.getData().get(1)).getStackTraceWriter()) .isNotNull(); - assertThat( ( (ReportEntry) receiver.getData().get( 1 ) ) - .getStackTraceWriter().getThrowable().getLocalizedMessage() ) - .isEqualTo( "msg" ); - assertThat( ( (ReportEntry) receiver.getData().get( 1 ) ).getStackTraceWriter().smartTrimmedStackTrace() ) - .isEqualTo( "MyTest:86 >> Error" ); - assertThat( ( (ReportEntry) receiver.getData().get( 1 ) ).getStackTraceWriter().writeTraceToString() ) - .isEqualTo( stackTrace ); - assertThat( ( (ReportEntry) receiver.getData().get( 1 ) ).getStackTraceWriter().writeTrimmedTraceToString() ) - .isEqualTo( trimmedStackTrace ); - assertThat( client.isSaidGoodBye() ) - .isFalse(); - assertThat( client.isErrorInFork() ) - .isFalse(); - assertThat( client.getErrorInFork() ) - .isNull(); - assertThat( client.hadTimeout() ) - .isFalse(); - assertThat( client.hasTestsInProgress() ) - .isFalse(); - assertThat( client.testsInProgress() ) - .isEmpty(); - assertThat( client.getTestVmSystemProperties() ) - .isEmpty(); - assertThat( client.getTestVmSystemProperties() ) - .isEmpty(); - assertThat( client.getDefaultReporterFactory() ) - .isSameAs( factory ); + assertThat(((ReportEntry) receiver.getData().get(1)) + .getStackTraceWriter() + .getThrowable() + .getLocalizedMessage()) + .isEqualTo("msg"); + assertThat(((ReportEntry) receiver.getData().get(1)) + .getStackTraceWriter() + .smartTrimmedStackTrace()) + .isEqualTo("MyTest:86 >> Error"); + assertThat(((ReportEntry) receiver.getData().get(1)) + .getStackTraceWriter() + .writeTraceToString()) + .isEqualTo(stackTrace); + assertThat(((ReportEntry) receiver.getData().get(1)) + .getStackTraceWriter() + .writeTrimmedTraceToString()) + .isEqualTo(trimmedStackTrace); + assertThat(client.isSaidGoodBye()).isFalse(); + assertThat(client.isErrorInFork()).isFalse(); + assertThat(client.getErrorInFork()).isNull(); + assertThat(client.hadTimeout()).isFalse(); + assertThat(client.hasTestsInProgress()).isFalse(); + assertThat(client.testsInProgress()).isEmpty(); + assertThat(client.getTestVmSystemProperties()).isEmpty(); + assertThat(client.getTestVmSystemProperties()).isEmpty(); + assertThat(client.getDefaultReporterFactory()).isSameAs(factory); } @Test - public void shouldSendTestSkipped() - { - String cwd = System.getProperty( "user.dir" ); - File target = new File( cwd, "target" ); - DefaultReporterFactory factory = mock( DefaultReporterFactory.class ); - when( factory.getReportsDirectory() ) - .thenReturn( new File( target, "surefire-reports" ) ); + public void shouldSendTestSkipped() { + String cwd = System.getProperty("user.dir"); + File target = new File(cwd, "target"); + DefaultReporterFactory factory = mock(DefaultReporterFactory.class); + when(factory.getReportsDirectory()).thenReturn(new File(target, "surefire-reports")); MockReporter receiver = new MockReporter(); - when( factory.createTestReportListener() ) - .thenReturn( receiver ); - NotifiableTestStream notifiableTestStream = mock( NotifiableTestStream.class ); + when(factory.createTestReportListener()).thenReturn(receiver); + NotifiableTestStream notifiableTestStream = mock(NotifiableTestStream.class); final String exceptionMessage = "msg"; final String smartStackTrace = "MyTest:86 >> Error"; final String stackTrace = "trace line 1\ntrace line 2"; final String trimmedStackTrace = "trace line 1"; - SafeThrowable safeThrowable = new SafeThrowable( new Exception( exceptionMessage ) ); - StackTraceWriter stackTraceWriter = mock( StackTraceWriter.class ); - when( stackTraceWriter.getThrowable() ).thenReturn( safeThrowable ); - when( stackTraceWriter.smartTrimmedStackTrace() ).thenReturn( smartStackTrace ); - when( stackTraceWriter.writeTrimmedTraceToString() ).thenReturn( trimmedStackTrace ); - when( stackTraceWriter.writeTraceToString() ).thenReturn( stackTrace ); - - ReportEntry reportEntry = mock( ReportEntry.class ); - when( reportEntry.getRunMode() ).thenReturn( NORMAL_RUN ); - when( reportEntry.getTestRunId() ).thenReturn( 1L ); - when( reportEntry.getElapsed() ).thenReturn( ELAPSED_TIME ); - when( reportEntry.getGroup() ).thenReturn( "this group" ); - when( reportEntry.getMessage() ).thenReturn( "some test" ); - when( reportEntry.getName() ).thenReturn( "my test" ); - when( reportEntry.getNameWithGroup() ).thenReturn( "name with group" ); - when( reportEntry.getSourceName() ).thenReturn( "pkg.MyTest" ); - when( reportEntry.getStackTraceWriter() ).thenReturn( stackTraceWriter ); - - ForkClient client = new ForkClient( factory, notifiableTestStream, 0 ); + SafeThrowable safeThrowable = new SafeThrowable(new Exception(exceptionMessage)); + StackTraceWriter stackTraceWriter = mock(StackTraceWriter.class); + when(stackTraceWriter.getThrowable()).thenReturn(safeThrowable); + when(stackTraceWriter.smartTrimmedStackTrace()).thenReturn(smartStackTrace); + when(stackTraceWriter.writeTrimmedTraceToString()).thenReturn(trimmedStackTrace); + when(stackTraceWriter.writeTraceToString()).thenReturn(stackTrace); + + ReportEntry reportEntry = mock(ReportEntry.class); + when(reportEntry.getRunMode()).thenReturn(NORMAL_RUN); + when(reportEntry.getTestRunId()).thenReturn(1L); + when(reportEntry.getElapsed()).thenReturn(ELAPSED_TIME); + when(reportEntry.getGroup()).thenReturn("this group"); + when(reportEntry.getMessage()).thenReturn("some test"); + when(reportEntry.getName()).thenReturn("my test"); + when(reportEntry.getNameWithGroup()).thenReturn("name with group"); + when(reportEntry.getSourceName()).thenReturn("pkg.MyTest"); + when(reportEntry.getStackTraceWriter()).thenReturn(stackTraceWriter); + + ForkClient client = new ForkClient(factory, notifiableTestStream, 0); SimpleReportEntry testStarted = - new SimpleReportEntry( NORMAL_RUN, 1L, reportEntry.getSourceName(), null, null, null ); - client.handleEvent( new TestStartingEvent( testStarted ) ); - - assertThat( client.testsInProgress() ) - .hasSize( 1 ) - .contains( "pkg.MyTest" ); - - client.handleEvent( new TestSkippedEvent( reportEntry ) ); - - verifyZeroInteractions( notifiableTestStream ); - verify( factory ).createTestReportListener(); - verifyNoMoreInteractions( factory ); - assertThat( client.getReporter() ) + new SimpleReportEntry(NORMAL_RUN, 1L, reportEntry.getSourceName(), null, null, null); + client.handleEvent(new TestStartingEvent(testStarted)); + + assertThat(client.testsInProgress()).hasSize(1).contains("pkg.MyTest"); + + client.handleEvent(new TestSkippedEvent(reportEntry)); + + verifyZeroInteractions(notifiableTestStream); + verify(factory).createTestReportListener(); + verifyNoMoreInteractions(factory); + assertThat(client.getReporter()).isNotNull(); + assertThat(receiver.getEvents()).hasSize(2); + assertThat(receiver.getEvents()).contains(TEST_STARTING, TEST_SKIPPED); + assertThat(receiver.getData()).hasSize(2); + assertThat(((ReportEntry) receiver.getData().get(0)).getSourceName()).isEqualTo("pkg.MyTest"); + assertThat(((ReportEntry) receiver.getData().get(0)).getSourceText()).isNull(); + assertThat(((ReportEntry) receiver.getData().get(0)).getName()).isNull(); + assertThat(((ReportEntry) receiver.getData().get(0)).getNameText()).isNull(); + assertThat(((ReportEntry) receiver.getData().get(1)).getSourceName()).isEqualTo("pkg.MyTest"); + assertThat(((ReportEntry) receiver.getData().get(1)).getSourceText()).isNull(); + assertThat(((ReportEntry) receiver.getData().get(1)).getName()).isEqualTo("my test"); + assertThat(((ReportEntry) receiver.getData().get(1)).getNameText()).isNull(); + assertThat(((ReportEntry) receiver.getData().get(1)).getElapsed()).isEqualTo(ELAPSED_TIME); + assertThat(((ReportEntry) receiver.getData().get(1)).getMessage()).isEqualTo("some test"); + assertThat(((ReportEntry) receiver.getData().get(1)).getGroup()).isEqualTo("this group"); + assertThat(((ReportEntry) receiver.getData().get(1)).getStackTraceWriter()) .isNotNull(); - assertThat( receiver.getEvents() ) - .hasSize( 2 ); - assertThat( receiver.getEvents() ) - .contains( TEST_STARTING, TEST_SKIPPED ); - assertThat( receiver.getData() ) - .hasSize( 2 ); - assertThat( ( (ReportEntry) receiver.getData().get( 0 ) ).getSourceName() ) - .isEqualTo( "pkg.MyTest" ); - assertThat( ( (ReportEntry) receiver.getData().get( 0 ) ).getSourceText() ) - .isNull(); - assertThat( ( (ReportEntry) receiver.getData().get( 0 ) ).getName() ) - .isNull(); - assertThat( ( (ReportEntry) receiver.getData().get( 0 ) ).getNameText() ) - .isNull(); - assertThat( ( (ReportEntry) receiver.getData().get( 1 ) ).getSourceName() ) - .isEqualTo( "pkg.MyTest" ); - assertThat( ( (ReportEntry) receiver.getData().get( 1 ) ).getSourceText() ) - .isNull(); - assertThat( ( (ReportEntry) receiver.getData().get( 1 ) ).getName() ) - .isEqualTo( "my test" ); - assertThat( ( (ReportEntry) receiver.getData().get( 1 ) ).getNameText() ) - .isNull(); - assertThat( ( (ReportEntry) receiver.getData().get( 1 ) ).getElapsed() ) - .isEqualTo( ELAPSED_TIME ); - assertThat( ( (ReportEntry) receiver.getData().get( 1 ) ).getMessage() ) - .isEqualTo( "some test" ); - assertThat( ( (ReportEntry) receiver.getData().get( 1 ) ).getGroup() ) - .isEqualTo( "this group" ); - assertThat( ( (ReportEntry) receiver.getData().get( 1 ) ).getStackTraceWriter() ) - .isNotNull(); - assertThat( ( (ReportEntry) receiver.getData().get( 1 ) ) - .getStackTraceWriter().getThrowable().getLocalizedMessage() ) - .isEqualTo( "msg" ); - assertThat( ( (ReportEntry) receiver.getData().get( 1 ) ).getStackTraceWriter().smartTrimmedStackTrace() ) - .isEqualTo( smartStackTrace ); - assertThat( ( (ReportEntry) receiver.getData().get( 1 ) ).getStackTraceWriter().writeTraceToString() ) - .isEqualTo( stackTrace ); - assertThat( ( (ReportEntry) receiver.getData().get( 1 ) ).getStackTraceWriter().writeTrimmedTraceToString() ) - .isEqualTo( trimmedStackTrace ); - assertThat( client.isSaidGoodBye() ) - .isFalse(); - assertThat( client.isErrorInFork() ) - .isFalse(); - assertThat( client.getErrorInFork() ) - .isNull(); - assertThat( client.hadTimeout() ) - .isFalse(); - assertThat( client.hasTestsInProgress() ) - .isFalse(); - assertThat( client.testsInProgress() ) - .isEmpty(); - assertThat( client.getTestVmSystemProperties() ) - .isEmpty(); - assertThat( client.getTestVmSystemProperties() ) - .isEmpty(); - assertThat( client.getDefaultReporterFactory() ) - .isSameAs( factory ); + assertThat(((ReportEntry) receiver.getData().get(1)) + .getStackTraceWriter() + .getThrowable() + .getLocalizedMessage()) + .isEqualTo("msg"); + assertThat(((ReportEntry) receiver.getData().get(1)) + .getStackTraceWriter() + .smartTrimmedStackTrace()) + .isEqualTo(smartStackTrace); + assertThat(((ReportEntry) receiver.getData().get(1)) + .getStackTraceWriter() + .writeTraceToString()) + .isEqualTo(stackTrace); + assertThat(((ReportEntry) receiver.getData().get(1)) + .getStackTraceWriter() + .writeTrimmedTraceToString()) + .isEqualTo(trimmedStackTrace); + assertThat(client.isSaidGoodBye()).isFalse(); + assertThat(client.isErrorInFork()).isFalse(); + assertThat(client.getErrorInFork()).isNull(); + assertThat(client.hadTimeout()).isFalse(); + assertThat(client.hasTestsInProgress()).isFalse(); + assertThat(client.testsInProgress()).isEmpty(); + assertThat(client.getTestVmSystemProperties()).isEmpty(); + assertThat(client.getTestVmSystemProperties()).isEmpty(); + assertThat(client.getDefaultReporterFactory()).isSameAs(factory); } @Test - public void shouldSendTestError() - { - String cwd = System.getProperty( "user.dir" ); - File target = new File( cwd, "target" ); - DefaultReporterFactory factory = mock( DefaultReporterFactory.class ); - when( factory.getReportsDirectory() ) - .thenReturn( new File( target, "surefire-reports" ) ); + public void shouldSendTestError() { + String cwd = System.getProperty("user.dir"); + File target = new File(cwd, "target"); + DefaultReporterFactory factory = mock(DefaultReporterFactory.class); + when(factory.getReportsDirectory()).thenReturn(new File(target, "surefire-reports")); MockReporter receiver = new MockReporter(); - when( factory.createTestReportListener() ) - .thenReturn( receiver ); - NotifiableTestStream notifiableTestStream = mock( NotifiableTestStream.class ); + when(factory.createTestReportListener()).thenReturn(receiver); + NotifiableTestStream notifiableTestStream = mock(NotifiableTestStream.class); final String exceptionMessage = "msg"; final String smartStackTrace = "MyTest:86 >> Error"; final String stackTrace = "trace line 1\ntrace line 2"; final String trimmedStackTrace = "trace line 1"; - SafeThrowable safeThrowable = new SafeThrowable( new Exception( exceptionMessage ) ); - StackTraceWriter stackTraceWriter = mock( StackTraceWriter.class ); - when( stackTraceWriter.getThrowable() ).thenReturn( safeThrowable ); - when( stackTraceWriter.smartTrimmedStackTrace() ).thenReturn( smartStackTrace ); - when( stackTraceWriter.writeTrimmedTraceToString() ).thenReturn( trimmedStackTrace ); - when( stackTraceWriter.writeTraceToString() ).thenReturn( stackTrace ); - - ReportEntry reportEntry = mock( ReportEntry.class ); - when( reportEntry.getRunMode() ).thenReturn( NORMAL_RUN ); - when( reportEntry.getTestRunId() ).thenReturn( 1L ); - when( reportEntry.getElapsed() ).thenReturn( ELAPSED_TIME ); - when( reportEntry.getGroup() ).thenReturn( "this group" ); - when( reportEntry.getMessage() ).thenReturn( "some test" ); - when( reportEntry.getName() ).thenReturn( "my test" ); - when( reportEntry.getNameWithGroup() ).thenReturn( "name with group" ); - when( reportEntry.getSourceName() ).thenReturn( "pkg.MyTest" ); - when( reportEntry.getSourceText() ).thenReturn( "display name" ); - when( reportEntry.getStackTraceWriter() ).thenReturn( stackTraceWriter ); - - ForkClient client = new ForkClient( factory, notifiableTestStream, 0 ); - SimpleReportEntry testStarted = new SimpleReportEntry( NORMAL_RUN, 1L, reportEntry.getSourceName(), - reportEntry.getSourceText(), null, null ); - client.handleEvent( new TestStartingEvent( testStarted ) ); - - assertThat( client.testsInProgress() ) - .hasSize( 1 ) - .contains( "pkg.MyTest" ); - - client.handleEvent( new TestErrorEvent( reportEntry ) ); - - verifyZeroInteractions( notifiableTestStream ); - verify( factory ).createTestReportListener(); - verifyNoMoreInteractions( factory ); - assertThat( client.getReporter() ) - .isNotNull(); - assertThat( receiver.getEvents() ) - .hasSize( 2 ); - assertThat( receiver.getEvents() ) - .contains( TEST_STARTING, TEST_ERROR ); - assertThat( receiver.getData() ) - .hasSize( 2 ); - assertThat( ( (ReportEntry) receiver.getData().get( 0 ) ).getSourceName() ) - .isEqualTo( "pkg.MyTest" ); - assertThat( ( (ReportEntry) receiver.getData().get( 0 ) ).getSourceText() ) - .isEqualTo( "display name" ); - assertThat( ( (ReportEntry) receiver.getData().get( 0 ) ).getName() ) - .isNull(); - assertThat( ( (ReportEntry) receiver.getData().get( 1 ) ).getSourceName() ) - .isEqualTo( "pkg.MyTest" ); - assertThat( ( (ReportEntry) receiver.getData().get( 1 ) ).getSourceText() ) - .isEqualTo( "display name" ); - assertThat( ( (ReportEntry) receiver.getData().get( 1 ) ).getName() ) - .isEqualTo( "my test" ); - assertThat( ( (ReportEntry) receiver.getData().get( 1 ) ).getElapsed() ) - .isEqualTo( ELAPSED_TIME ); - assertThat( ( (ReportEntry) receiver.getData().get( 1 ) ).getMessage() ) - .isEqualTo( "some test" ); - assertThat( ( (ReportEntry) receiver.getData().get( 1 ) ).getGroup() ) - .isEqualTo( "this group" ); - assertThat( ( (ReportEntry) receiver.getData().get( 1 ) ).getStackTraceWriter() ) + SafeThrowable safeThrowable = new SafeThrowable(new Exception(exceptionMessage)); + StackTraceWriter stackTraceWriter = mock(StackTraceWriter.class); + when(stackTraceWriter.getThrowable()).thenReturn(safeThrowable); + when(stackTraceWriter.smartTrimmedStackTrace()).thenReturn(smartStackTrace); + when(stackTraceWriter.writeTrimmedTraceToString()).thenReturn(trimmedStackTrace); + when(stackTraceWriter.writeTraceToString()).thenReturn(stackTrace); + + ReportEntry reportEntry = mock(ReportEntry.class); + when(reportEntry.getRunMode()).thenReturn(NORMAL_RUN); + when(reportEntry.getTestRunId()).thenReturn(1L); + when(reportEntry.getElapsed()).thenReturn(ELAPSED_TIME); + when(reportEntry.getGroup()).thenReturn("this group"); + when(reportEntry.getMessage()).thenReturn("some test"); + when(reportEntry.getName()).thenReturn("my test"); + when(reportEntry.getNameWithGroup()).thenReturn("name with group"); + when(reportEntry.getSourceName()).thenReturn("pkg.MyTest"); + when(reportEntry.getSourceText()).thenReturn("display name"); + when(reportEntry.getStackTraceWriter()).thenReturn(stackTraceWriter); + + ForkClient client = new ForkClient(factory, notifiableTestStream, 0); + SimpleReportEntry testStarted = new SimpleReportEntry( + NORMAL_RUN, 1L, reportEntry.getSourceName(), reportEntry.getSourceText(), null, null); + client.handleEvent(new TestStartingEvent(testStarted)); + + assertThat(client.testsInProgress()).hasSize(1).contains("pkg.MyTest"); + + client.handleEvent(new TestErrorEvent(reportEntry)); + + verifyZeroInteractions(notifiableTestStream); + verify(factory).createTestReportListener(); + verifyNoMoreInteractions(factory); + assertThat(client.getReporter()).isNotNull(); + assertThat(receiver.getEvents()).hasSize(2); + assertThat(receiver.getEvents()).contains(TEST_STARTING, TEST_ERROR); + assertThat(receiver.getData()).hasSize(2); + assertThat(((ReportEntry) receiver.getData().get(0)).getSourceName()).isEqualTo("pkg.MyTest"); + assertThat(((ReportEntry) receiver.getData().get(0)).getSourceText()).isEqualTo("display name"); + assertThat(((ReportEntry) receiver.getData().get(0)).getName()).isNull(); + assertThat(((ReportEntry) receiver.getData().get(1)).getSourceName()).isEqualTo("pkg.MyTest"); + assertThat(((ReportEntry) receiver.getData().get(1)).getSourceText()).isEqualTo("display name"); + assertThat(((ReportEntry) receiver.getData().get(1)).getName()).isEqualTo("my test"); + assertThat(((ReportEntry) receiver.getData().get(1)).getElapsed()).isEqualTo(ELAPSED_TIME); + assertThat(((ReportEntry) receiver.getData().get(1)).getMessage()).isEqualTo("some test"); + assertThat(((ReportEntry) receiver.getData().get(1)).getGroup()).isEqualTo("this group"); + assertThat(((ReportEntry) receiver.getData().get(1)).getStackTraceWriter()) .isNotNull(); - assertThat( ( (ReportEntry) receiver.getData().get( 1 ) ) - .getStackTraceWriter().getThrowable().getLocalizedMessage() ) - .isEqualTo( "msg" ); - assertThat( ( (ReportEntry) receiver.getData().get( 1 ) ).getStackTraceWriter().smartTrimmedStackTrace() ) - .isEqualTo( smartStackTrace ); - assertThat( ( (ReportEntry) receiver.getData().get( 1 ) ).getStackTraceWriter().writeTraceToString() ) - .isEqualTo( stackTrace ); - assertThat( ( (ReportEntry) receiver.getData().get( 1 ) ).getStackTraceWriter().writeTrimmedTraceToString() ) - .isEqualTo( trimmedStackTrace ); - assertThat( client.isSaidGoodBye() ) - .isFalse(); - assertThat( client.isErrorInFork() ) - .isFalse(); - assertThat( client.getErrorInFork() ) - .isNull(); - assertThat( client.hadTimeout() ) - .isFalse(); - assertThat( client.hasTestsInProgress() ) - .isFalse(); - assertThat( client.testsInProgress() ) - .isEmpty(); - assertThat( client.getTestVmSystemProperties() ) - .isEmpty(); - assertThat( client.getTestVmSystemProperties() ) - .isEmpty(); - assertThat( client.getDefaultReporterFactory() ) - .isSameAs( factory ); + assertThat(((ReportEntry) receiver.getData().get(1)) + .getStackTraceWriter() + .getThrowable() + .getLocalizedMessage()) + .isEqualTo("msg"); + assertThat(((ReportEntry) receiver.getData().get(1)) + .getStackTraceWriter() + .smartTrimmedStackTrace()) + .isEqualTo(smartStackTrace); + assertThat(((ReportEntry) receiver.getData().get(1)) + .getStackTraceWriter() + .writeTraceToString()) + .isEqualTo(stackTrace); + assertThat(((ReportEntry) receiver.getData().get(1)) + .getStackTraceWriter() + .writeTrimmedTraceToString()) + .isEqualTo(trimmedStackTrace); + assertThat(client.isSaidGoodBye()).isFalse(); + assertThat(client.isErrorInFork()).isFalse(); + assertThat(client.getErrorInFork()).isNull(); + assertThat(client.hadTimeout()).isFalse(); + assertThat(client.hasTestsInProgress()).isFalse(); + assertThat(client.testsInProgress()).isEmpty(); + assertThat(client.getTestVmSystemProperties()).isEmpty(); + assertThat(client.getTestVmSystemProperties()).isEmpty(); + assertThat(client.getDefaultReporterFactory()).isSameAs(factory); } @Test - public void shouldSendTestAssumptionFailure() - { - String cwd = System.getProperty( "user.dir" ); - File target = new File( cwd, "target" ); - DefaultReporterFactory factory = mock( DefaultReporterFactory.class ); - when( factory.getReportsDirectory() ) - .thenReturn( new File( target, "surefire-reports" ) ); + public void shouldSendTestAssumptionFailure() { + String cwd = System.getProperty("user.dir"); + File target = new File(cwd, "target"); + DefaultReporterFactory factory = mock(DefaultReporterFactory.class); + when(factory.getReportsDirectory()).thenReturn(new File(target, "surefire-reports")); MockReporter receiver = new MockReporter(); - when( factory.createTestReportListener() ) - .thenReturn( receiver ); - NotifiableTestStream notifiableTestStream = mock( NotifiableTestStream.class ); + when(factory.createTestReportListener()).thenReturn(receiver); + NotifiableTestStream notifiableTestStream = mock(NotifiableTestStream.class); final String exceptionMessage = "msg"; final String smartStackTrace = "MyTest:86 >> Error"; final String stackTrace = "trace line 1\ntrace line 2"; final String trimmedStackTrace = "trace line 1"; - SafeThrowable safeThrowable = new SafeThrowable( new Exception( exceptionMessage ) ); - StackTraceWriter stackTraceWriter = mock( StackTraceWriter.class ); - when( stackTraceWriter.getThrowable() ).thenReturn( safeThrowable ); - when( stackTraceWriter.smartTrimmedStackTrace() ).thenReturn( smartStackTrace ); - when( stackTraceWriter.writeTrimmedTraceToString() ).thenReturn( trimmedStackTrace ); - when( stackTraceWriter.writeTraceToString() ).thenReturn( stackTrace ); - - ReportEntry reportEntry = mock( ReportEntry.class ); - when( reportEntry.getRunMode() ).thenReturn( NORMAL_RUN ); - when( reportEntry.getTestRunId() ).thenReturn( 1L ); - when( reportEntry.getElapsed() ).thenReturn( ELAPSED_TIME ); - when( reportEntry.getGroup() ).thenReturn( "this group" ); - when( reportEntry.getMessage() ).thenReturn( "some test" ); - when( reportEntry.getName() ).thenReturn( "my test" ); - when( reportEntry.getNameText() ).thenReturn( "display name" ); - when( reportEntry.getNameWithGroup() ).thenReturn( "name with group" ); - when( reportEntry.getSourceName() ).thenReturn( "pkg.MyTest" ); - when( reportEntry.getStackTraceWriter() ).thenReturn( stackTraceWriter ); - - ForkClient client = new ForkClient( factory, notifiableTestStream, 0 ); + SafeThrowable safeThrowable = new SafeThrowable(new Exception(exceptionMessage)); + StackTraceWriter stackTraceWriter = mock(StackTraceWriter.class); + when(stackTraceWriter.getThrowable()).thenReturn(safeThrowable); + when(stackTraceWriter.smartTrimmedStackTrace()).thenReturn(smartStackTrace); + when(stackTraceWriter.writeTrimmedTraceToString()).thenReturn(trimmedStackTrace); + when(stackTraceWriter.writeTraceToString()).thenReturn(stackTrace); + + ReportEntry reportEntry = mock(ReportEntry.class); + when(reportEntry.getRunMode()).thenReturn(NORMAL_RUN); + when(reportEntry.getTestRunId()).thenReturn(1L); + when(reportEntry.getElapsed()).thenReturn(ELAPSED_TIME); + when(reportEntry.getGroup()).thenReturn("this group"); + when(reportEntry.getMessage()).thenReturn("some test"); + when(reportEntry.getName()).thenReturn("my test"); + when(reportEntry.getNameText()).thenReturn("display name"); + when(reportEntry.getNameWithGroup()).thenReturn("name with group"); + when(reportEntry.getSourceName()).thenReturn("pkg.MyTest"); + when(reportEntry.getStackTraceWriter()).thenReturn(stackTraceWriter); + + ForkClient client = new ForkClient(factory, notifiableTestStream, 0); SimpleReportEntry testStarted = - new SimpleReportEntry( NORMAL_RUN, 1L, reportEntry.getSourceName(), null, null, null ); - client.handleEvent( new TestStartingEvent( testStarted ) ); - - assertThat( client.testsInProgress() ) - .hasSize( 1 ) - .contains( "pkg.MyTest" ); - - client.handleEvent( new TestAssumptionFailureEvent( reportEntry ) ); - - verifyZeroInteractions( notifiableTestStream ); - verify( factory ).createTestReportListener(); - verifyNoMoreInteractions( factory ); - assertThat( client.getReporter() ) - .isNotNull(); - assertThat( receiver.getEvents() ) - .hasSize( 2 ); - assertThat( receiver.getEvents() ) - .contains( TEST_STARTING, TEST_ASSUMPTION_FAIL ); - assertThat( receiver.getData() ) - .hasSize( 2 ); - assertThat( ( (ReportEntry) receiver.getData().get( 0 ) ).getSourceName() ) - .isEqualTo( "pkg.MyTest" ); - assertThat( ( (ReportEntry) receiver.getData().get( 0 ) ).getSourceText() ) - .isNull(); - assertThat( ( (ReportEntry) receiver.getData().get( 0 ) ).getName() ) - .isNull(); - assertThat( ( (ReportEntry) receiver.getData().get( 1 ) ).getSourceName() ) - .isEqualTo( "pkg.MyTest" ); - assertThat( ( (ReportEntry) receiver.getData().get( 1 ) ).getName() ) - .isEqualTo( "my test" ); - assertThat( ( (ReportEntry) receiver.getData().get( 1 ) ).getNameText() ) - .isEqualTo( "display name" ); - assertThat( ( (ReportEntry) receiver.getData().get( 1 ) ).getElapsed() ) - .isEqualTo( ELAPSED_TIME ); - assertThat( ( (ReportEntry) receiver.getData().get( 1 ) ).getMessage() ) - .isEqualTo( "some test" ); - assertThat( ( (ReportEntry) receiver.getData().get( 1 ) ).getGroup() ) - .isEqualTo( "this group" ); - assertThat( ( (ReportEntry) receiver.getData().get( 1 ) ).getStackTraceWriter() ) + new SimpleReportEntry(NORMAL_RUN, 1L, reportEntry.getSourceName(), null, null, null); + client.handleEvent(new TestStartingEvent(testStarted)); + + assertThat(client.testsInProgress()).hasSize(1).contains("pkg.MyTest"); + + client.handleEvent(new TestAssumptionFailureEvent(reportEntry)); + + verifyZeroInteractions(notifiableTestStream); + verify(factory).createTestReportListener(); + verifyNoMoreInteractions(factory); + assertThat(client.getReporter()).isNotNull(); + assertThat(receiver.getEvents()).hasSize(2); + assertThat(receiver.getEvents()).contains(TEST_STARTING, TEST_ASSUMPTION_FAIL); + assertThat(receiver.getData()).hasSize(2); + assertThat(((ReportEntry) receiver.getData().get(0)).getSourceName()).isEqualTo("pkg.MyTest"); + assertThat(((ReportEntry) receiver.getData().get(0)).getSourceText()).isNull(); + assertThat(((ReportEntry) receiver.getData().get(0)).getName()).isNull(); + assertThat(((ReportEntry) receiver.getData().get(1)).getSourceName()).isEqualTo("pkg.MyTest"); + assertThat(((ReportEntry) receiver.getData().get(1)).getName()).isEqualTo("my test"); + assertThat(((ReportEntry) receiver.getData().get(1)).getNameText()).isEqualTo("display name"); + assertThat(((ReportEntry) receiver.getData().get(1)).getElapsed()).isEqualTo(ELAPSED_TIME); + assertThat(((ReportEntry) receiver.getData().get(1)).getMessage()).isEqualTo("some test"); + assertThat(((ReportEntry) receiver.getData().get(1)).getGroup()).isEqualTo("this group"); + assertThat(((ReportEntry) receiver.getData().get(1)).getStackTraceWriter()) .isNotNull(); - assertThat( ( (ReportEntry) receiver.getData().get( 1 ) ) - .getStackTraceWriter().getThrowable().getLocalizedMessage() ) - .isEqualTo( "msg" ); - assertThat( ( (ReportEntry) receiver.getData().get( 1 ) ).getStackTraceWriter().smartTrimmedStackTrace() ) - .isEqualTo( smartStackTrace ); - assertThat( ( (ReportEntry) receiver.getData().get( 1 ) ).getStackTraceWriter().writeTraceToString() ) - .isEqualTo( stackTrace ); - assertThat( ( (ReportEntry) receiver.getData().get( 1 ) ).getStackTraceWriter().writeTrimmedTraceToString() ) - .isEqualTo( trimmedStackTrace ); - assertThat( client.isSaidGoodBye() ) - .isFalse(); - assertThat( client.isErrorInFork() ) - .isFalse(); - assertThat( client.getErrorInFork() ) - .isNull(); - assertThat( client.hadTimeout() ) - .isFalse(); - assertThat( client.hasTestsInProgress() ) - .isFalse(); - assertThat( client.testsInProgress() ) - .isEmpty(); - assertThat( client.getTestVmSystemProperties() ) - .isEmpty(); - assertThat( client.getTestVmSystemProperties() ) - .isEmpty(); - assertThat( client.getDefaultReporterFactory() ) - .isSameAs( factory ); + assertThat(((ReportEntry) receiver.getData().get(1)) + .getStackTraceWriter() + .getThrowable() + .getLocalizedMessage()) + .isEqualTo("msg"); + assertThat(((ReportEntry) receiver.getData().get(1)) + .getStackTraceWriter() + .smartTrimmedStackTrace()) + .isEqualTo(smartStackTrace); + assertThat(((ReportEntry) receiver.getData().get(1)) + .getStackTraceWriter() + .writeTraceToString()) + .isEqualTo(stackTrace); + assertThat(((ReportEntry) receiver.getData().get(1)) + .getStackTraceWriter() + .writeTrimmedTraceToString()) + .isEqualTo(trimmedStackTrace); + assertThat(client.isSaidGoodBye()).isFalse(); + assertThat(client.isErrorInFork()).isFalse(); + assertThat(client.getErrorInFork()).isNull(); + assertThat(client.hadTimeout()).isFalse(); + assertThat(client.hasTestsInProgress()).isFalse(); + assertThat(client.testsInProgress()).isEmpty(); + assertThat(client.getTestVmSystemProperties()).isEmpty(); + assertThat(client.getTestVmSystemProperties()).isEmpty(); + assertThat(client.getDefaultReporterFactory()).isSameAs(factory); } - private static class EH implements EventHandler - { - private final BlockingQueue cache = new LinkedBlockingQueue<>( 1 ); + private static class EH implements EventHandler { + private final BlockingQueue cache = new LinkedBlockingQueue<>(1); - Event pullEvent() throws InterruptedException - { - return cache.poll( 1, TimeUnit.MINUTES ); + Event pullEvent() throws InterruptedException { + return cache.poll(1, TimeUnit.MINUTES); } - int sizeOfEventCache() - { + int sizeOfEventCache() { return cache.size(); } @Override - public void handleEvent( @Nonnull Event event ) - { - cache.add( event ); + public void handleEvent(@Nonnull Event event) { + cache.add(event); } } /** * Threadsafe impl. Mockito and Powermock are not thread-safe. */ - private static class ForkNodeArgumentsMock implements ForkNodeArguments - { + private static class ForkNodeArgumentsMock implements ForkNodeArguments { private final ConcurrentLinkedQueue dumpStreamText = new ConcurrentLinkedQueue<>(); private final ConcurrentLinkedQueue logWarningAtEnd = new ConcurrentLinkedQueue<>(); private final ConsoleLogger logger; private final File dumpStreamTextFile; - ForkNodeArgumentsMock( ConsoleLogger logger, File dumpStreamTextFile ) - { + ForkNodeArgumentsMock(ConsoleLogger logger, File dumpStreamTextFile) { this.logger = logger; this.dumpStreamTextFile = dumpStreamTextFile; } @Nonnull @Override - public String getSessionId() - { + public String getSessionId() { throw new UnsupportedOperationException(); } @Override - public int getForkChannelId() - { + public int getForkChannelId() { return 0; } @Nonnull @Override - public File dumpStreamText( @Nonnull String text ) - { - dumpStreamText.add( text ); + public File dumpStreamText(@Nonnull String text) { + dumpStreamText.add(text); return dumpStreamTextFile; } @Nonnull @Override - public File dumpStreamException( @Nonnull Throwable t ) - { + public File dumpStreamException(@Nonnull Throwable t) { throw new UnsupportedOperationException(); } @Override - public void logWarningAtEnd( @Nonnull String text ) - { - logWarningAtEnd.add( text ); + public void logWarningAtEnd(@Nonnull String text) { + logWarningAtEnd.add(text); } @Nonnull @Override - public ConsoleLogger getConsoleLogger() - { + public ConsoleLogger getConsoleLogger() { return logger; } @Nonnull @Override - public Object getConsoleLock() - { + public Object getConsoleLock() { return logger; } - boolean isCalled() - { + boolean isCalled() { return !dumpStreamText.isEmpty() || !logWarningAtEnd.isEmpty(); } @Override - public File getEventStreamBinaryFile() - { + public File getEventStreamBinaryFile() { return null; } @Override - public File getCommandStreamBinaryFile() - { + public File getCommandStreamBinaryFile() { return null; } } @@ -1922,8 +1508,7 @@ public File getCommandStreamBinaryFile() /** * Threadsafe impl. Mockito and Powermock are not thread-safe. */ - private static class ConsoleLoggerMock implements ConsoleLogger - { + private static class ConsoleLoggerMock implements ConsoleLogger { final ConcurrentLinkedQueue debug = new ConcurrentLinkedQueue<>(); final ConcurrentLinkedQueue info = new ConcurrentLinkedQueue<>(); final ConcurrentLinkedQueue error = new ConcurrentLinkedQueue<>(); @@ -1935,8 +1520,7 @@ private static class ConsoleLoggerMock implements ConsoleLogger private volatile boolean isDebugEnabledCalled; private volatile boolean isInfoEnabledCalled; - ConsoleLoggerMock( boolean isDebug, boolean isInfo, boolean isWarning, boolean isError ) - { + ConsoleLoggerMock(boolean isDebug, boolean isInfo, boolean isWarning, boolean isError) { this.isDebug = isDebug; this.isInfo = isInfo; this.isWarning = isWarning; @@ -1944,76 +1528,65 @@ private static class ConsoleLoggerMock implements ConsoleLogger } @Override - public synchronized boolean isDebugEnabled() - { + public synchronized boolean isDebugEnabled() { isDebugEnabledCalled = true; called = true; return isDebug; } @Override - public synchronized void debug( String message ) - { - debug.add( message ); + public synchronized void debug(String message) { + debug.add(message); called = true; } @Override - public synchronized boolean isInfoEnabled() - { + public synchronized boolean isInfoEnabled() { isInfoEnabledCalled = true; called = true; return isInfo; } @Override - public synchronized void info( String message ) - { - info.add( message ); + public synchronized void info(String message) { + info.add(message); called = true; } @Override - public synchronized boolean isWarnEnabled() - { + public synchronized boolean isWarnEnabled() { called = true; return isWarning; } @Override - public synchronized void warning( String message ) - { + public synchronized void warning(String message) { called = true; } @Override - public synchronized boolean isErrorEnabled() - { + public synchronized boolean isErrorEnabled() { called = true; return isError; } @Override - public synchronized void error( String message ) - { - error.add( message ); + public synchronized void error(String message) { + error.add(message); called = true; } @Override - public synchronized void error( String message, Throwable t ) - { + public synchronized void error(String message, Throwable t) { called = true; } @Override - public synchronized void error( Throwable t ) - { + public synchronized void error(Throwable t) { called = true; } - synchronized boolean isCalled() - { + synchronized boolean isCalled() { return called; } } diff --git a/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/booterclient/output/MultipleFailureExceptionTest.java b/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/booterclient/output/MultipleFailureExceptionTest.java index 82c2f83666..65f84c066a 100644 --- a/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/booterclient/output/MultipleFailureExceptionTest.java +++ b/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/booterclient/output/MultipleFailureExceptionTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire.booterclient.output; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.surefire.booterclient.output; import java.io.IOException; @@ -28,32 +27,23 @@ /** * Tests for {@code MultipleFailureException}. */ -public class MultipleFailureExceptionTest -{ +public class MultipleFailureExceptionTest { @Test - public void test() - { + public void test() { MultipleFailureException e = new MultipleFailureException(); - NullPointerException suppressed1 = new NullPointerException( "field is null" ); - IOException suppressed2 = new IOException( "read error" ); - e.addException( suppressed1 ); - e.addException( suppressed2 ); + NullPointerException suppressed1 = new NullPointerException("field is null"); + IOException suppressed2 = new IOException("read error"); + e.addException(suppressed1); + e.addException(suppressed2); - assertThat( e.getMessage() ) - .contains( "field is null" ) - .contains( "read error" ); + assertThat(e.getMessage()).contains("field is null").contains("read error"); - assertThat( e.getLocalizedMessage() ) - .contains( "field is null" ) - .contains( "read error" ); + assertThat(e.getLocalizedMessage()).contains("field is null").contains("read error"); - assertThat( e.getSuppressed() ) - .hasSize( 2 ); + assertThat(e.getSuppressed()).hasSize(2); - assertThat( e.getSuppressed() ) - .contains( suppressed1, suppressed2 ); + assertThat(e.getSuppressed()).contains(suppressed1, suppressed2); - assertThat( e.hasNestedExceptions() ) - .isTrue(); + assertThat(e.hasNestedExceptions()).isTrue(); } } diff --git a/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/booterclient/output/ThreadedStreamConsumerTest.java b/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/booterclient/output/ThreadedStreamConsumerTest.java index 804b76d711..e43b34fb80 100644 --- a/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/booterclient/output/ThreadedStreamConsumerTest.java +++ b/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/booterclient/output/ThreadedStreamConsumerTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire.booterclient.output; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,13 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.surefire.booterclient.output; + +import javax.annotation.Nonnull; + +import java.util.concurrent.Callable; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.FutureTask; import org.apache.maven.plugin.surefire.booterclient.output.ThreadedStreamConsumer.QueueSynchronizer; import org.apache.maven.surefire.api.event.Event; @@ -25,11 +30,6 @@ import org.apache.maven.surefire.extensions.EventHandler; import org.junit.Test; -import javax.annotation.Nonnull; -import java.util.concurrent.Callable; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.FutureTask; - import static java.util.concurrent.TimeUnit.SECONDS; import static org.apache.maven.surefire.api.report.RunMode.NORMAL_RUN; import static org.assertj.core.api.Assertions.assertThat; @@ -37,115 +37,96 @@ /** * */ -@SuppressWarnings( "checkstyle:magicnumber" ) -public class ThreadedStreamConsumerTest -{ +@SuppressWarnings("checkstyle:magicnumber") +public class ThreadedStreamConsumerTest { @Test - public void testQueueSynchronizer() throws Exception - { - final CountDownLatch countDown = new CountDownLatch( 5_000_000 ); - final QueueSynchronizer sync = new QueueSynchronizer<>( 8 * 1024, null ); + public void testQueueSynchronizer() throws Exception { + final CountDownLatch countDown = new CountDownLatch(5_000_000); + final QueueSynchronizer sync = new QueueSynchronizer<>(8 * 1024, null); - Thread t = new Thread() - { + Thread t = new Thread() { @Override - public void run() - { - while ( true ) - { - try - { + public void run() { + while (true) { + try { sync.awaitNext(); countDown.countDown(); - } - catch ( InterruptedException e ) - { - throw new IllegalStateException( e ); + } catch (InterruptedException e) { + throw new IllegalStateException(e); } } } }; - t.setDaemon( true ); + t.setDaemon(true); t.start(); - SECONDS.sleep( 1 ); + SECONDS.sleep(1); System.gc(); - SECONDS.sleep( 2 ); + SECONDS.sleep(2); long t1 = System.currentTimeMillis(); - for ( int i = 0; i < 5_000_000; i++ ) - { - sync.pushNext( i ); + for (int i = 0; i < 5_000_000; i++) { + sync.pushNext(i); } - assertThat( countDown.await( 3L, SECONDS ) ) - .isTrue(); + assertThat(countDown.await(3L, SECONDS)).isTrue(); long t2 = System.currentTimeMillis(); - System.out.println( ( t2 - t1 ) + " millis in testQueueSynchronizer()" ); + System.out.println((t2 - t1) + " millis in testQueueSynchronizer()"); } @Test - public void testThreadedStreamConsumer() throws Exception - { - final CountDownLatch countDown = new CountDownLatch( 5_000_000 ); - EventHandler handler = new EventHandler() - { + public void testThreadedStreamConsumer() throws Exception { + final CountDownLatch countDown = new CountDownLatch(5_000_000); + EventHandler handler = new EventHandler() { @Override - public void handleEvent( @Nonnull Event event ) - { + public void handleEvent(@Nonnull Event event) { countDown.countDown(); } }; - ThreadedStreamConsumer streamConsumer = new ThreadedStreamConsumer( handler ); + ThreadedStreamConsumer streamConsumer = new ThreadedStreamConsumer(handler); - SECONDS.sleep( 1 ); + SECONDS.sleep(1); System.gc(); - SECONDS.sleep( 2 ); + SECONDS.sleep(2); long t1 = System.currentTimeMillis(); - Event event = new StandardStreamOutWithNewLineEvent( NORMAL_RUN, 1L, "" ); - for ( int i = 0; i < 5_000_000; i++ ) - { - streamConsumer.handleEvent( event ); + Event event = new StandardStreamOutWithNewLineEvent(NORMAL_RUN, 1L, ""); + for (int i = 0; i < 5_000_000; i++) { + streamConsumer.handleEvent(event); } - assertThat( countDown.await( 3L, SECONDS ) ) - .isTrue(); + assertThat(countDown.await(3L, SECONDS)).isTrue(); long t2 = System.currentTimeMillis(); - System.out.println( ( t2 - t1 ) + " millis in testThreadedStreamConsumer()" ); + System.out.println((t2 - t1) + " millis in testThreadedStreamConsumer()"); streamConsumer.close(); } @Test - public void testBasicStatus() throws Exception - { - final QueueSynchronizer sync = new QueueSynchronizer<>( 2, null ); - sync.pushNext( "1" ); - sync.pushNext( "2" ); + public void testBasicStatus() throws Exception { + final QueueSynchronizer sync = new QueueSynchronizer<>(2, null); + sync.pushNext("1"); + sync.pushNext("2"); String s1 = sync.awaitNext(); String s2 = sync.awaitNext(); - assertThat( s1 ).isEqualTo( "1" ); - assertThat( s2 ).isEqualTo( "2" ); - FutureTask future = new FutureTask<>( new Callable() - { + assertThat(s1).isEqualTo("1"); + assertThat(s2).isEqualTo("2"); + FutureTask future = new FutureTask<>(new Callable() { @Override - public Void call() throws Exception - { + public Void call() throws Exception { sync.awaitNext(); return null; } - } ); - Thread t = new Thread( future ); - t.setDaemon( true ); + }); + Thread t = new Thread(future); + t.setDaemon(true); t.start(); - SECONDS.sleep( 3L ); - assertThat( t.getState() ) - .isEqualTo( Thread.State.WAITING ); + SECONDS.sleep(3L); + assertThat(t.getState()).isEqualTo(Thread.State.WAITING); } } diff --git a/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/extensions/ConsoleOutputReporterTest.java b/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/extensions/ConsoleOutputReporterTest.java index 0fb79da712..0d1cb87a20 100644 --- a/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/extensions/ConsoleOutputReporterTest.java +++ b/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/extensions/ConsoleOutputReporterTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire.extensions; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.surefire.extensions; import java.io.File; import java.io.PrintStream; @@ -35,141 +34,103 @@ /** * tests for {@link SurefireConsoleOutputReporter} and {@link JUnit5ConsoleOutputReporter}. */ -public class ConsoleOutputReporterTest -{ +public class ConsoleOutputReporterTest { @Test - public void shouldCloneConsoleReporter() - { + public void shouldCloneConsoleReporter() { SurefireConsoleOutputReporter extension = new SurefireConsoleOutputReporter(); - extension.setDisable( true ); - extension.setEncoding( "ISO-8859-1" ); + extension.setDisable(true); + extension.setEncoding("ISO-8859-1"); ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); - Object clone = extension.clone( classLoader ); - assertThat( clone ) - .isNotSameAs( extension ); - assertThat( clone ) - .isInstanceOf( SurefireConsoleOutputReporter.class ); - assertThat( clone.toString() ) - .isEqualTo( "SurefireConsoleOutputReporter{disable=true, encoding=ISO-8859-1}" ); - assertThat( ( (SurefireConsoleOutputReporter) clone ).isDisable() ) - .isTrue(); - assertThat( ( (SurefireConsoleOutputReporter) clone ).getEncoding() ) - .isEqualTo( "ISO-8859-1" ); + Object clone = extension.clone(classLoader); + assertThat(clone).isNotSameAs(extension); + assertThat(clone).isInstanceOf(SurefireConsoleOutputReporter.class); + assertThat(clone.toString()).isEqualTo("SurefireConsoleOutputReporter{disable=true, encoding=ISO-8859-1}"); + assertThat(((SurefireConsoleOutputReporter) clone).isDisable()).isTrue(); + assertThat(((SurefireConsoleOutputReporter) clone).getEncoding()).isEqualTo("ISO-8859-1"); } @Test - public void shouldAssertToStringConsoleReporter() - { + public void shouldAssertToStringConsoleReporter() { SurefireConsoleOutputReporter extension = new SurefireConsoleOutputReporter(); - assertThat( extension.toString() ) - .isEqualTo( "SurefireConsoleOutputReporter{disable=false, encoding=UTF-8}" ); + assertThat(extension.toString()).isEqualTo("SurefireConsoleOutputReporter{disable=false, encoding=UTF-8}"); } @Test - public void shouldCreateConsoleListener() - { + public void shouldCreateConsoleListener() { ConsoleOutputReporter extension = new SurefireConsoleOutputReporter(); - ConsoleOutputReportEventListener listener1 = extension.createListener( System.out, System.err ); - assertThat( listener1 ) - .isInstanceOf( DirectConsoleOutput.class ); - assertThat( (PrintStream) getInternalState( listener1, "out" ) ) - .isSameAs( System.out ); - assertThat( (PrintStream) getInternalState( listener1, "err" ) ) - .isSameAs( System.err ); + ConsoleOutputReportEventListener listener1 = extension.createListener(System.out, System.err); + assertThat(listener1).isInstanceOf(DirectConsoleOutput.class); + assertThat((PrintStream) getInternalState(listener1, "out")).isSameAs(System.out); + assertThat((PrintStream) getInternalState(listener1, "err")).isSameAs(System.err); - File target = new File( System.getProperty( "user.dir" ), "target" ); - File reportsDirectory = new File( target, "surefire-reports" ); + File target = new File(System.getProperty("user.dir"), "target"); + File reportsDirectory = new File(target, "surefire-reports"); String reportNameSuffix = "suffix"; boolean usePhrasedFileName = false; Integer forkNumber = 1; String encoding = "ISO-8859-2"; - extension.setEncoding( encoding ); + extension.setEncoding(encoding); ConsoleOutputReportEventListener listener2 = - extension.createListener( reportsDirectory, reportNameSuffix, forkNumber ); - assertThat( listener2 ) - .isInstanceOf( ConsoleOutputFileReporter.class ); - assertThat( (File) getInternalState( listener2, "reportsDirectory" ) ) - .isSameAs( reportsDirectory ); - assertThat( (String) getInternalState( listener2, "reportNameSuffix" ) ) - .isSameAs( reportNameSuffix ); - assertThat( (boolean) getInternalState( listener2, "usePhrasedFileName" ) ) - .isEqualTo( usePhrasedFileName ); - assertThat( (Integer) getInternalState( listener2, "forkNumber" ) ) - .isSameAs( forkNumber ); - assertThat( (String) getInternalState( listener2, "encoding" ) ) - .isSameAs( encoding ); - assertThat( (String) getInternalState( listener2, "reportEntryName" ) ) - .isNull(); + extension.createListener(reportsDirectory, reportNameSuffix, forkNumber); + assertThat(listener2).isInstanceOf(ConsoleOutputFileReporter.class); + assertThat((File) getInternalState(listener2, "reportsDirectory")).isSameAs(reportsDirectory); + assertThat((String) getInternalState(listener2, "reportNameSuffix")).isSameAs(reportNameSuffix); + assertThat((boolean) getInternalState(listener2, "usePhrasedFileName")).isEqualTo(usePhrasedFileName); + assertThat((Integer) getInternalState(listener2, "forkNumber")).isSameAs(forkNumber); + assertThat((String) getInternalState(listener2, "encoding")).isSameAs(encoding); + assertThat((String) getInternalState(listener2, "reportEntryName")).isNull(); } @Test - public void shouldCloneJUnit5ConsoleReporter() - { + public void shouldCloneJUnit5ConsoleReporter() { JUnit5ConsoleOutputReporter extension = new JUnit5ConsoleOutputReporter(); - extension.setDisable( true ); - extension.setEncoding( "ISO-8859-1" ); - extension.setUsePhrasedFileName( true ); + extension.setDisable(true); + extension.setEncoding("ISO-8859-1"); + extension.setUsePhrasedFileName(true); ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); - Object clone = extension.clone( classLoader ); - assertThat( clone ) - .isNotSameAs( extension ); - assertThat( clone ) - .isInstanceOf( JUnit5ConsoleOutputReporter.class ); - assertThat( clone.toString() ).isEqualTo( - "JUnit5ConsoleOutputReporter{disable=true, encoding=ISO-8859-1, usePhrasedFileName=true}" ); - assertThat( ( (JUnit5ConsoleOutputReporter) clone ).isDisable() ) - .isTrue(); - assertThat( ( (JUnit5ConsoleOutputReporter) clone ).getEncoding() ) - .isEqualTo( "ISO-8859-1" ); - assertThat( ( (JUnit5ConsoleOutputReporter) clone ).isUsePhrasedFileName() ) - .isTrue(); + Object clone = extension.clone(classLoader); + assertThat(clone).isNotSameAs(extension); + assertThat(clone).isInstanceOf(JUnit5ConsoleOutputReporter.class); + assertThat(clone.toString()) + .isEqualTo("JUnit5ConsoleOutputReporter{disable=true, encoding=ISO-8859-1, usePhrasedFileName=true}"); + assertThat(((JUnit5ConsoleOutputReporter) clone).isDisable()).isTrue(); + assertThat(((JUnit5ConsoleOutputReporter) clone).getEncoding()).isEqualTo("ISO-8859-1"); + assertThat(((JUnit5ConsoleOutputReporter) clone).isUsePhrasedFileName()).isTrue(); } @Test - public void shouldAssertToStringJUnit5ConsoleReporter() - { + public void shouldAssertToStringJUnit5ConsoleReporter() { JUnit5ConsoleOutputReporter extension = new JUnit5ConsoleOutputReporter(); - assertThat( extension.toString() ) - .isEqualTo( "JUnit5ConsoleOutputReporter{disable=false, encoding=UTF-8, usePhrasedFileName=false}" ); + assertThat(extension.toString()) + .isEqualTo("JUnit5ConsoleOutputReporter{disable=false, encoding=UTF-8, usePhrasedFileName=false}"); } @Test - public void shouldCreateJUnit5ConsoleListener() - { + public void shouldCreateJUnit5ConsoleListener() { JUnit5ConsoleOutputReporter extension = new JUnit5ConsoleOutputReporter(); - ConsoleOutputReportEventListener listener1 = extension.createListener( System.out, System.err ); - assertThat( listener1 ) - .isInstanceOf( DirectConsoleOutput.class ); - assertThat( (PrintStream) getInternalState( listener1, "out" ) ) - .isSameAs( System.out ); - assertThat( (PrintStream) getInternalState( listener1, "err" ) ) - .isSameAs( System.err ); + ConsoleOutputReportEventListener listener1 = extension.createListener(System.out, System.err); + assertThat(listener1).isInstanceOf(DirectConsoleOutput.class); + assertThat((PrintStream) getInternalState(listener1, "out")).isSameAs(System.out); + assertThat((PrintStream) getInternalState(listener1, "err")).isSameAs(System.err); - File target = new File( System.getProperty( "user.dir" ), "target" ); - File reportsDirectory = new File( target, "surefire-reports" ); + File target = new File(System.getProperty("user.dir"), "target"); + File reportsDirectory = new File(target, "surefire-reports"); String reportNameSuffix = "suffix"; boolean usePhrasedFileName = true; Integer forkNumber = 1; String encoding = "ISO-8859-1"; - extension.setEncoding( encoding ); - extension.setUsePhrasedFileName( usePhrasedFileName ); + extension.setEncoding(encoding); + extension.setUsePhrasedFileName(usePhrasedFileName); ConsoleOutputReportEventListener listener2 = - extension.createListener( reportsDirectory, reportNameSuffix, forkNumber ); - assertThat( listener2 ) - .isInstanceOf( ConsoleOutputFileReporter.class ); - assertThat( (File) getInternalState( listener2, "reportsDirectory" ) ) - .isSameAs( reportsDirectory ); - assertThat( (String) getInternalState( listener2, "reportNameSuffix" ) ) - .isSameAs( reportNameSuffix ); - assertThat( (boolean) getInternalState( listener2, "usePhrasedFileName" ) ) - .isEqualTo( usePhrasedFileName ); - assertThat( (Integer) getInternalState( listener2, "forkNumber" ) ) - .isSameAs( forkNumber ); - assertThat( (String) getInternalState( listener2, "encoding" ) ) - .isSameAs( encoding ); - assertThat( (String) getInternalState( listener2, "reportEntryName" ) ) - .isNull(); + extension.createListener(reportsDirectory, reportNameSuffix, forkNumber); + assertThat(listener2).isInstanceOf(ConsoleOutputFileReporter.class); + assertThat((File) getInternalState(listener2, "reportsDirectory")).isSameAs(reportsDirectory); + assertThat((String) getInternalState(listener2, "reportNameSuffix")).isSameAs(reportNameSuffix); + assertThat((boolean) getInternalState(listener2, "usePhrasedFileName")).isEqualTo(usePhrasedFileName); + assertThat((Integer) getInternalState(listener2, "forkNumber")).isSameAs(forkNumber); + assertThat((String) getInternalState(listener2, "encoding")).isSameAs(encoding); + assertThat((String) getInternalState(listener2, "reportEntryName")).isNull(); } } diff --git a/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/extensions/E2ETest.java b/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/extensions/E2ETest.java index 09040459e4..b5693ab254 100644 --- a/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/extensions/E2ETest.java +++ b/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/extensions/E2ETest.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire.extensions; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.surefire.extensions; import javax.annotation.Nonnull; @@ -63,330 +62,273 @@ /** * Simulates the End To End use case where Maven process and Surefire process communicate using the TCP/IP protocol. */ -@SuppressWarnings( "checkstyle:magicnumber" ) -public class E2ETest -{ +@SuppressWarnings("checkstyle:magicnumber") +public class E2ETest { private static final String LONG_STRING = - "0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789"; + "0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789"; @Rule public final ExpectedException e = ExpectedException.none(); @Test - public void endToEndTest() throws Exception - { - ForkNodeArguments arguments = new Arguments( UUID.randomUUID().toString(), 1, new NullConsoleLogger() ); + public void endToEndTest() throws Exception { + ForkNodeArguments arguments = new Arguments(UUID.randomUUID().toString(), 1, new NullConsoleLogger()); - final SurefireForkChannel server = new SurefireForkChannel( arguments ); + final SurefireForkChannel server = new SurefireForkChannel(arguments); server.tryConnectToClient(); final String connection = server.getForkNodeConnectionString(); final SurefireMasterProcessChannelProcessorFactory factory = new SurefireMasterProcessChannelProcessorFactory(); - factory.connect( connection ); - final EventChannelEncoder encoder = (EventChannelEncoder) factory.createEncoder( arguments ); + factory.connect(connection); + final EventChannelEncoder encoder = (EventChannelEncoder) factory.createEncoder(arguments); - final CountDownLatch awaitHandlerFinished = new CountDownLatch( 2 ); + final CountDownLatch awaitHandlerFinished = new CountDownLatch(2); final AtomicLong readTime = new AtomicLong(); final int totalCalls = 400_000; // 400_000; // 1_000_000; // 10_000_000; - EventHandler h = new EventHandler() - { + EventHandler h = new EventHandler() { private final AtomicInteger counter = new AtomicInteger(); private volatile long t1; @Override - public void handleEvent( @Nonnull Event event ) - { - try - { - if ( counter.getAndIncrement() == 0 ) - { + public void handleEvent(@Nonnull Event event) { + try { + if (counter.getAndIncrement() == 0) { t1 = System.currentTimeMillis(); } long t2 = System.currentTimeMillis(); long spent = t2 - t1; - if ( counter.get() == totalCalls - 64 * 1024 ) - { - readTime.set( spent ); - System.out.println( spent + "ms on read" ); + if (counter.get() == totalCalls - 64 * 1024) { + readTime.set(spent); + System.out.println(spent + "ms on read"); awaitHandlerFinished.countDown(); } - } - catch ( Exception e ) - { + } catch (Exception e) { e.printStackTrace(); } } }; - EventHandler queue = new ThreadedStreamConsumer( h ); + EventHandler queue = new ThreadedStreamConsumer(h); System.gc(); - SECONDS.sleep( 5L ); + SECONDS.sleep(5L); - server.bindEventHandler( queue, new CountdownCloseable( new DummyCloseable(), 1 ), new DummyReadableChannel() ); - server.bindCommandReader( new DummyCommandReader(), null ); + server.bindEventHandler(queue, new CountdownCloseable(new DummyCloseable(), 1), new DummyReadableChannel()); + server.bindCommandReader(new DummyCommandReader(), null); - Thread t = new Thread() - { + Thread t = new Thread() { @Override - public void run() - { - TestOutputReceiver target = new TestOutputReceiver() - { + public void run() { + TestOutputReceiver target = new TestOutputReceiver() { @Override - public void writeTestOutput( OutputReportEntry reportEntry ) - { - encoder.testOutput( stdOutln( reportEntry.getLog() ) ); + public void writeTestOutput(OutputReportEntry reportEntry) { + encoder.testOutput(stdOutln(reportEntry.getLog())); } }; - //PrintStream out = System.out; - //PrintStream err = System.err; + // PrintStream out = System.out; + // PrintStream err = System.err; - //ConsoleOutputCapture.startCapture( target ); + // ConsoleOutputCapture.startCapture( target ); - try - { + try { long t1 = System.currentTimeMillis(); - for ( int i = 0; i < totalCalls; i++ ) - { - //System.out.println( LONG_STRING ); - encoder.testOutput( new TestOutputReportEntry( stdOutln( LONG_STRING ), NORMAL_RUN, 1L ) ); + for (int i = 0; i < totalCalls; i++) { + // System.out.println( LONG_STRING ); + encoder.testOutput(new TestOutputReportEntry(stdOutln(LONG_STRING), NORMAL_RUN, 1L)); } long t2 = System.currentTimeMillis(); long spent = t2 - t1; - //System.setOut( out ); - //System.setErr( err ); - System.out.println( spent + "ms on write" ); + // System.setOut( out ); + // System.setErr( err ); + System.out.println(spent + "ms on write"); awaitHandlerFinished.countDown(); - } - catch ( Exception e ) - { + } catch (Exception e) { e.printStackTrace(); } } }; - t.setDaemon( true ); + t.setDaemon(true); t.start(); - assertThat( awaitHandlerFinished.await( 30L, SECONDS ) ) - .isTrue(); + assertThat(awaitHandlerFinished.await(30L, SECONDS)).isTrue(); factory.close(); server.close(); - //queue.close(); + // queue.close(); // 1.0 seconds while using the encoder/decoder - assertThat( readTime.get() ) - .describedAs( "The performance test should assert 1.0s of read time. " - + "The limit 6s guarantees that the read time does not exceed this limit on overloaded CPU." ) - .isPositive() - .isLessThanOrEqualTo( 6_000L ); + assertThat(readTime.get()) + .describedAs("The performance test should assert 1.0s of read time. " + + "The limit 6s guarantees that the read time does not exceed this limit on overloaded CPU.") + .isPositive() + .isLessThanOrEqualTo(6_000L); } - @Test( timeout = 10_000L ) - public void shouldVerifyClient() throws Exception - { - ForkNodeArguments forkNodeArguments = - new Arguments( UUID.randomUUID().toString(), 1, new NullConsoleLogger() ); - - try ( SurefireForkChannel server = new SurefireForkChannel( forkNodeArguments ); - SurefireMasterProcessChannelProcessorFactory client = new SurefireMasterProcessChannelProcessorFactory() ) - { - FutureTask task = new FutureTask<>( new Callable() - { + @Test(timeout = 10_000L) + public void shouldVerifyClient() throws Exception { + ForkNodeArguments forkNodeArguments = new Arguments(UUID.randomUUID().toString(), 1, new NullConsoleLogger()); + + try (SurefireForkChannel server = new SurefireForkChannel(forkNodeArguments); + SurefireMasterProcessChannelProcessorFactory client = + new SurefireMasterProcessChannelProcessorFactory()) { + FutureTask task = new FutureTask<>(new Callable() { @Override - public String call() throws Exception - { - client.connect( server.getForkNodeConnectionString() ); + public String call() throws Exception { + client.connect(server.getForkNodeConnectionString()); return "client connected"; } - } ); + }); - Thread t = new Thread( task ); - t.setDaemon( true ); + Thread t = new Thread(task); + t.setDaemon(true); t.start(); - assertThat( task.get() ) - .isEqualTo( "client connected" ); + assertThat(task.get()).isEqualTo("client connected"); } } - @Test( timeout = 10_000L ) - public void shouldNotVerifyClient() throws Exception - { - ForkNodeArguments forkNodeArguments = - new Arguments( UUID.randomUUID().toString(), 1, new NullConsoleLogger() ); - - try ( SurefireForkChannel server = new SurefireForkChannel( forkNodeArguments ); - SurefireMasterProcessChannelProcessorFactory client = new SurefireMasterProcessChannelProcessorFactory() ) - { - FutureTask task = new FutureTask<>( new Callable() - { + @Test(timeout = 10_000L) + public void shouldNotVerifyClient() throws Exception { + ForkNodeArguments forkNodeArguments = new Arguments(UUID.randomUUID().toString(), 1, new NullConsoleLogger()); + + try (SurefireForkChannel server = new SurefireForkChannel(forkNodeArguments); + SurefireMasterProcessChannelProcessorFactory client = + new SurefireMasterProcessChannelProcessorFactory()) { + FutureTask task = new FutureTask<>(new Callable() { @Override - public String call() throws Exception - { - URI connectionUri = new URI( server.getForkNodeConnectionString() ); - client.connect( "tcp://" + connectionUri.getHost() + ":" + connectionUri.getPort() - + "?sessionId=6ba7b812-9dad-11d1-80b4-00c04fd430c8" ); + public String call() throws Exception { + URI connectionUri = new URI(server.getForkNodeConnectionString()); + client.connect("tcp://" + connectionUri.getHost() + ":" + connectionUri.getPort() + + "?sessionId=6ba7b812-9dad-11d1-80b4-00c04fd430c8"); return "client connected"; } - } ); + }); - Thread t = new Thread( task ); - t.setDaemon( true ); + Thread t = new Thread(task); + t.setDaemon(true); t.start(); - e.expect( InvalidSessionIdException.class ); - e.expectMessage( "The actual sessionId '6ba7b812-9dad-11d1-80b4-00c04fd430c8' does not match '" - + forkNodeArguments.getSessionId() + "'." ); + e.expect(InvalidSessionIdException.class); + e.expectMessage("The actual sessionId '6ba7b812-9dad-11d1-80b4-00c04fd430c8' does not match '" + + forkNodeArguments.getSessionId() + "'."); server.tryConnectToClient(); - server.bindCommandReader( new DummyCommandReader(), new DummyWritableByteChannel() ); + server.bindCommandReader(new DummyCommandReader(), new DummyWritableByteChannel()); - server.bindEventHandler( new DummyEventHandler(), - new CountdownCloseable( new DummyCloseable(), 1 ), new DummyReadableChannel() ); + server.bindEventHandler( + new DummyEventHandler(), + new CountdownCloseable(new DummyCloseable(), 1), + new DummyReadableChannel()); - fail( task.get() ); + fail(task.get()); } } - private static class DummyEventHandler implements EventHandler - { + private static class DummyEventHandler implements EventHandler { @Override - public void handleEvent( @Nonnull Event event ) - { - } + public void handleEvent(@Nonnull Event event) {} } - private static class DummyReadableChannel implements ReadableByteChannel - { + private static class DummyReadableChannel implements ReadableByteChannel { private volatile Thread t; @Override - public int read( ByteBuffer dst ) throws IOException - { - try - { + public int read(ByteBuffer dst) throws IOException { + try { t = Thread.currentThread(); - HOURS.sleep( 1L ); + HOURS.sleep(1L); return 0; - } - catch ( InterruptedException e ) - { - throw new IOException( e.getLocalizedMessage(), e ); + } catch (InterruptedException e) { + throw new IOException(e.getLocalizedMessage(), e); } } @Override - public boolean isOpen() - { + public boolean isOpen() { return true; } @Override - public void close() - { - if ( t != null ) - { + public void close() { + if (t != null) { t.interrupt(); } } } - private static class DummyWritableByteChannel implements WritableByteChannel - { + private static class DummyWritableByteChannel implements WritableByteChannel { private volatile Thread t; @Override - public int write( ByteBuffer src ) throws IOException - { - try - { + public int write(ByteBuffer src) throws IOException { + try { t = Thread.currentThread(); - HOURS.sleep( 1L ); + HOURS.sleep(1L); return 0; - } - catch ( InterruptedException e ) - { - throw new IOException( e.getLocalizedMessage(), e ); + } catch (InterruptedException e) { + throw new IOException(e.getLocalizedMessage(), e); } } @Override - public boolean isOpen() - { + public boolean isOpen() { return true; } @Override - public void close() throws IOException - { - if ( t != null ) - { + public void close() throws IOException { + if (t != null) { t.interrupt(); } } } - private static class DummyCommandReader implements CommandReader - { + private static class DummyCommandReader implements CommandReader { private volatile Thread t; @Override - public Command readNextCommand() throws IOException - { - try - { + public Command readNextCommand() throws IOException { + try { t = Thread.currentThread(); - HOURS.sleep( 1L ); + HOURS.sleep(1L); return null; - } - catch ( InterruptedException e ) - { - throw new IOException( e.getLocalizedMessage(), e ); + } catch (InterruptedException e) { + throw new IOException(e.getLocalizedMessage(), e); } } @Override - public void close() - { - if ( t != null ) - { + public void close() { + if (t != null) { t.interrupt(); } } @Override - public boolean isClosed() - { + public boolean isClosed() { return false; } } - private static class DummyCloseable implements Closeable - { + private static class DummyCloseable implements Closeable { @Override - public void close() - { - } + public void close() {} } - private static class Arguments implements ForkNodeArguments - { + private static class Arguments implements ForkNodeArguments { private final String sessionId; private final int id; private final ConsoleLogger logger; - private Arguments( String sessionId, int id, ConsoleLogger logger ) - { + private Arguments(String sessionId, int id, ConsoleLogger logger) { this.sessionId = sessionId; this.id = id; this.logger = logger; @@ -394,59 +336,49 @@ private Arguments( String sessionId, int id, ConsoleLogger logger ) @Nonnull @Override - public String getSessionId() - { + public String getSessionId() { return sessionId; } @Override - public int getForkChannelId() - { + public int getForkChannelId() { return id; } @Nonnull @Override - public File dumpStreamText( @Nonnull String text ) - { - return new File( "" ); + public File dumpStreamText(@Nonnull String text) { + return new File(""); } @Nonnull @Override - public File dumpStreamException( @Nonnull Throwable t ) - { - return new File( "" ); + public File dumpStreamException(@Nonnull Throwable t) { + return new File(""); } @Override - public void logWarningAtEnd( @Nonnull String text ) - { - } + public void logWarningAtEnd(@Nonnull String text) {} @Nonnull @Override - public ConsoleLogger getConsoleLogger() - { + public ConsoleLogger getConsoleLogger() { return logger; } @Nonnull @Override - public Object getConsoleLock() - { + public Object getConsoleLock() { return logger; } @Override - public File getEventStreamBinaryFile() - { + public File getEventStreamBinaryFile() { return null; } @Override - public File getCommandStreamBinaryFile() - { + public File getCommandStreamBinaryFile() { return null; } } diff --git a/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/extensions/EventConsumerThreadTest.java b/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/extensions/EventConsumerThreadTest.java index 3fac0e4dcb..69cc846119 100644 --- a/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/extensions/EventConsumerThreadTest.java +++ b/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/extensions/EventConsumerThreadTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire.extensions; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,15 +16,10 @@ * specific language governing permissions and limitations * under the License. */ - -import org.apache.maven.plugin.surefire.log.api.ConsoleLogger; -import org.apache.maven.surefire.api.event.Event; -import org.apache.maven.surefire.api.fork.ForkNodeArguments; -import org.apache.maven.surefire.extensions.EventHandler; -import org.apache.maven.surefire.extensions.util.CountdownCloseable; -import org.junit.Test; +package org.apache.maven.plugin.surefire.extensions; import javax.annotation.Nonnull; + import java.io.Closeable; import java.io.File; import java.nio.Buffer; @@ -34,6 +27,13 @@ import java.nio.channels.ReadableByteChannel; import java.util.concurrent.atomic.AtomicInteger; +import org.apache.maven.plugin.surefire.log.api.ConsoleLogger; +import org.apache.maven.surefire.api.event.Event; +import org.apache.maven.surefire.api.fork.ForkNodeArguments; +import org.apache.maven.surefire.extensions.EventHandler; +import org.apache.maven.surefire.extensions.util.CountdownCloseable; +import org.junit.Test; + import static java.lang.Math.min; import static java.nio.charset.StandardCharsets.UTF_8; import static java.util.Arrays.copyOfRange; @@ -43,209 +43,173 @@ /** * */ -public class EventConsumerThreadTest -{ - @SuppressWarnings( "checkstyle:magicnumber" ) - @Test( timeout = 60_000L ) - public void performanceTest() throws Exception - { +public class EventConsumerThreadTest { + @SuppressWarnings("checkstyle:magicnumber") + @Test(timeout = 60_000L) + public void performanceTest() throws Exception { final long[] staredAt = {0}; final long[] finishedAt = {0}; final AtomicInteger calls = new AtomicInteger(); final int totalCalls = 1_000_000; // 400_000; // 1_000_000; // 10_000_000; - EventHandler handler = new EventHandler() - { + EventHandler handler = new EventHandler() { @Override - public void handleEvent( @Nonnull Event event ) - { - if ( staredAt[0] == 0 ) - { + public void handleEvent(@Nonnull Event event) { + if (staredAt[0] == 0) { staredAt[0] = System.currentTimeMillis(); } - if ( calls.incrementAndGet() == totalCalls ) - { + if (calls.incrementAndGet() == totalCalls) { finishedAt[0] = System.currentTimeMillis(); } } }; - final ByteBuffer event = ByteBuffer.allocate( 192 ); - event.put( ":maven-surefire-event:".getBytes( UTF_8 ) ); - event.put( (byte) 14 ); - event.put( ":std-out-stream:".getBytes( UTF_8 ) ); - event.put( (byte) 10 ); - event.put( ":normal-run:".getBytes( UTF_8 ) ); - event.put( "\u0001\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0001:".getBytes( UTF_8 ) ); - event.put( (byte) 5 ); - event.put( ":UTF-8:".getBytes( UTF_8 ) ); - event.putInt( 100 ); + final ByteBuffer event = ByteBuffer.allocate(192); + event.put(":maven-surefire-event:".getBytes(UTF_8)); + event.put((byte) 14); + event.put(":std-out-stream:".getBytes(UTF_8)); + event.put((byte) 10); + event.put(":normal-run:".getBytes(UTF_8)); + event.put("\u0001\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0001:".getBytes(UTF_8)); + event.put((byte) 5); + event.put(":UTF-8:".getBytes(UTF_8)); + event.putInt(100); event.put( - ":0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789:" - .getBytes( UTF_8 ) ); + ":0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789:" + .getBytes(UTF_8)); - ( (Buffer) event ).flip(); - byte[] frame = copyOfRange( event.array(), event.arrayOffset(), event.arrayOffset() + event.remaining() ); - ReadableByteChannel channel = new Channel( frame, 100 ) - { + ((Buffer) event).flip(); + byte[] frame = copyOfRange(event.array(), event.arrayOffset(), event.arrayOffset() + event.remaining()); + ReadableByteChannel channel = new Channel(frame, 100) { private int countRounds; @Override - public synchronized int read( ByteBuffer dst ) - { - if ( countRounds == totalCalls ) - { + public synchronized int read(ByteBuffer dst) { + if (countRounds == totalCalls) { return -1; } - if ( remaining() == 0 ) - { + if (remaining() == 0) { countRounds++; i = 0; } - return super.read( dst ); + return super.read(dst); } }; - EventConsumerThread thread = new EventConsumerThread( "t", channel, handler, - new CountdownCloseable( new MockCloseable(), 1 ), new MockForkNodeArguments() ); + EventConsumerThread thread = new EventConsumerThread( + "t", channel, handler, new CountdownCloseable(new MockCloseable(), 1), new MockForkNodeArguments()); - SECONDS.sleep( 2 ); + SECONDS.sleep(2); System.gc(); - SECONDS.sleep( 5 ); + SECONDS.sleep(5); - System.out.println( "Starting the event thread..." ); + System.out.println("Starting the event thread..."); thread.start(); thread.join(); long execTime = finishedAt[0] - staredAt[0]; - System.out.println( execTime ); + System.out.println(execTime); // 0.6 seconds while using the encoder/decoder for 10 million messages - assertThat( execTime ) - .describedAs( "The performance test should assert 0.75s of read time. " - + "The limit 3.65s guarantees that the read time does not exceed this limit on overloaded CPU." ) - .isPositive() - .isLessThanOrEqualTo( 3_650L ); + assertThat(execTime) + .describedAs("The performance test should assert 0.75s of read time. " + + "The limit 3.65s guarantees that the read time does not exceed this limit on overloaded CPU.") + .isPositive() + .isLessThanOrEqualTo(3_650L); } - private static class Channel implements ReadableByteChannel - { + private static class Channel implements ReadableByteChannel { private final byte[] bytes; private final int chunkSize; protected int i; - Channel( byte[] bytes, int chunkSize ) - { + Channel(byte[] bytes, int chunkSize) { this.bytes = bytes; this.chunkSize = chunkSize; } @Override - public int read( ByteBuffer dst ) - { - if ( remaining() == 0 ) - { + public int read(ByteBuffer dst) { + if (remaining() == 0) { return -1; - } - else if ( dst.hasRemaining() ) - { - int length = min( min( chunkSize, remaining() ), dst.remaining() ) ; - dst.put( bytes, i, length ); + } else if (dst.hasRemaining()) { + int length = min(min(chunkSize, remaining()), dst.remaining()); + dst.put(bytes, i, length); i += length; return length; - } - else - { + } else { return 0; } } - protected final int remaining() - { + protected final int remaining() { return bytes.length - i; } @Override - public boolean isOpen() - { + public boolean isOpen() { return false; } @Override - public void close() - { - } + public void close() {} } - private static class MockCloseable implements Closeable - { + private static class MockCloseable implements Closeable { @Override - public void close() - { - } + public void close() {} } - private static class MockForkNodeArguments implements ForkNodeArguments - { + private static class MockForkNodeArguments implements ForkNodeArguments { @Nonnull @Override - public String getSessionId() - { + public String getSessionId() { return null; } @Override - public int getForkChannelId() - { + public int getForkChannelId() { return 0; } @Nonnull @Override - public File dumpStreamText( @Nonnull String text ) - { + public File dumpStreamText(@Nonnull String text) { return null; } @Nonnull @Override - public File dumpStreamException( @Nonnull Throwable t ) - { + public File dumpStreamException(@Nonnull Throwable t) { return null; } @Override - public void logWarningAtEnd( @Nonnull String text ) - { - } + public void logWarningAtEnd(@Nonnull String text) {} @Nonnull @Override - public ConsoleLogger getConsoleLogger() - { + public ConsoleLogger getConsoleLogger() { return null; } @Nonnull @Override - public Object getConsoleLock() - { + public Object getConsoleLock() { return new Object(); } @Override - public File getEventStreamBinaryFile() - { + public File getEventStreamBinaryFile() { return null; } @Override - public File getCommandStreamBinaryFile() - { + public File getCommandStreamBinaryFile() { return null; } } diff --git a/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/extensions/ForkedProcessEventNotifierTest.java b/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/extensions/ForkedProcessEventNotifierTest.java index dc3c6f381a..26237831a4 100644 --- a/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/extensions/ForkedProcessEventNotifierTest.java +++ b/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/extensions/ForkedProcessEventNotifierTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire.extensions; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,26 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.surefire.extensions; + +import javax.annotation.Nonnull; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.Closeable; +import java.io.File; +import java.io.LineNumberReader; +import java.io.PrintStream; +import java.io.StringReader; +import java.nio.channels.ReadableByteChannel; +import java.nio.charset.Charset; +import java.util.Map; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.concurrent.LinkedTransferQueue; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; import org.apache.maven.plugin.surefire.booterclient.output.DeserializedStacktraceWriter; import org.apache.maven.plugin.surefire.booterclient.output.ForkedProcessEventListener; @@ -54,24 +72,6 @@ import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.modules.junit4.PowerMockRunner; -import javax.annotation.Nonnull; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.Closeable; -import java.io.File; -import java.io.LineNumberReader; -import java.io.PrintStream; -import java.io.StringReader; -import java.nio.channels.ReadableByteChannel; -import java.nio.charset.Charset; -import java.util.Map; -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.ConcurrentLinkedQueue; -import java.util.concurrent.LinkedTransferQueue; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicInteger; - import static java.lang.String.format; import static java.nio.charset.StandardCharsets.UTF_8; import static org.apache.maven.surefire.api.report.RunMode.NORMAL_RUN; @@ -93,1175 +93,1026 @@ * @author Tibor Digana (tibor17) * @since 3.0.0-M4 */ -@RunWith( Enclosed.class ) -public class ForkedProcessEventNotifierTest -{ +@RunWith(Enclosed.class) +public class ForkedProcessEventNotifierTest { /** * */ - @RunWith( PowerMockRunner.class ) - @PowerMockIgnore( { "org.jacoco.agent.rt.*", "com.vladium.emma.rt.*" } ) - public static class DecoderOperationsTest - { + @RunWith(PowerMockRunner.class) + @PowerMockIgnore({"org.jacoco.agent.rt.*", "com.vladium.emma.rt.*"}) + public static class DecoderOperationsTest { @Rule public final ExpectedException rule = none(); @Test - public void shouldSendByeEvent() throws Exception - { + public void shouldSendByeEvent() throws Exception { Stream out = Stream.newStream(); - EventChannelEncoder encoder = new EventChannelEncoder( newBufferedChannel( out ) ); + EventChannelEncoder encoder = new EventChannelEncoder(newBufferedChannel(out)); encoder.bye(); - String read = new String( out.toByteArray(), UTF_8 ); + String read = new String(out.toByteArray(), UTF_8); - assertThat( read ) - .isEqualTo( ":maven-surefire-event:\u0003:bye:" ); + assertThat(read).isEqualTo(":maven-surefire-event:\u0003:bye:"); - LineNumberReader lines = out.newReader( UTF_8 ); + LineNumberReader lines = out.newReader(UTF_8); final String cmd = lines.readLine(); - assertThat( cmd ) - .isNotNull(); + assertThat(cmd).isNotNull(); - ReadableByteChannel channel = newChannel( new ByteArrayInputStream( out.toByteArray() ) ); + ReadableByteChannel channel = newChannel(new ByteArrayInputStream(out.toByteArray())); ForkedProcessEventNotifier notifier = new ForkedProcessEventNotifier(); EventAssertionListener listener = new EventAssertionListener(); - notifier.setByeListener( listener ); + notifier.setByeListener(listener); EH eventHandler = new EH(); - CountdownCloseable countdown = new CountdownCloseable( mock( Closeable.class ), 0 ); - ConsoleLoggerMock logger = new ConsoleLoggerMock( false, false, false, false ); - ForkNodeArgumentsMock arguments = new ForkNodeArgumentsMock( logger, new File( "" ) ); - try ( EventConsumerThread t = new EventConsumerThread( "t", channel, eventHandler, countdown, arguments ) ) - { + CountdownCloseable countdown = new CountdownCloseable(mock(Closeable.class), 0); + ConsoleLoggerMock logger = new ConsoleLoggerMock(false, false, false, false); + ForkNodeArgumentsMock arguments = new ForkNodeArgumentsMock(logger, new File("")); + try (EventConsumerThread t = new EventConsumerThread("t", channel, eventHandler, countdown, arguments)) { t.start(); - notifier.notifyEvent( eventHandler.pullEvent() ); + notifier.notifyEvent(eventHandler.pullEvent()); } - assertThat( logger.error ).isEmpty(); - assertThat( logger.warning ).isEmpty(); - assertThat( logger.info ).isEmpty(); - assertThat( logger.debug ).isEmpty(); - - assertThat( logger.isCalled() ) - .isFalse(); - assertThat( arguments.isCalled() ) - .isFalse(); - assertThat( listener.called.get() ) - .isTrue(); + assertThat(logger.error).isEmpty(); + assertThat(logger.warning).isEmpty(); + assertThat(logger.info).isEmpty(); + assertThat(logger.debug).isEmpty(); + + assertThat(logger.isCalled()).isFalse(); + assertThat(arguments.isCalled()).isFalse(); + assertThat(listener.called.get()).isTrue(); } @Test - public void shouldSendStopOnNextTestEvent() throws Exception - { + public void shouldSendStopOnNextTestEvent() throws Exception { Stream out = Stream.newStream(); - EventChannelEncoder encoder = new EventChannelEncoder( newBufferedChannel( out ) ); + EventChannelEncoder encoder = new EventChannelEncoder(newBufferedChannel(out)); encoder.stopOnNextTest(); - String read = new String( out.toByteArray(), UTF_8 ); + String read = new String(out.toByteArray(), UTF_8); - assertThat( read ) - .isEqualTo( ":maven-surefire-event:\u0011:stop-on-next-test:" ); + assertThat(read).isEqualTo(":maven-surefire-event:\u0011:stop-on-next-test:"); - LineNumberReader lines = out.newReader( UTF_8 ); + LineNumberReader lines = out.newReader(UTF_8); final String cmd = lines.readLine(); - assertThat( cmd ) - .isNotNull(); + assertThat(cmd).isNotNull(); - ReadableByteChannel channel = newChannel( new ByteArrayInputStream( out.toByteArray() ) ); + ReadableByteChannel channel = newChannel(new ByteArrayInputStream(out.toByteArray())); ForkedProcessEventNotifier notifier = new ForkedProcessEventNotifier(); EventAssertionListener listener = new EventAssertionListener(); - notifier.setStopOnNextTestListener( listener ); + notifier.setStopOnNextTestListener(listener); EH eventHandler = new EH(); - CountdownCloseable countdown = new CountdownCloseable( mock( Closeable.class ), 0 ); - ConsoleLoggerMock logger = new ConsoleLoggerMock( false, false, false, false ); - ForkNodeArgumentsMock arguments = new ForkNodeArgumentsMock( logger, new File( "" ) ); - try ( EventConsumerThread t = new EventConsumerThread( "t", channel, eventHandler, countdown, arguments ) ) - { + CountdownCloseable countdown = new CountdownCloseable(mock(Closeable.class), 0); + ConsoleLoggerMock logger = new ConsoleLoggerMock(false, false, false, false); + ForkNodeArgumentsMock arguments = new ForkNodeArgumentsMock(logger, new File("")); + try (EventConsumerThread t = new EventConsumerThread("t", channel, eventHandler, countdown, arguments)) { t.start(); - notifier.notifyEvent( eventHandler.pullEvent() ); + notifier.notifyEvent(eventHandler.pullEvent()); } - assertThat( logger.error ).isEmpty(); - assertThat( logger.warning ).isEmpty(); - assertThat( logger.info ).isEmpty(); - assertThat( logger.debug ).isEmpty(); - - assertThat( logger.isCalled() ) - .isFalse(); - assertThat( arguments.dumpStreamText ) - .isEmpty(); - assertThat( arguments.isCalled() ) - .isFalse(); - assertThat( listener.called.get() ) - .isTrue(); + assertThat(logger.error).isEmpty(); + assertThat(logger.warning).isEmpty(); + assertThat(logger.info).isEmpty(); + assertThat(logger.debug).isEmpty(); + + assertThat(logger.isCalled()).isFalse(); + assertThat(arguments.dumpStreamText).isEmpty(); + assertThat(arguments.isCalled()).isFalse(); + assertThat(listener.called.get()).isTrue(); } @Test - public void shouldCorrectlyDecodeStackTracesWithEmptyStringTraceMessages() throws Exception - { + public void shouldCorrectlyDecodeStackTracesWithEmptyStringTraceMessages() throws Exception { String exceptionMessage = ""; String smartStackTrace = "JUnit5Test.failWithEmptyString:16"; String exceptionStackTrace = "org.opentest4j.AssertionFailedError: \n" + "\tat JUnit5Test.failWithEmptyString(JUnit5Test.java:16)\n"; - StackTraceWriter stackTraceWriter = mock( StackTraceWriter.class ); - SafeThrowable safeThrowable = new SafeThrowable( exceptionMessage ); - when( stackTraceWriter.getThrowable() ).thenReturn( safeThrowable ); - when( stackTraceWriter.smartTrimmedStackTrace() ).thenReturn( smartStackTrace ); - when( stackTraceWriter.writeTrimmedTraceToString() ).thenReturn( exceptionStackTrace ); - when( stackTraceWriter.writeTraceToString() ).thenReturn( exceptionStackTrace ); - - ReportEntry reportEntry = mock( ReportEntry.class ); - when( reportEntry.getRunMode() ).thenReturn( NORMAL_RUN ); - when( reportEntry.getTestRunId() ).thenReturn( 1L ); - when( reportEntry.getElapsed() ).thenReturn( 7 ); - when( reportEntry.getGroup() ).thenReturn( null ); - when( reportEntry.getMessage() ).thenReturn( null ); - when( reportEntry.getName() ).thenReturn( "failWithEmptyString" ); - when( reportEntry.getNameWithGroup() ).thenReturn( "JUnit5Test" ); - when( reportEntry.getSourceName() ).thenReturn( "JUnit5Test" ); - when( reportEntry.getSourceText() ).thenReturn( null ); - when( reportEntry.getStackTraceWriter() ).thenReturn( stackTraceWriter ); + StackTraceWriter stackTraceWriter = mock(StackTraceWriter.class); + SafeThrowable safeThrowable = new SafeThrowable(exceptionMessage); + when(stackTraceWriter.getThrowable()).thenReturn(safeThrowable); + when(stackTraceWriter.smartTrimmedStackTrace()).thenReturn(smartStackTrace); + when(stackTraceWriter.writeTrimmedTraceToString()).thenReturn(exceptionStackTrace); + when(stackTraceWriter.writeTraceToString()).thenReturn(exceptionStackTrace); + + ReportEntry reportEntry = mock(ReportEntry.class); + when(reportEntry.getRunMode()).thenReturn(NORMAL_RUN); + when(reportEntry.getTestRunId()).thenReturn(1L); + when(reportEntry.getElapsed()).thenReturn(7); + when(reportEntry.getGroup()).thenReturn(null); + when(reportEntry.getMessage()).thenReturn(null); + when(reportEntry.getName()).thenReturn("failWithEmptyString"); + when(reportEntry.getNameWithGroup()).thenReturn("JUnit5Test"); + when(reportEntry.getSourceName()).thenReturn("JUnit5Test"); + when(reportEntry.getSourceText()).thenReturn(null); + when(reportEntry.getStackTraceWriter()).thenReturn(stackTraceWriter); final Stream out = Stream.newStream(); - EventChannelEncoder encoder = new EventChannelEncoder( newBufferedChannel( out ) ); - encoder.testFailed( reportEntry, true ); + EventChannelEncoder encoder = new EventChannelEncoder(newBufferedChannel(out)); + encoder.testFailed(reportEntry, true); - ReadableByteChannel channel = newChannel( new ByteArrayInputStream( out.toByteArray() ) ); + ReadableByteChannel channel = newChannel(new ByteArrayInputStream(out.toByteArray())); final ForkedProcessEventNotifier notifier = new ForkedProcessEventNotifier(); - ReportEventAssertionListener listener = new ReportEventAssertionListener( reportEntry, true ); - notifier.setTestFailedListener( listener ); + ReportEventAssertionListener listener = new ReportEventAssertionListener(reportEntry, true); + notifier.setTestFailedListener(listener); EH eventHandler = new EH(); - CountdownCloseable countdown = new CountdownCloseable( mock( Closeable.class ), 0 ); - ConsoleLoggerMock logger = new ConsoleLoggerMock( false, false, false, false ); - ForkNodeArgumentsMock arguments = new ForkNodeArgumentsMock( logger, new File( "" ) ); - try ( EventConsumerThread t = new EventConsumerThread( "t", channel, eventHandler, countdown, arguments ) ) - { + CountdownCloseable countdown = new CountdownCloseable(mock(Closeable.class), 0); + ConsoleLoggerMock logger = new ConsoleLoggerMock(false, false, false, false); + ForkNodeArgumentsMock arguments = new ForkNodeArgumentsMock(logger, new File("")); + try (EventConsumerThread t = new EventConsumerThread("t", channel, eventHandler, countdown, arguments)) { t.start(); - notifier.notifyEvent( eventHandler.pullEvent() ); + notifier.notifyEvent(eventHandler.pullEvent()); } - assertThat( logger.error ).isEmpty(); - assertThat( logger.warning ).isEmpty(); - assertThat( logger.info ).isEmpty(); - assertThat( logger.debug ).isEmpty(); - - assertThat( logger.isCalled() ) - .isFalse(); - assertThat( arguments.isCalled() ) - .isFalse(); - assertThat( listener.called.get() ) - .isTrue(); + assertThat(logger.error).isEmpty(); + assertThat(logger.warning).isEmpty(); + assertThat(logger.info).isEmpty(); + assertThat(logger.debug).isEmpty(); + + assertThat(logger.isCalled()).isFalse(); + assertThat(arguments.isCalled()).isFalse(); + assertThat(listener.called.get()).isTrue(); } @Test - public void shouldSendNextTestEvent() throws Exception - { + public void shouldSendNextTestEvent() throws Exception { final Stream out = Stream.newStream(); - EventChannelEncoder encoder = new EventChannelEncoder( newBufferedChannel( out ) ); + EventChannelEncoder encoder = new EventChannelEncoder(newBufferedChannel(out)); encoder.acquireNextTest(); - String read = new String( out.toByteArray(), UTF_8 ); + String read = new String(out.toByteArray(), UTF_8); - assertThat( read ) - .isEqualTo( ":maven-surefire-event:\u0009:next-test:" ); + assertThat(read).isEqualTo(":maven-surefire-event:\u0009:next-test:"); - ReadableByteChannel channel = newChannel( new ByteArrayInputStream( out.toByteArray() ) ); + ReadableByteChannel channel = newChannel(new ByteArrayInputStream(out.toByteArray())); ForkedProcessEventNotifier notifier = new ForkedProcessEventNotifier(); EventAssertionListener listener = new EventAssertionListener(); - notifier.setAcquireNextTestListener( listener ); + notifier.setAcquireNextTestListener(listener); EH eventHandler = new EH(); - CountdownCloseable countdown = new CountdownCloseable( mock( Closeable.class ), 0 ); - ConsoleLoggerMock logger = new ConsoleLoggerMock( false, false, false, false ); - ForkNodeArgumentsMock arguments = new ForkNodeArgumentsMock( logger, new File( "" ) ); - try ( EventConsumerThread t = new EventConsumerThread( "t", channel, eventHandler, countdown, arguments ) ) - { + CountdownCloseable countdown = new CountdownCloseable(mock(Closeable.class), 0); + ConsoleLoggerMock logger = new ConsoleLoggerMock(false, false, false, false); + ForkNodeArgumentsMock arguments = new ForkNodeArgumentsMock(logger, new File("")); + try (EventConsumerThread t = new EventConsumerThread("t", channel, eventHandler, countdown, arguments)) { t.start(); - notifier.notifyEvent( eventHandler.pullEvent() ); + notifier.notifyEvent(eventHandler.pullEvent()); } - assertThat( logger.error ).isEmpty(); - assertThat( logger.warning ).isEmpty(); - assertThat( logger.info ).isEmpty(); - assertThat( logger.debug ).isEmpty(); - - assertThat( logger.isCalled() ) - .isFalse(); - assertThat( arguments.isCalled() ) - .isFalse(); - assertThat( listener.called.get() ) - .isTrue(); + assertThat(logger.error).isEmpty(); + assertThat(logger.warning).isEmpty(); + assertThat(logger.info).isEmpty(); + assertThat(logger.debug).isEmpty(); + + assertThat(logger.isCalled()).isFalse(); + assertThat(arguments.isCalled()).isFalse(); + assertThat(listener.called.get()).isTrue(); } @Test - public void testConsole() throws Exception - { + public void testConsole() throws Exception { final Stream out = Stream.newStream(); - EventChannelEncoder encoder = new EventChannelEncoder( newBufferedChannel( out ) ); - encoder.consoleInfoLog( "msg" ); + EventChannelEncoder encoder = new EventChannelEncoder(newBufferedChannel(out)); + encoder.consoleInfoLog("msg"); - ReadableByteChannel channel = newChannel( new ByteArrayInputStream( out.toByteArray() ) ); + ReadableByteChannel channel = newChannel(new ByteArrayInputStream(out.toByteArray())); ForkedProcessEventNotifier notifier = new ForkedProcessEventNotifier(); - StringEventAssertionListener listener = new StringEventAssertionListener( "msg" ); - notifier.setConsoleInfoListener( listener ); + StringEventAssertionListener listener = new StringEventAssertionListener("msg"); + notifier.setConsoleInfoListener(listener); EH eventHandler = new EH(); - CountdownCloseable countdown = new CountdownCloseable( mock( Closeable.class ), 0 ); - ConsoleLoggerMock logger = new ConsoleLoggerMock( false, false, false, false ); - ForkNodeArgumentsMock arguments = new ForkNodeArgumentsMock( logger, new File( "" ) ); - try ( EventConsumerThread t = new EventConsumerThread( "t", channel, eventHandler, countdown, arguments ) ) - { + CountdownCloseable countdown = new CountdownCloseable(mock(Closeable.class), 0); + ConsoleLoggerMock logger = new ConsoleLoggerMock(false, false, false, false); + ForkNodeArgumentsMock arguments = new ForkNodeArgumentsMock(logger, new File("")); + try (EventConsumerThread t = new EventConsumerThread("t", channel, eventHandler, countdown, arguments)) { t.start(); - notifier.notifyEvent( eventHandler.pullEvent() ); + notifier.notifyEvent(eventHandler.pullEvent()); } - assertThat( logger.error ).isEmpty(); - assertThat( logger.warning ).isEmpty(); - assertThat( logger.info ).isEmpty(); - assertThat( logger.debug ).isEmpty(); - - assertThat( logger.isCalled() ) - .isFalse(); - assertThat( arguments.isCalled() ) - .isFalse(); - assertThat( listener.called.get() ) - .isTrue(); + assertThat(logger.error).isEmpty(); + assertThat(logger.warning).isEmpty(); + assertThat(logger.info).isEmpty(); + assertThat(logger.debug).isEmpty(); + + assertThat(logger.isCalled()).isFalse(); + assertThat(arguments.isCalled()).isFalse(); + assertThat(listener.called.get()).isTrue(); } @Test - public void testError() throws Exception - { + public void testError() throws Exception { final Stream out = Stream.newStream(); - EventChannelEncoder encoder = new EventChannelEncoder( newBufferedChannel( out ) ); - encoder.consoleErrorLog( "msg" ); + EventChannelEncoder encoder = new EventChannelEncoder(newBufferedChannel(out)); + encoder.consoleErrorLog("msg"); - ReadableByteChannel channel = newChannel( new ByteArrayInputStream( out.toByteArray() ) ); + ReadableByteChannel channel = newChannel(new ByteArrayInputStream(out.toByteArray())); ForkedProcessEventNotifier notifier = new ForkedProcessEventNotifier(); - StackTraceEventListener listener = new StackTraceEventListener( "msg", null, null ); - notifier.setConsoleErrorListener( listener ); + StackTraceEventListener listener = new StackTraceEventListener("msg", null, null); + notifier.setConsoleErrorListener(listener); EH eventHandler = new EH(); - CountdownCloseable countdown = new CountdownCloseable( mock( Closeable.class ), 0 ); - ConsoleLoggerMock logger = new ConsoleLoggerMock( false, false, false, false ); - ForkNodeArgumentsMock arguments = new ForkNodeArgumentsMock( logger, new File( "" ) ); - try ( EventConsumerThread t = new EventConsumerThread( "t", channel, eventHandler, countdown, arguments ) ) - { + CountdownCloseable countdown = new CountdownCloseable(mock(Closeable.class), 0); + ConsoleLoggerMock logger = new ConsoleLoggerMock(false, false, false, false); + ForkNodeArgumentsMock arguments = new ForkNodeArgumentsMock(logger, new File("")); + try (EventConsumerThread t = new EventConsumerThread("t", channel, eventHandler, countdown, arguments)) { t.start(); - notifier.notifyEvent( eventHandler.pullEvent() ); + notifier.notifyEvent(eventHandler.pullEvent()); } - assertThat( logger.error ).isEmpty(); - assertThat( logger.warning ).isEmpty(); - assertThat( logger.info ).isEmpty(); - assertThat( logger.debug ).isEmpty(); - - assertThat( logger.isCalled() ) - .isFalse(); - assertThat( arguments.isCalled() ) - .isFalse(); - assertThat( listener.called.get() ) - .isTrue(); + assertThat(logger.error).isEmpty(); + assertThat(logger.warning).isEmpty(); + assertThat(logger.info).isEmpty(); + assertThat(logger.debug).isEmpty(); + + assertThat(logger.isCalled()).isFalse(); + assertThat(arguments.isCalled()).isFalse(); + assertThat(listener.called.get()).isTrue(); } @Test - public void testErrorWithException() throws Exception - { + public void testErrorWithException() throws Exception { final Stream out = Stream.newStream(); - EventChannelEncoder encoder = new EventChannelEncoder( newBufferedChannel( out ) ); - Throwable throwable = new Throwable( "msg" ); - encoder.consoleErrorLog( throwable ); + EventChannelEncoder encoder = new EventChannelEncoder(newBufferedChannel(out)); + Throwable throwable = new Throwable("msg"); + encoder.consoleErrorLog(throwable); - ReadableByteChannel channel = newChannel( new ByteArrayInputStream( out.toByteArray() ) ); + ReadableByteChannel channel = newChannel(new ByteArrayInputStream(out.toByteArray())); ForkedProcessEventNotifier notifier = new ForkedProcessEventNotifier(); - String stackTrace = ConsoleLoggerUtils.toString( throwable ); - StackTraceEventListener listener = new StackTraceEventListener( "msg", null, stackTrace ); - notifier.setConsoleErrorListener( listener ); + String stackTrace = ConsoleLoggerUtils.toString(throwable); + StackTraceEventListener listener = new StackTraceEventListener("msg", null, stackTrace); + notifier.setConsoleErrorListener(listener); EH eventHandler = new EH(); - CountdownCloseable countdown = new CountdownCloseable( mock( Closeable.class ), 1 ); - ConsoleLoggerMock logger = new ConsoleLoggerMock( false, false, false, false ); - ForkNodeArgumentsMock arguments = new ForkNodeArgumentsMock( logger, new File( "" ) ); - try ( EventConsumerThread t = new EventConsumerThread( "t", channel, eventHandler, countdown, arguments ) ) - { + CountdownCloseable countdown = new CountdownCloseable(mock(Closeable.class), 1); + ConsoleLoggerMock logger = new ConsoleLoggerMock(false, false, false, false); + ForkNodeArgumentsMock arguments = new ForkNodeArgumentsMock(logger, new File("")); + try (EventConsumerThread t = new EventConsumerThread("t", channel, eventHandler, countdown, arguments)) { t.start(); - notifier.notifyEvent( eventHandler.pullEvent() ); + notifier.notifyEvent(eventHandler.pullEvent()); } - assertThat( logger.error ).isEmpty(); - assertThat( logger.warning ).isEmpty(); - assertThat( logger.info ).isEmpty(); - assertThat( logger.debug ).isEmpty(); - - assertThat( logger.isCalled() ) - .isFalse(); - assertThat( arguments.isCalled() ) - .isFalse(); - assertThat( listener.called.get() ) - .isTrue(); + assertThat(logger.error).isEmpty(); + assertThat(logger.warning).isEmpty(); + assertThat(logger.info).isEmpty(); + assertThat(logger.debug).isEmpty(); + + assertThat(logger.isCalled()).isFalse(); + assertThat(arguments.isCalled()).isFalse(); + assertThat(listener.called.get()).isTrue(); } @Test - public void testErrorWithStackTraceWriter() throws Exception - { + public void testErrorWithStackTraceWriter() throws Exception { final Stream out = Stream.newStream(); - EventChannelEncoder encoder = new EventChannelEncoder( newBufferedChannel( out ) ); - StackTraceWriter stackTraceWriter = new DeserializedStacktraceWriter( "1", "2", "3" ); - encoder.consoleErrorLog( stackTraceWriter, false ); + EventChannelEncoder encoder = new EventChannelEncoder(newBufferedChannel(out)); + StackTraceWriter stackTraceWriter = new DeserializedStacktraceWriter("1", "2", "3"); + encoder.consoleErrorLog(stackTraceWriter, false); - ReadableByteChannel channel = newChannel( new ByteArrayInputStream( out.toByteArray() ) ); + ReadableByteChannel channel = newChannel(new ByteArrayInputStream(out.toByteArray())); ForkedProcessEventNotifier notifier = new ForkedProcessEventNotifier(); - StackTraceEventListener listener = new StackTraceEventListener( "1", "2", "3" ); - notifier.setConsoleErrorListener( listener ); + StackTraceEventListener listener = new StackTraceEventListener("1", "2", "3"); + notifier.setConsoleErrorListener(listener); EH eventHandler = new EH(); - CountdownCloseable countdown = new CountdownCloseable( mock( Closeable.class ), 0 ); - ConsoleLoggerMock logger = new ConsoleLoggerMock( false, false, false, false ); - ForkNodeArgumentsMock arguments = new ForkNodeArgumentsMock( logger, new File( "" ) ); - try ( EventConsumerThread t = new EventConsumerThread( "t", channel, eventHandler, countdown, arguments ) ) - { + CountdownCloseable countdown = new CountdownCloseable(mock(Closeable.class), 0); + ConsoleLoggerMock logger = new ConsoleLoggerMock(false, false, false, false); + ForkNodeArgumentsMock arguments = new ForkNodeArgumentsMock(logger, new File("")); + try (EventConsumerThread t = new EventConsumerThread("t", channel, eventHandler, countdown, arguments)) { t.start(); - notifier.notifyEvent( eventHandler.pullEvent() ); + notifier.notifyEvent(eventHandler.pullEvent()); } - assertThat( logger.error ).isEmpty(); - assertThat( logger.warning ).isEmpty(); - assertThat( logger.info ).isEmpty(); - assertThat( logger.debug ).isEmpty(); - - assertThat( logger.isCalled() ) - .isFalse(); - assertThat( arguments.isCalled() ) - .isFalse(); - assertThat( listener.called.get() ) - .isTrue(); + assertThat(logger.error).isEmpty(); + assertThat(logger.warning).isEmpty(); + assertThat(logger.info).isEmpty(); + assertThat(logger.debug).isEmpty(); + + assertThat(logger.isCalled()).isFalse(); + assertThat(arguments.isCalled()).isFalse(); + assertThat(listener.called.get()).isTrue(); } @Test - public void testDebug() throws Exception - { + public void testDebug() throws Exception { final Stream out = Stream.newStream(); - EventChannelEncoder encoder = new EventChannelEncoder( newBufferedChannel( out ) ); - encoder.consoleDebugLog( "msg" ); + EventChannelEncoder encoder = new EventChannelEncoder(newBufferedChannel(out)); + encoder.consoleDebugLog("msg"); - ReadableByteChannel channel = newChannel( new ByteArrayInputStream( out.toByteArray() ) ); + ReadableByteChannel channel = newChannel(new ByteArrayInputStream(out.toByteArray())); ForkedProcessEventNotifier notifier = new ForkedProcessEventNotifier(); - StringEventAssertionListener listener = new StringEventAssertionListener( "msg" ); - notifier.setConsoleDebugListener( listener ); + StringEventAssertionListener listener = new StringEventAssertionListener("msg"); + notifier.setConsoleDebugListener(listener); EH eventHandler = new EH(); - CountdownCloseable countdown = new CountdownCloseable( mock( Closeable.class ), 0 ); - ConsoleLoggerMock logger = new ConsoleLoggerMock( false, false, false, false ); - ForkNodeArgumentsMock arguments = new ForkNodeArgumentsMock( logger, new File( "" ) ); - try ( EventConsumerThread t = new EventConsumerThread( "t", channel, eventHandler, countdown, arguments ) ) - { + CountdownCloseable countdown = new CountdownCloseable(mock(Closeable.class), 0); + ConsoleLoggerMock logger = new ConsoleLoggerMock(false, false, false, false); + ForkNodeArgumentsMock arguments = new ForkNodeArgumentsMock(logger, new File("")); + try (EventConsumerThread t = new EventConsumerThread("t", channel, eventHandler, countdown, arguments)) { t.start(); - notifier.notifyEvent( eventHandler.pullEvent() ); + notifier.notifyEvent(eventHandler.pullEvent()); } - assertThat( logger.error ).isEmpty(); - assertThat( logger.warning ).isEmpty(); - assertThat( logger.info ).isEmpty(); - assertThat( logger.debug ).isEmpty(); + assertThat(logger.error).isEmpty(); + assertThat(logger.warning).isEmpty(); + assertThat(logger.info).isEmpty(); + assertThat(logger.debug).isEmpty(); - assertThat( logger.isCalled() ) - .isFalse(); + assertThat(logger.isCalled()).isFalse(); - assertThat( arguments.isCalled() ) - .isFalse(); + assertThat(arguments.isCalled()).isFalse(); - assertThat( listener.called.get() ) - .isTrue(); + assertThat(listener.called.get()).isTrue(); - assertThat( listener.msg ) - .isEqualTo( "msg" ); + assertThat(listener.msg).isEqualTo("msg"); } @Test - public void testWarning() throws Exception - { + public void testWarning() throws Exception { final Stream out = Stream.newStream(); - EventChannelEncoder encoder = new EventChannelEncoder( newBufferedChannel( out ) ); - encoder.consoleWarningLog( "msg" ); + EventChannelEncoder encoder = new EventChannelEncoder(newBufferedChannel(out)); + encoder.consoleWarningLog("msg"); - ReadableByteChannel channel = newChannel( new ByteArrayInputStream( out.toByteArray() ) ); + ReadableByteChannel channel = newChannel(new ByteArrayInputStream(out.toByteArray())); ForkedProcessEventNotifier notifier = new ForkedProcessEventNotifier(); - StringEventAssertionListener listener = new StringEventAssertionListener( "msg" ); - notifier.setConsoleWarningListener( listener ); + StringEventAssertionListener listener = new StringEventAssertionListener("msg"); + notifier.setConsoleWarningListener(listener); EH eventHandler = new EH(); - CountdownCloseable countdown = new CountdownCloseable( mock( Closeable.class ), 0 ); - ConsoleLoggerMock logger = new ConsoleLoggerMock( false, false, false, false ); - ForkNodeArgumentsMock arguments = new ForkNodeArgumentsMock( logger, new File( "" ) ); - try ( EventConsumerThread t = new EventConsumerThread( "t", channel, eventHandler, countdown, arguments ) ) - { + CountdownCloseable countdown = new CountdownCloseable(mock(Closeable.class), 0); + ConsoleLoggerMock logger = new ConsoleLoggerMock(false, false, false, false); + ForkNodeArgumentsMock arguments = new ForkNodeArgumentsMock(logger, new File("")); + try (EventConsumerThread t = new EventConsumerThread("t", channel, eventHandler, countdown, arguments)) { t.start(); - notifier.notifyEvent( eventHandler.pullEvent() ); + notifier.notifyEvent(eventHandler.pullEvent()); } - assertThat( logger.error ).isEmpty(); - assertThat( logger.warning ).isEmpty(); - assertThat( logger.info ).isEmpty(); - assertThat( logger.debug ).isEmpty(); - - assertThat( logger.isCalled() ) - .isFalse(); - assertThat( arguments.isCalled() ) - .isFalse(); - assertThat( listener.called.get() ) - .isTrue(); + assertThat(logger.error).isEmpty(); + assertThat(logger.warning).isEmpty(); + assertThat(logger.info).isEmpty(); + assertThat(logger.debug).isEmpty(); + + assertThat(logger.isCalled()).isFalse(); + assertThat(arguments.isCalled()).isFalse(); + assertThat(listener.called.get()).isTrue(); } @Test - public void testStdOutStream() throws Exception - { + public void testStdOutStream() throws Exception { final Stream out = Stream.newStream(); - WritableBufferedByteChannel wChannel = newBufferedChannel( out ); - EventChannelEncoder encoder = new EventChannelEncoder( wChannel ); - encoder.testOutput( new TestOutputReportEntry( stdOut( "msg" ), NORMAL_RUN, 1L ) ); + WritableBufferedByteChannel wChannel = newBufferedChannel(out); + EventChannelEncoder encoder = new EventChannelEncoder(wChannel); + encoder.testOutput(new TestOutputReportEntry(stdOut("msg"), NORMAL_RUN, 1L)); wChannel.close(); - ReadableByteChannel channel = newChannel( new ByteArrayInputStream( out.toByteArray() ) ); + ReadableByteChannel channel = newChannel(new ByteArrayInputStream(out.toByteArray())); ForkedProcessEventNotifier notifier = new ForkedProcessEventNotifier(); StandardOutErrEventAssertionListener listener = - new StandardOutErrEventAssertionListener( NORMAL_RUN, 1L, "msg", false ); - notifier.setStdOutListener( listener ); + new StandardOutErrEventAssertionListener(NORMAL_RUN, 1L, "msg", false); + notifier.setStdOutListener(listener); EH eventHandler = new EH(); - CountdownCloseable countdown = new CountdownCloseable( mock( Closeable.class ), 0 ); - ConsoleLoggerMock logger = new ConsoleLoggerMock( false, false, false, false ); - ForkNodeArgumentsMock arguments = new ForkNodeArgumentsMock( logger, new File( "" ) ); - try ( EventConsumerThread t = new EventConsumerThread( "t", channel, eventHandler, countdown, arguments ) ) - { + CountdownCloseable countdown = new CountdownCloseable(mock(Closeable.class), 0); + ConsoleLoggerMock logger = new ConsoleLoggerMock(false, false, false, false); + ForkNodeArgumentsMock arguments = new ForkNodeArgumentsMock(logger, new File("")); + try (EventConsumerThread t = new EventConsumerThread("t", channel, eventHandler, countdown, arguments)) { t.start(); - notifier.notifyEvent( eventHandler.pullEvent() ); + notifier.notifyEvent(eventHandler.pullEvent()); } - assertThat( logger.error ).isEmpty(); - assertThat( logger.warning ).isEmpty(); - assertThat( logger.info ).isEmpty(); - assertThat( logger.debug ).isEmpty(); - - assertThat( logger.isCalled() ) - .isFalse(); - assertThat( arguments.isCalled() ) - .isFalse(); - assertThat( listener.called.get() ) - .isTrue(); + assertThat(logger.error).isEmpty(); + assertThat(logger.warning).isEmpty(); + assertThat(logger.info).isEmpty(); + assertThat(logger.debug).isEmpty(); + + assertThat(logger.isCalled()).isFalse(); + assertThat(arguments.isCalled()).isFalse(); + assertThat(listener.called.get()).isTrue(); } @Test - public void testStdOutStreamPrint() throws Exception - { + public void testStdOutStreamPrint() throws Exception { final Stream out = Stream.newStream(); - WritableBufferedByteChannel wChannel = newBufferedChannel( out ); - EventChannelEncoder encoder = new EventChannelEncoder( wChannel ); - encoder.testOutput( new TestOutputReportEntry( stdOut( "" ), NORMAL_RUN, 1L ) ); + WritableBufferedByteChannel wChannel = newBufferedChannel(out); + EventChannelEncoder encoder = new EventChannelEncoder(wChannel); + encoder.testOutput(new TestOutputReportEntry(stdOut(""), NORMAL_RUN, 1L)); wChannel.close(); - ReadableByteChannel channel = newChannel( new ByteArrayInputStream( out.toByteArray() ) ); + ReadableByteChannel channel = newChannel(new ByteArrayInputStream(out.toByteArray())); ForkedProcessEventNotifier notifier = new ForkedProcessEventNotifier(); StandardOutErrEventAssertionListener listener = - new StandardOutErrEventAssertionListener( NORMAL_RUN, 1L, "", false ); - notifier.setStdOutListener( listener ); + new StandardOutErrEventAssertionListener(NORMAL_RUN, 1L, "", false); + notifier.setStdOutListener(listener); EH eventHandler = new EH(); - CountdownCloseable countdown = new CountdownCloseable( mock( Closeable.class ), 0 ); - ConsoleLoggerMock logger = new ConsoleLoggerMock( false, false, false, false ); - ForkNodeArgumentsMock arguments = new ForkNodeArgumentsMock( logger, new File( "" ) ); - try ( EventConsumerThread t = new EventConsumerThread( "t", channel, eventHandler, countdown, arguments ) ) - { + CountdownCloseable countdown = new CountdownCloseable(mock(Closeable.class), 0); + ConsoleLoggerMock logger = new ConsoleLoggerMock(false, false, false, false); + ForkNodeArgumentsMock arguments = new ForkNodeArgumentsMock(logger, new File("")); + try (EventConsumerThread t = new EventConsumerThread("t", channel, eventHandler, countdown, arguments)) { t.start(); - notifier.notifyEvent( eventHandler.pullEvent() ); + notifier.notifyEvent(eventHandler.pullEvent()); } - assertThat( logger.error ).isEmpty(); - assertThat( logger.warning ).isEmpty(); - assertThat( logger.info ).isEmpty(); - assertThat( logger.debug ).isEmpty(); - - assertThat( logger.isCalled() ) - .isFalse(); - assertThat( arguments.isCalled() ) - .isFalse(); - assertThat( listener.called.get() ) - .isTrue(); + assertThat(logger.error).isEmpty(); + assertThat(logger.warning).isEmpty(); + assertThat(logger.info).isEmpty(); + assertThat(logger.debug).isEmpty(); + + assertThat(logger.isCalled()).isFalse(); + assertThat(arguments.isCalled()).isFalse(); + assertThat(listener.called.get()).isTrue(); } @Test - public void testStdOutStreamPrintWithNull() throws Exception - { + public void testStdOutStreamPrintWithNull() throws Exception { final Stream out = Stream.newStream(); - WritableBufferedByteChannel wChannel = newBufferedChannel( out ); - EventChannelEncoder encoder = new EventChannelEncoder( wChannel ); - encoder.testOutput( new TestOutputReportEntry( stdOut( null ), NORMAL_RUN, 1L ) ); + WritableBufferedByteChannel wChannel = newBufferedChannel(out); + EventChannelEncoder encoder = new EventChannelEncoder(wChannel); + encoder.testOutput(new TestOutputReportEntry(stdOut(null), NORMAL_RUN, 1L)); wChannel.close(); - ReadableByteChannel channel = newChannel( new ByteArrayInputStream( out.toByteArray() ) ); + ReadableByteChannel channel = newChannel(new ByteArrayInputStream(out.toByteArray())); ForkedProcessEventNotifier notifier = new ForkedProcessEventNotifier(); StandardOutErrEventAssertionListener listener = - new StandardOutErrEventAssertionListener( NORMAL_RUN, 1L, null, false ); - notifier.setStdOutListener( listener ); + new StandardOutErrEventAssertionListener(NORMAL_RUN, 1L, null, false); + notifier.setStdOutListener(listener); EH eventHandler = new EH(); - CountdownCloseable countdown = new CountdownCloseable( mock( Closeable.class ), 0 ); - ConsoleLoggerMock logger = new ConsoleLoggerMock( false, false, false, false ); - ForkNodeArgumentsMock arguments = new ForkNodeArgumentsMock( logger, new File( "" ) ); - try ( EventConsumerThread t = new EventConsumerThread( "t", channel, eventHandler, countdown, arguments ) ) - { + CountdownCloseable countdown = new CountdownCloseable(mock(Closeable.class), 0); + ConsoleLoggerMock logger = new ConsoleLoggerMock(false, false, false, false); + ForkNodeArgumentsMock arguments = new ForkNodeArgumentsMock(logger, new File("")); + try (EventConsumerThread t = new EventConsumerThread("t", channel, eventHandler, countdown, arguments)) { t.start(); - notifier.notifyEvent( eventHandler.pullEvent() ); + notifier.notifyEvent(eventHandler.pullEvent()); } - assertThat( logger.error ).isEmpty(); - assertThat( logger.warning ).isEmpty(); - assertThat( logger.info ).isEmpty(); - assertThat( logger.debug ).isEmpty(); - - assertThat( logger.isCalled() ) - .isFalse(); - assertThat( arguments.isCalled() ) - .isFalse(); - assertThat( listener.called.get() ) - .isTrue(); + assertThat(logger.error).isEmpty(); + assertThat(logger.warning).isEmpty(); + assertThat(logger.info).isEmpty(); + assertThat(logger.debug).isEmpty(); + + assertThat(logger.isCalled()).isFalse(); + assertThat(arguments.isCalled()).isFalse(); + assertThat(listener.called.get()).isTrue(); } @Test - public void testStdOutStreamPrintln() throws Exception - { + public void testStdOutStreamPrintln() throws Exception { final Stream out = Stream.newStream(); - WritableBufferedByteChannel wChannel = newBufferedChannel( out ); - EventChannelEncoder encoder = new EventChannelEncoder( wChannel ); - encoder.testOutput( new TestOutputReportEntry( stdOutln( "" ), NORMAL_RUN, 1L ) ); + WritableBufferedByteChannel wChannel = newBufferedChannel(out); + EventChannelEncoder encoder = new EventChannelEncoder(wChannel); + encoder.testOutput(new TestOutputReportEntry(stdOutln(""), NORMAL_RUN, 1L)); wChannel.close(); - ReadableByteChannel channel = newChannel( new ByteArrayInputStream( out.toByteArray() ) ); + ReadableByteChannel channel = newChannel(new ByteArrayInputStream(out.toByteArray())); ForkedProcessEventNotifier notifier = new ForkedProcessEventNotifier(); StandardOutErrEventAssertionListener listener = - new StandardOutErrEventAssertionListener( NORMAL_RUN, 1L, "", true ); - notifier.setStdOutListener( listener ); + new StandardOutErrEventAssertionListener(NORMAL_RUN, 1L, "", true); + notifier.setStdOutListener(listener); EH eventHandler = new EH(); - CountdownCloseable countdown = new CountdownCloseable( mock( Closeable.class ), 0 ); - ConsoleLoggerMock logger = new ConsoleLoggerMock( false, false, false, false ); - ForkNodeArgumentsMock arguments = new ForkNodeArgumentsMock( logger, new File( "" ) ); - try ( EventConsumerThread t = new EventConsumerThread( "t", channel, eventHandler, countdown, arguments ) ) - { + CountdownCloseable countdown = new CountdownCloseable(mock(Closeable.class), 0); + ConsoleLoggerMock logger = new ConsoleLoggerMock(false, false, false, false); + ForkNodeArgumentsMock arguments = new ForkNodeArgumentsMock(logger, new File("")); + try (EventConsumerThread t = new EventConsumerThread("t", channel, eventHandler, countdown, arguments)) { t.start(); - notifier.notifyEvent( eventHandler.pullEvent() ); + notifier.notifyEvent(eventHandler.pullEvent()); } - assertThat( logger.error ).isEmpty(); - assertThat( logger.warning ).isEmpty(); - assertThat( logger.info ).isEmpty(); - assertThat( logger.debug ).isEmpty(); - - assertThat( logger.isCalled() ) - .isFalse(); - assertThat( arguments.isCalled() ) - .isFalse(); - assertThat( listener.called.get() ) - .isTrue(); + assertThat(logger.error).isEmpty(); + assertThat(logger.warning).isEmpty(); + assertThat(logger.info).isEmpty(); + assertThat(logger.debug).isEmpty(); + + assertThat(logger.isCalled()).isFalse(); + assertThat(arguments.isCalled()).isFalse(); + assertThat(listener.called.get()).isTrue(); } @Test - public void testStdOutStreamPrintlnWithNull() throws Exception - { + public void testStdOutStreamPrintlnWithNull() throws Exception { final Stream out = Stream.newStream(); - WritableBufferedByteChannel wChannel = newBufferedChannel( out ); - EventChannelEncoder encoder = new EventChannelEncoder( wChannel ); - encoder.testOutput( new TestOutputReportEntry( stdOutln( null ), NORMAL_RUN, 1L ) ); + WritableBufferedByteChannel wChannel = newBufferedChannel(out); + EventChannelEncoder encoder = new EventChannelEncoder(wChannel); + encoder.testOutput(new TestOutputReportEntry(stdOutln(null), NORMAL_RUN, 1L)); wChannel.close(); - ReadableByteChannel channel = newChannel( new ByteArrayInputStream( out.toByteArray() ) ); + ReadableByteChannel channel = newChannel(new ByteArrayInputStream(out.toByteArray())); ForkedProcessEventNotifier notifier = new ForkedProcessEventNotifier(); StandardOutErrEventAssertionListener listener = - new StandardOutErrEventAssertionListener( NORMAL_RUN, 1L, null, true ); - notifier.setStdOutListener( listener ); + new StandardOutErrEventAssertionListener(NORMAL_RUN, 1L, null, true); + notifier.setStdOutListener(listener); EH eventHandler = new EH(); - CountdownCloseable countdown = new CountdownCloseable( mock( Closeable.class ), 0 ); - ConsoleLoggerMock logger = new ConsoleLoggerMock( false, false, false, false ); - ForkNodeArgumentsMock arguments = new ForkNodeArgumentsMock( logger, new File( "" ) ); - try ( EventConsumerThread t = new EventConsumerThread( "t", channel, eventHandler, countdown, arguments ) ) - { + CountdownCloseable countdown = new CountdownCloseable(mock(Closeable.class), 0); + ConsoleLoggerMock logger = new ConsoleLoggerMock(false, false, false, false); + ForkNodeArgumentsMock arguments = new ForkNodeArgumentsMock(logger, new File("")); + try (EventConsumerThread t = new EventConsumerThread("t", channel, eventHandler, countdown, arguments)) { t.start(); - notifier.notifyEvent( eventHandler.pullEvent() ); + notifier.notifyEvent(eventHandler.pullEvent()); } - assertThat( logger.error ).isEmpty(); - assertThat( logger.warning ).isEmpty(); - assertThat( logger.info ).isEmpty(); - assertThat( logger.debug ).isEmpty(); - - assertThat( logger.isCalled() ) - .isFalse(); - assertThat( arguments.isCalled() ) - .isFalse(); - assertThat( listener.called.get() ) - .isTrue(); + assertThat(logger.error).isEmpty(); + assertThat(logger.warning).isEmpty(); + assertThat(logger.info).isEmpty(); + assertThat(logger.debug).isEmpty(); + + assertThat(logger.isCalled()).isFalse(); + assertThat(arguments.isCalled()).isFalse(); + assertThat(listener.called.get()).isTrue(); } @Test - public void testStdErrStream() throws Exception - { + public void testStdErrStream() throws Exception { final Stream out = Stream.newStream(); - WritableBufferedByteChannel wChannel = newBufferedChannel( out ); - EventChannelEncoder encoder = new EventChannelEncoder( wChannel ); - encoder.testOutput( new TestOutputReportEntry( stdErr( "msg" ), NORMAL_RUN, 1L ) ); + WritableBufferedByteChannel wChannel = newBufferedChannel(out); + EventChannelEncoder encoder = new EventChannelEncoder(wChannel); + encoder.testOutput(new TestOutputReportEntry(stdErr("msg"), NORMAL_RUN, 1L)); wChannel.close(); - ReadableByteChannel channel = newChannel( new ByteArrayInputStream( out.toByteArray() ) ); + ReadableByteChannel channel = newChannel(new ByteArrayInputStream(out.toByteArray())); ForkedProcessEventNotifier notifier = new ForkedProcessEventNotifier(); StandardOutErrEventAssertionListener listener = - new StandardOutErrEventAssertionListener( NORMAL_RUN, 1L, "msg", false ); - notifier.setStdErrListener( listener ); + new StandardOutErrEventAssertionListener(NORMAL_RUN, 1L, "msg", false); + notifier.setStdErrListener(listener); EH eventHandler = new EH(); - CountdownCloseable countdown = new CountdownCloseable( mock( Closeable.class ), 0 ); - ConsoleLoggerMock logger = new ConsoleLoggerMock( false, false, false, false ); - ForkNodeArgumentsMock arguments = new ForkNodeArgumentsMock( logger, new File( "" ) ); - try ( EventConsumerThread t = new EventConsumerThread( "t", channel, eventHandler, countdown, arguments ) ) - { + CountdownCloseable countdown = new CountdownCloseable(mock(Closeable.class), 0); + ConsoleLoggerMock logger = new ConsoleLoggerMock(false, false, false, false); + ForkNodeArgumentsMock arguments = new ForkNodeArgumentsMock(logger, new File("")); + try (EventConsumerThread t = new EventConsumerThread("t", channel, eventHandler, countdown, arguments)) { t.start(); - notifier.notifyEvent( eventHandler.pullEvent() ); + notifier.notifyEvent(eventHandler.pullEvent()); } - assertThat( logger.error ).isEmpty(); - assertThat( logger.warning ).isEmpty(); - assertThat( logger.info ).isEmpty(); - assertThat( logger.debug ).isEmpty(); - - assertThat( logger.isCalled() ) - .isFalse(); - assertThat( arguments.isCalled() ) - .isFalse(); - assertThat( listener.called.get() ) - .isTrue(); + assertThat(logger.error).isEmpty(); + assertThat(logger.warning).isEmpty(); + assertThat(logger.info).isEmpty(); + assertThat(logger.debug).isEmpty(); + + assertThat(logger.isCalled()).isFalse(); + assertThat(arguments.isCalled()).isFalse(); + assertThat(listener.called.get()).isTrue(); } @Test - public void shouldHandleErrorAfterNullLine() - { + public void shouldHandleErrorAfterNullLine() { ForkedProcessEventNotifier decoder = new ForkedProcessEventNotifier(); - decoder.setSystemPropertiesListener( new PropertyEventAssertionListener() ); - rule.expect( NullPointerException.class ); - decoder.notifyEvent( null ); + decoder.setSystemPropertiesListener(new PropertyEventAssertionListener()); + rule.expect(NullPointerException.class); + decoder.notifyEvent(null); } @Test - public void shouldHandleErrorAfterUnknownOperation() throws Exception - { + public void shouldHandleErrorAfterUnknownOperation() throws Exception { String cmd = ":maven-surefire-event:\u000c:abnormal-run:-:\n"; - ReadableByteChannel channel = newChannel( new ByteArrayInputStream( cmd.getBytes() ) ); + ReadableByteChannel channel = newChannel(new ByteArrayInputStream(cmd.getBytes())); EH eventHandler = new EH(); - CountdownCloseable countdown = new CountdownCloseable( mock( Closeable.class ), 1 ); - ConsoleLoggerMock logger = new ConsoleLoggerMock( true, true, true, true ); - ForkNodeArgumentsMock arguments = new ForkNodeArgumentsMock( logger, new File( "" ) ); - try ( EventConsumerThread t = new EventConsumerThread( "t", channel, eventHandler, countdown, arguments ) ) - { + CountdownCloseable countdown = new CountdownCloseable(mock(Closeable.class), 1); + ConsoleLoggerMock logger = new ConsoleLoggerMock(true, true, true, true); + ForkNodeArgumentsMock arguments = new ForkNodeArgumentsMock(logger, new File("")); + try (EventConsumerThread t = new EventConsumerThread("t", channel, eventHandler, countdown, arguments)) { t.start(); countdown.awaitClosed(); } - assertThat( arguments.isCalled() ) - .isTrue(); + assertThat(arguments.isCalled()).isTrue(); - assertThat( logger.isCalled() ) - .isTrue(); + assertThat(logger.isCalled()).isTrue(); - assertThat( logger.debug ) - .hasSize( 1 ); + assertThat(logger.debug).hasSize(1); - assertThat( logger.debug.peek() ) - .contains( ":maven-surefire-event:\u000c:abnormal-run:-:" ); + assertThat(logger.debug.peek()).contains(":maven-surefire-event:\u000c:abnormal-run:-:"); String dump = "Corrupted channel by directly writing to native stream in forked JVM 0."; - assertThat( arguments.dumpStreamText ) - .hasSize( 1 ) - .contains( format( dump + " Stream '%s'.", ":maven-surefire-event:\u000c:abnormal-run:-:" ) ); + assertThat(arguments.dumpStreamText) + .hasSize(1) + .contains(format(dump + " Stream '%s'.", ":maven-surefire-event:\u000c:abnormal-run:-:")); dump += " See FAQ web page and the dump file "; - assertThat( arguments.logWarningAtEnd ) - .hasSize( 1 ); - assertThat( arguments.logWarningAtEnd.peek() ) - .startsWith( dump ); + assertThat(arguments.logWarningAtEnd).hasSize(1); + assertThat(arguments.logWarningAtEnd.peek()).startsWith(dump); } @Test - public void shouldHandleExit() throws Exception - { + public void shouldHandleExit() throws Exception { final Stream out = Stream.newStream(); - EventChannelEncoder encoder = new EventChannelEncoder( newBufferedChannel( out ) ); + EventChannelEncoder encoder = new EventChannelEncoder(newBufferedChannel(out)); - StackTraceWriter stackTraceWriter = mock( StackTraceWriter.class ); - when( stackTraceWriter.getThrowable() ).thenReturn( new SafeThrowable( "1" ) ); - when( stackTraceWriter.smartTrimmedStackTrace() ).thenReturn( "2" ); - when( stackTraceWriter.writeTraceToString() ).thenReturn( "3" ); - when( stackTraceWriter.writeTrimmedTraceToString() ).thenReturn( "4" ); - encoder.sendExitError( stackTraceWriter, false ); + StackTraceWriter stackTraceWriter = mock(StackTraceWriter.class); + when(stackTraceWriter.getThrowable()).thenReturn(new SafeThrowable("1")); + when(stackTraceWriter.smartTrimmedStackTrace()).thenReturn("2"); + when(stackTraceWriter.writeTraceToString()).thenReturn("3"); + when(stackTraceWriter.writeTrimmedTraceToString()).thenReturn("4"); + encoder.sendExitError(stackTraceWriter, false); - ReadableByteChannel channel = newChannel( new ByteArrayInputStream( out.toByteArray() ) ); + ReadableByteChannel channel = newChannel(new ByteArrayInputStream(out.toByteArray())); ForkedProcessEventNotifier notifier = new ForkedProcessEventNotifier(); ProcessExitErrorListener listener = new ProcessExitErrorListener(); - notifier.setExitErrorEventListener( listener ); + notifier.setExitErrorEventListener(listener); EH eventHandler = new EH(); - CountdownCloseable countdown = new CountdownCloseable( mock( Closeable.class ), 0 ); - ConsoleLoggerMock logger = new ConsoleLoggerMock( false, false, false, false ); - ForkNodeArgumentsMock arguments = new ForkNodeArgumentsMock( logger, new File( "" ) ); - try ( EventConsumerThread t = new EventConsumerThread( "t", channel, eventHandler, countdown, arguments ) ) - { + CountdownCloseable countdown = new CountdownCloseable(mock(Closeable.class), 0); + ConsoleLoggerMock logger = new ConsoleLoggerMock(false, false, false, false); + ForkNodeArgumentsMock arguments = new ForkNodeArgumentsMock(logger, new File("")); + try (EventConsumerThread t = new EventConsumerThread("t", channel, eventHandler, countdown, arguments)) { t.start(); - notifier.notifyEvent( eventHandler.pullEvent() ); + notifier.notifyEvent(eventHandler.pullEvent()); } - assertThat( logger.error ).isEmpty(); - assertThat( logger.warning ).isEmpty(); - assertThat( logger.info ).isEmpty(); - assertThat( logger.debug ).isEmpty(); - - assertThat( logger.isCalled() ) - .isFalse(); - assertThat( arguments.isCalled() ) - .isFalse(); - assertThat( listener.called.get() ) - .isTrue(); + assertThat(logger.error).isEmpty(); + assertThat(logger.warning).isEmpty(); + assertThat(logger.info).isEmpty(); + assertThat(logger.debug).isEmpty(); + + assertThat(logger.isCalled()).isFalse(); + assertThat(arguments.isCalled()).isFalse(); + assertThat(listener.called.get()).isTrue(); } } /** * */ - @RunWith( Theories.class ) - public static class ReportEntryTest - { - @DataPoints( value = "operation" ) - @SuppressWarnings( "checkstyle:visibilitymodifier" ) - public static String[][] operations = { { "testSetStarting", "setTestSetStartingListener" }, - { "testSetCompleted", "setTestSetCompletedListener" }, - { "testStarting", "setTestStartingListener" }, - { "testSucceeded", "setTestSucceededListener" }, - { "testFailed", "setTestFailedListener" }, - { "testSkipped", "setTestSkippedListener" }, - { "testError", "setTestErrorListener" }, - { "testAssumptionFailure", "setTestAssumptionFailureListener" } + @RunWith(Theories.class) + public static class ReportEntryTest { + @DataPoints(value = "operation") + @SuppressWarnings("checkstyle:visibilitymodifier") + public static String[][] operations = { + {"testSetStarting", "setTestSetStartingListener"}, + {"testSetCompleted", "setTestSetCompletedListener"}, + {"testStarting", "setTestStartingListener"}, + {"testSucceeded", "setTestSucceededListener"}, + {"testFailed", "setTestFailedListener"}, + {"testSkipped", "setTestSkippedListener"}, + {"testError", "setTestErrorListener"}, + {"testAssumptionFailure", "setTestAssumptionFailureListener"} }; - @DataPoints( value = "reportedMessage" ) - @SuppressWarnings( "checkstyle:visibilitymodifier" ) - public static String[] reportedMessage = { null, "skipped test" }; + @DataPoints(value = "reportedMessage") + @SuppressWarnings("checkstyle:visibilitymodifier") + public static String[] reportedMessage = {null, "skipped test"}; - @DataPoints( value = "elapsed" ) - @SuppressWarnings( { "checkstyle:visibilitymodifier", "checkstyle:magicnumber" } ) - public static Integer[] elapsed = { null, 102 }; + @DataPoints(value = "elapsed") + @SuppressWarnings({"checkstyle:visibilitymodifier", "checkstyle:magicnumber"}) + public static Integer[] elapsed = {null, 102}; - @DataPoints( value = "trim" ) - @SuppressWarnings( "checkstyle:visibilitymodifier" ) - public static boolean[] trim = { false, true }; + @DataPoints(value = "trim") + @SuppressWarnings("checkstyle:visibilitymodifier") + public static boolean[] trim = {false, true}; - @DataPoints( value = "msg" ) - @SuppressWarnings( "checkstyle:visibilitymodifier" ) - public static boolean[] msg = { false, true }; + @DataPoints(value = "msg") + @SuppressWarnings("checkstyle:visibilitymodifier") + public static boolean[] msg = {false, true}; - @DataPoints( value = "smart" ) - @SuppressWarnings( "checkstyle:visibilitymodifier" ) - public static boolean[] smart = { false, true }; + @DataPoints(value = "smart") + @SuppressWarnings("checkstyle:visibilitymodifier") + public static boolean[] smart = {false, true}; - @DataPoints( value = "trace" ) - @SuppressWarnings( "checkstyle:visibilitymodifier" ) - public static boolean[] trace = { false, true }; + @DataPoints(value = "trace") + @SuppressWarnings("checkstyle:visibilitymodifier") + public static boolean[] trace = {false, true}; @Theory - public void testReportEntryOperations( @FromDataPoints( "operation" ) String[] operation, - @FromDataPoints( "reportedMessage" ) String reportedMessage, - @FromDataPoints( "elapsed" ) Integer elapsed, - @FromDataPoints( "trim" ) boolean trim, - @FromDataPoints( "msg" ) boolean msg, - @FromDataPoints( "smart" ) boolean smart, - @FromDataPoints( "trace" ) boolean trace ) - throws Exception - { + public void testReportEntryOperations( + @FromDataPoints("operation") String[] operation, + @FromDataPoints("reportedMessage") String reportedMessage, + @FromDataPoints("elapsed") Integer elapsed, + @FromDataPoints("trim") boolean trim, + @FromDataPoints("msg") boolean msg, + @FromDataPoints("smart") boolean smart, + @FromDataPoints("trace") boolean trace) + throws Exception { String exceptionMessage = msg ? "msg" : null; String smartStackTrace = smart ? "MyTest:86 >> Error" : null; String exceptionStackTrace = - trace ? ( trim ? "trace line 1\ntrace line 2" : "Exception: msg\ntrace line 1\ntrace line 2" ) - : null; + trace ? (trim ? "trace line 1\ntrace line 2" : "Exception: msg\ntrace line 1\ntrace line 2") : null; StackTraceWriter stackTraceWriter = null; - if ( exceptionStackTrace != null ) - { - SafeThrowable safeThrowable = new SafeThrowable( exceptionMessage ); - stackTraceWriter = mock( StackTraceWriter.class ); - when( stackTraceWriter.getThrowable() ).thenReturn( safeThrowable ); - when( stackTraceWriter.smartTrimmedStackTrace() ).thenReturn( smartStackTrace ); - when( stackTraceWriter.writeTrimmedTraceToString() ).thenReturn( exceptionStackTrace ); - when( stackTraceWriter.writeTraceToString() ).thenReturn( exceptionStackTrace ); + if (exceptionStackTrace != null) { + SafeThrowable safeThrowable = new SafeThrowable(exceptionMessage); + stackTraceWriter = mock(StackTraceWriter.class); + when(stackTraceWriter.getThrowable()).thenReturn(safeThrowable); + when(stackTraceWriter.smartTrimmedStackTrace()).thenReturn(smartStackTrace); + when(stackTraceWriter.writeTrimmedTraceToString()).thenReturn(exceptionStackTrace); + when(stackTraceWriter.writeTraceToString()).thenReturn(exceptionStackTrace); } - TestSetReportEntry reportEntry = mock( TestSetReportEntry.class ); - when( reportEntry.getRunMode() ).thenReturn( NORMAL_RUN ); - when( reportEntry.getTestRunId() ).thenReturn( 1L ); - when( reportEntry.getElapsed() ).thenReturn( elapsed ); - when( reportEntry.getGroup() ).thenReturn( "this group" ); - when( reportEntry.getMessage() ).thenReturn( reportedMessage ); - when( reportEntry.getName() ).thenReturn( "my test" ); - when( reportEntry.getName() ).thenReturn( "display name of test" ); - when( reportEntry.getNameWithGroup() ).thenReturn( "name with group" ); - when( reportEntry.getSourceName() ).thenReturn( "pkg.MyTest" ); - when( reportEntry.getSourceText() ).thenReturn( "test class display name" ); - when( reportEntry.getStackTraceWriter() ).thenReturn( stackTraceWriter ); - when( reportEntry.getSystemProperties() ).thenReturn( systemProps() ); + TestSetReportEntry reportEntry = mock(TestSetReportEntry.class); + when(reportEntry.getRunMode()).thenReturn(NORMAL_RUN); + when(reportEntry.getTestRunId()).thenReturn(1L); + when(reportEntry.getElapsed()).thenReturn(elapsed); + when(reportEntry.getGroup()).thenReturn("this group"); + when(reportEntry.getMessage()).thenReturn(reportedMessage); + when(reportEntry.getName()).thenReturn("my test"); + when(reportEntry.getName()).thenReturn("display name of test"); + when(reportEntry.getNameWithGroup()).thenReturn("name with group"); + when(reportEntry.getSourceName()).thenReturn("pkg.MyTest"); + when(reportEntry.getSourceText()).thenReturn("test class display name"); + when(reportEntry.getStackTraceWriter()).thenReturn(stackTraceWriter); + when(reportEntry.getSystemProperties()).thenReturn(systemProps()); final Stream out = Stream.newStream(); - EventChannelEncoder encoder = new EventChannelEncoder( newBufferedChannel( out ) ); + EventChannelEncoder encoder = new EventChannelEncoder(newBufferedChannel(out)); - Class reportType = operation[0].startsWith( "testSet" ) ? TestSetReportEntry.class : ReportEntry.class; - EventChannelEncoder.class.getMethod( operation[0], reportType, boolean.class ) - .invoke( encoder, reportEntry, trim ); + Class reportType = operation[0].startsWith("testSet") ? TestSetReportEntry.class : ReportEntry.class; + EventChannelEncoder.class + .getMethod(operation[0], reportType, boolean.class) + .invoke(encoder, reportEntry, trim); ForkedProcessEventNotifier notifier = new ForkedProcessEventNotifier(); - ForkedProcessEventNotifier.class.getMethod( operation[1], ForkedProcessReportEventListener.class ) - .invoke( notifier, new ReportEventAssertionListener( reportEntry, stackTraceWriter != null ) ); + ForkedProcessEventNotifier.class + .getMethod(operation[1], ForkedProcessReportEventListener.class) + .invoke(notifier, new ReportEventAssertionListener(reportEntry, stackTraceWriter != null)); - ReadableByteChannel channel = newChannel( new ByteArrayInputStream( out.toByteArray() ) ); + ReadableByteChannel channel = newChannel(new ByteArrayInputStream(out.toByteArray())); EH eventHandler = new EH(); - CountdownCloseable countdown = new CountdownCloseable( mock( Closeable.class ), 0 ); - ConsoleLoggerMock logger = new ConsoleLoggerMock( false, false, false, false ); - ForkNodeArgumentsMock arguments = new ForkNodeArgumentsMock( logger, new File( "" ) ); - try ( EventConsumerThread t = new EventConsumerThread( "t", channel, eventHandler, countdown, arguments ) ) - { + CountdownCloseable countdown = new CountdownCloseable(mock(Closeable.class), 0); + ConsoleLoggerMock logger = new ConsoleLoggerMock(false, false, false, false); + ForkNodeArgumentsMock arguments = new ForkNodeArgumentsMock(logger, new File("")); + try (EventConsumerThread t = new EventConsumerThread("t", channel, eventHandler, countdown, arguments)) { t.start(); - notifier.notifyEvent( eventHandler.pullEvent() ); + notifier.notifyEvent(eventHandler.pullEvent()); } - assertThat( logger.error ).isEmpty(); - assertThat( logger.warning ).isEmpty(); - assertThat( logger.info ).isEmpty(); - assertThat( logger.debug ).isEmpty(); + assertThat(logger.error).isEmpty(); + assertThat(logger.warning).isEmpty(); + assertThat(logger.info).isEmpty(); + assertThat(logger.debug).isEmpty(); - assertThat( logger.isCalled() ) - .isFalse(); + assertThat(logger.isCalled()).isFalse(); - assertThat( arguments.isCalled() ) - .isFalse(); + assertThat(arguments.isCalled()).isFalse(); } } - private static class ProcessExitErrorListener implements ForkedProcessExitErrorListener - { + private static class ProcessExitErrorListener implements ForkedProcessExitErrorListener { final AtomicBoolean called = new AtomicBoolean(); @Override - public void handle( StackTraceWriter stackTrace ) - { - called.set( true ); - assertThat( stackTrace.getThrowable().getMessage() ).isEqualTo( "1" ); - assertThat( stackTrace.smartTrimmedStackTrace() ).isEqualTo( "2" ); - assertThat( stackTrace.writeTraceToString() ).isEqualTo( "3" ); + public void handle(StackTraceWriter stackTrace) { + called.set(true); + assertThat(stackTrace.getThrowable().getMessage()).isEqualTo("1"); + assertThat(stackTrace.smartTrimmedStackTrace()).isEqualTo("2"); + assertThat(stackTrace.writeTraceToString()).isEqualTo("3"); } } - private static class PropertyEventAssertionListener implements ForkedProcessPropertyEventListener - { + private static class PropertyEventAssertionListener implements ForkedProcessPropertyEventListener { final AtomicBoolean called = new AtomicBoolean(); private final Map sysProps = System.getProperties(); private final AtomicInteger counter = new AtomicInteger(); - public void handle( String key, String value, RunMode runMode, Long testRunId ) - { - called.set( true ); + public void handle(String key, String value, RunMode runMode, Long testRunId) { + called.set(true); counter.incrementAndGet(); - assertThat( runMode ).isEqualTo( NORMAL_RUN ); - assertThat( testRunId ).isEqualTo( 1L ); - assertTrue( sysProps.containsKey( key ) ); - assertThat( sysProps.get( key ) ).isEqualTo( value ); + assertThat(runMode).isEqualTo(NORMAL_RUN); + assertThat(testRunId).isEqualTo(1L); + assertTrue(sysProps.containsKey(key)); + assertThat(sysProps.get(key)).isEqualTo(value); } } - private static class EventAssertionListener implements ForkedProcessEventListener - { + private static class EventAssertionListener implements ForkedProcessEventListener { final AtomicBoolean called = new AtomicBoolean(); - public void handle() - { - called.set( true ); + public void handle() { + called.set(true); } } - private static class StringEventAssertionListener implements ForkedProcessStringEventListener - { + private static class StringEventAssertionListener implements ForkedProcessStringEventListener { final AtomicBoolean called = new AtomicBoolean(); private final String msg; - StringEventAssertionListener( String msg ) - { + StringEventAssertionListener(String msg) { this.msg = msg; } - public void handle( String msg ) - { - called.set( true ); - assertThat( msg ) - .isEqualTo( this.msg ); + public void handle(String msg) { + called.set(true); + assertThat(msg).isEqualTo(this.msg); } } - private static class StackTraceEventListener implements ForkedProcessStackTraceEventListener - { + private static class StackTraceEventListener implements ForkedProcessStackTraceEventListener { final AtomicBoolean called = new AtomicBoolean(); private final String msg; private final String smartStackTrace; private final String stackTrace; - StackTraceEventListener( String msg, String smartStackTrace, String stackTrace ) - { + StackTraceEventListener(String msg, String smartStackTrace, String stackTrace) { this.msg = msg; this.smartStackTrace = smartStackTrace; this.stackTrace = stackTrace; } @Override - public void handle( @Nonnull StackTraceWriter stackTrace ) - { - called.set( true ); + public void handle(@Nonnull StackTraceWriter stackTrace) { + called.set(true); - assertThat( stackTrace.getThrowable().getMessage() ) - .isEqualTo( msg ); + assertThat(stackTrace.getThrowable().getMessage()).isEqualTo(msg); - assertThat( stackTrace.smartTrimmedStackTrace() ) - .isEqualTo( smartStackTrace ); + assertThat(stackTrace.smartTrimmedStackTrace()).isEqualTo(smartStackTrace); - assertThat( stackTrace.writeTraceToString() ) - .isEqualTo( this.stackTrace ); + assertThat(stackTrace.writeTraceToString()).isEqualTo(this.stackTrace); } } - private static class StandardOutErrEventAssertionListener implements ForkedProcessStandardOutErrEventListener - { + private static class StandardOutErrEventAssertionListener implements ForkedProcessStandardOutErrEventListener { final AtomicBoolean called = new AtomicBoolean(); private final RunMode runMode; private final long testRunId; private final String output; private final boolean newLine; - StandardOutErrEventAssertionListener( RunMode runMode, long testRunId, String output, boolean newLine ) - { + StandardOutErrEventAssertionListener(RunMode runMode, long testRunId, String output, boolean newLine) { this.runMode = runMode; this.testRunId = testRunId; this.output = output; this.newLine = newLine; } - public void handle( String output, boolean newLine, RunMode runMode, Long testRunId ) - { - called.set( true ); + public void handle(String output, boolean newLine, RunMode runMode, Long testRunId) { + called.set(true); - assertThat( runMode ) - .isEqualTo( this.runMode ); + assertThat(runMode).isEqualTo(this.runMode); - assertThat( testRunId ) - .isEqualTo( this.testRunId ); + assertThat(testRunId).isEqualTo(this.testRunId); - assertThat( output ) - .isEqualTo( this.output ); + assertThat(output).isEqualTo(this.output); - assertThat( newLine ) - .isEqualTo( this.newLine ); + assertThat(newLine).isEqualTo(this.newLine); } } - private static class ReportEventAssertionListener implements ForkedProcessReportEventListener - { + private static class ReportEventAssertionListener implements ForkedProcessReportEventListener { final AtomicBoolean called = new AtomicBoolean(); private final ReportEntry reportEntry; private final boolean hasStackTrace; - ReportEventAssertionListener( ReportEntry reportEntry, boolean hasStackTrace ) - { + ReportEventAssertionListener(ReportEntry reportEntry, boolean hasStackTrace) { this.reportEntry = reportEntry; this.hasStackTrace = hasStackTrace; } - public void handle( ReportEntry reportEntry ) - { - called.set( true ); - assertThat( reportEntry.getSourceName() ).isEqualTo( this.reportEntry.getSourceName() ); - assertThat( reportEntry.getSourceText() ).isEqualTo( this.reportEntry.getSourceText() ); - assertThat( reportEntry.getName() ).isEqualTo( this.reportEntry.getName() ); - assertThat( reportEntry.getNameText() ).isEqualTo( this.reportEntry.getNameText() ); - assertThat( reportEntry.getGroup() ).isEqualTo( this.reportEntry.getGroup() ); - assertThat( reportEntry.getMessage() ).isEqualTo( this.reportEntry.getMessage() ); - assertThat( reportEntry.getElapsed() ).isEqualTo( this.reportEntry.getElapsed() ); - if ( reportEntry.getStackTraceWriter() == null ) - { - assertThat( hasStackTrace ).isFalse(); - assertThat( this.reportEntry.getStackTraceWriter() ).isNull(); - } - else - { - assertThat( hasStackTrace ).isTrue(); - assertThat( this.reportEntry.getStackTraceWriter() ).isNotNull(); - - assertThat( reportEntry.getStackTraceWriter().getThrowable().getMessage() ) - .isEqualTo( this.reportEntry.getStackTraceWriter().getThrowable().getMessage() ); - - assertThat( reportEntry.getStackTraceWriter().getThrowable().getLocalizedMessage() ) - .isEqualTo( this.reportEntry.getStackTraceWriter().getThrowable().getLocalizedMessage() ); - - assertThat( reportEntry.getStackTraceWriter().smartTrimmedStackTrace() ) - .isEqualTo( this.reportEntry.getStackTraceWriter().smartTrimmedStackTrace() ); + public void handle(ReportEntry reportEntry) { + called.set(true); + assertThat(reportEntry.getSourceName()).isEqualTo(this.reportEntry.getSourceName()); + assertThat(reportEntry.getSourceText()).isEqualTo(this.reportEntry.getSourceText()); + assertThat(reportEntry.getName()).isEqualTo(this.reportEntry.getName()); + assertThat(reportEntry.getNameText()).isEqualTo(this.reportEntry.getNameText()); + assertThat(reportEntry.getGroup()).isEqualTo(this.reportEntry.getGroup()); + assertThat(reportEntry.getMessage()).isEqualTo(this.reportEntry.getMessage()); + assertThat(reportEntry.getElapsed()).isEqualTo(this.reportEntry.getElapsed()); + if (reportEntry.getStackTraceWriter() == null) { + assertThat(hasStackTrace).isFalse(); + assertThat(this.reportEntry.getStackTraceWriter()).isNull(); + } else { + assertThat(hasStackTrace).isTrue(); + assertThat(this.reportEntry.getStackTraceWriter()).isNotNull(); + + assertThat(reportEntry.getStackTraceWriter().getThrowable().getMessage()) + .isEqualTo(this.reportEntry + .getStackTraceWriter() + .getThrowable() + .getMessage()); + + assertThat(reportEntry.getStackTraceWriter().getThrowable().getLocalizedMessage()) + .isEqualTo(this.reportEntry + .getStackTraceWriter() + .getThrowable() + .getLocalizedMessage()); + + assertThat(reportEntry.getStackTraceWriter().smartTrimmedStackTrace()) + .isEqualTo(this.reportEntry.getStackTraceWriter().smartTrimmedStackTrace()); } } } - private static class Stream extends PrintStream - { + private static class Stream extends PrintStream { private final ByteArrayOutputStream out; - Stream( ByteArrayOutputStream out ) - { - super( out, true ); + Stream(ByteArrayOutputStream out) { + super(out, true); this.out = out; } - byte[] toByteArray() - { + byte[] toByteArray() { return out.toByteArray(); } - LineNumberReader newReader( Charset streamCharset ) - { - return new LineNumberReader( new StringReader( new String( toByteArray(), streamCharset ) ) ); + LineNumberReader newReader(Charset streamCharset) { + return new LineNumberReader(new StringReader(new String(toByteArray(), streamCharset))); } - static Stream newStream() - { - return new Stream( new ByteArrayOutputStream() ); + static Stream newStream() { + return new Stream(new ByteArrayOutputStream()); } } - private static class EH implements EventHandler - { + private static class EH implements EventHandler { private final BlockingQueue cache = new LinkedTransferQueue<>(); - Event pullEvent() throws InterruptedException - { - return cache.poll( 1, TimeUnit.MINUTES ); + Event pullEvent() throws InterruptedException { + return cache.poll(1, TimeUnit.MINUTES); } @Override - public void handleEvent( @Nonnull Event event ) - { - cache.add( event ); + public void handleEvent(@Nonnull Event event) { + cache.add(event); } } /** * Threadsafe impl. Mockito and Powermock are not thread-safe. */ - private static class ForkNodeArgumentsMock implements ForkNodeArguments - { + private static class ForkNodeArgumentsMock implements ForkNodeArguments { private final ConcurrentLinkedQueue dumpStreamText = new ConcurrentLinkedQueue<>(); private final ConcurrentLinkedQueue logWarningAtEnd = new ConcurrentLinkedQueue<>(); private final ConsoleLogger logger; private final File dumpStreamTextFile; - ForkNodeArgumentsMock( ConsoleLogger logger, File dumpStreamTextFile ) - { + ForkNodeArgumentsMock(ConsoleLogger logger, File dumpStreamTextFile) { this.logger = logger; this.dumpStreamTextFile = dumpStreamTextFile; } @Nonnull @Override - public String getSessionId() - { + public String getSessionId() { throw new UnsupportedOperationException(); } @Override - public int getForkChannelId() - { + public int getForkChannelId() { return 0; } @Nonnull @Override - public File dumpStreamText( @Nonnull String text ) - { - dumpStreamText.add( text ); + public File dumpStreamText(@Nonnull String text) { + dumpStreamText.add(text); return dumpStreamTextFile; } @Nonnull @Override - public File dumpStreamException( @Nonnull Throwable t ) - { + public File dumpStreamException(@Nonnull Throwable t) { return dumpStreamTextFile; } @Override - public void logWarningAtEnd( @Nonnull String text ) - { - logWarningAtEnd.add( text ); + public void logWarningAtEnd(@Nonnull String text) { + logWarningAtEnd.add(text); } @Nonnull @Override - public ConsoleLogger getConsoleLogger() - { + public ConsoleLogger getConsoleLogger() { return logger; } @Nonnull @Override - public Object getConsoleLock() - { + public Object getConsoleLock() { return logger; } - boolean isCalled() - { + boolean isCalled() { return !dumpStreamText.isEmpty() || !logWarningAtEnd.isEmpty(); } @Override - public File getEventStreamBinaryFile() - { + public File getEventStreamBinaryFile() { return null; } @Override - public File getCommandStreamBinaryFile() - { + public File getCommandStreamBinaryFile() { return null; } } @@ -1269,8 +1120,7 @@ public File getCommandStreamBinaryFile() /** * Threadsafe impl. Mockito and Powermock are not thread-safe. */ - private static class ConsoleLoggerMock implements ConsoleLogger - { + private static class ConsoleLoggerMock implements ConsoleLogger { final ConcurrentLinkedQueue debug = new ConcurrentLinkedQueue<>(); final ConcurrentLinkedQueue info = new ConcurrentLinkedQueue<>(); final ConcurrentLinkedQueue warning = new ConcurrentLinkedQueue<>(); @@ -1283,8 +1133,7 @@ private static class ConsoleLoggerMock implements ConsoleLogger private volatile boolean isDebugEnabledCalled; private volatile boolean isInfoEnabledCalled; - ConsoleLoggerMock( boolean isDebug, boolean isInfo, boolean isWarning, boolean isError ) - { + ConsoleLoggerMock(boolean isDebug, boolean isInfo, boolean isWarning, boolean isError) { this.isDebug = isDebug; this.isInfo = isInfo; this.isWarning = isWarning; @@ -1292,77 +1141,66 @@ private static class ConsoleLoggerMock implements ConsoleLogger } @Override - public synchronized boolean isDebugEnabled() - { + public synchronized boolean isDebugEnabled() { isDebugEnabledCalled = true; called = true; return isDebug; } @Override - public synchronized void debug( String message ) - { - debug.add( message ); + public synchronized void debug(String message) { + debug.add(message); called = true; } @Override - public synchronized boolean isInfoEnabled() - { + public synchronized boolean isInfoEnabled() { isInfoEnabledCalled = true; called = true; return isInfo; } @Override - public synchronized void info( String message ) - { - info.add( message ); + public synchronized void info(String message) { + info.add(message); called = true; } @Override - public synchronized boolean isWarnEnabled() - { + public synchronized boolean isWarnEnabled() { called = true; return isWarning; } @Override - public synchronized void warning( String message ) - { - warning.add( message ); + public synchronized void warning(String message) { + warning.add(message); called = true; } @Override - public synchronized boolean isErrorEnabled() - { + public synchronized boolean isErrorEnabled() { called = true; return isError; } @Override - public synchronized void error( String message ) - { - error.add( message ); + public synchronized void error(String message) { + error.add(message); called = true; } @Override - public synchronized void error( String message, Throwable t ) - { + public synchronized void error(String message, Throwable t) { called = true; } @Override - public synchronized void error( Throwable t ) - { + public synchronized void error(Throwable t) { called = true; } - synchronized boolean isCalled() - { + synchronized boolean isCalled() { return called; } } diff --git a/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/extensions/StatelessReporterTest.java b/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/extensions/StatelessReporterTest.java index 59fde6bc12..41e6b250f2 100644 --- a/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/extensions/StatelessReporterTest.java +++ b/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/extensions/StatelessReporterTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire.extensions; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,226 +16,172 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.surefire.extensions; + +import java.io.File; +import java.util.Deque; +import java.util.HashMap; +import java.util.Map; -import org.apache.maven.surefire.extensions.StatelessReportEventListener; import org.apache.maven.plugin.surefire.extensions.junit5.JUnit5Xml30StatelessReporter; import org.apache.maven.plugin.surefire.report.StatelessXmlReporter; import org.apache.maven.plugin.surefire.report.TestSetStats; import org.apache.maven.plugin.surefire.report.WrappedReportEntry; +import org.apache.maven.surefire.extensions.StatelessReportEventListener; import org.junit.Test; -import java.io.File; -import java.util.Deque; -import java.util.HashMap; -import java.util.Map; - import static org.assertj.core.api.Assertions.assertThat; import static org.powermock.reflect.Whitebox.getInternalState; /** * tests for {@link SurefireStatelessReporter} and {@link JUnit5Xml30StatelessReporter}. */ -public class StatelessReporterTest -{ +public class StatelessReporterTest { @Test - public void shouldCloneXmlReporter() - { + public void shouldCloneXmlReporter() { SurefireStatelessReporter extension = new SurefireStatelessReporter(); - extension.setDisable( true ); - extension.setVersion( "V1" ); + extension.setDisable(true); + extension.setVersion("V1"); ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); - Object clone = extension.clone( classLoader ); - assertThat( clone ) - .isNotSameAs( extension ); - assertThat( clone ) - .isInstanceOf( SurefireStatelessReporter.class ); - assertThat( clone.toString() ) - .isEqualTo( "SurefireStatelessReporter{version=V1, disable=true}" ); - assertThat( ( (SurefireStatelessReporter) clone ).isDisable() ) - .isTrue(); - assertThat( ( (SurefireStatelessReporter) clone ).getVersion() ) - .isEqualTo( "V1" ); + Object clone = extension.clone(classLoader); + assertThat(clone).isNotSameAs(extension); + assertThat(clone).isInstanceOf(SurefireStatelessReporter.class); + assertThat(clone.toString()).isEqualTo("SurefireStatelessReporter{version=V1, disable=true}"); + assertThat(((SurefireStatelessReporter) clone).isDisable()).isTrue(); + assertThat(((SurefireStatelessReporter) clone).getVersion()).isEqualTo("V1"); } @Test - public void shouldAssertToStringXmlReporter() - { + public void shouldAssertToStringXmlReporter() { SurefireStatelessReporter extension = new SurefireStatelessReporter(); - assertThat( extension.toString() ) - .isEqualTo( "SurefireStatelessReporter{version=3.0, disable=false}" ); + assertThat(extension.toString()).isEqualTo("SurefireStatelessReporter{version=3.0, disable=false}"); } @Test - public void shouldCreateConsoleListener() - { - File target = new File( System.getProperty( "user.dir" ), "target" ); - File reportsDirectory = new File( target, "surefire-reports" ); + public void shouldCreateConsoleListener() { + File target = new File(System.getProperty("user.dir"), "target"); + File reportsDirectory = new File(target, "surefire-reports"); String reportNameSuffix = "suffix"; String schema = "https://maven.apache.org/surefire/maven-surefire-plugin/xsd/surefire-test-report-3.0.xsd"; Map> testClassMethodRunHistory = new HashMap<>(); - DefaultStatelessReportMojoConfiguration config = - new DefaultStatelessReportMojoConfiguration( reportsDirectory, reportNameSuffix, true, 5, schema, - testClassMethodRunHistory ); + DefaultStatelessReportMojoConfiguration config = new DefaultStatelessReportMojoConfiguration( + reportsDirectory, reportNameSuffix, true, 5, schema, testClassMethodRunHistory); SurefireStatelessReporter extension = new SurefireStatelessReporter(); - assertThat( extension.getVersion() ) - .isEqualTo( "3.0" ); - extension.setVersion( "V3" ); - assertThat( extension.getVersion() ) - .isEqualTo( "V3" ); - - assertThat( extension.isDisable() ) - .isFalse(); - extension.setDisable( true ); - assertThat( extension.isDisable() ) - .isTrue(); - - StatelessReportEventListener listener = extension.createListener( config ); - assertThat( listener ) - .isInstanceOf( StatelessXmlReporter.class ); - assertThat( (File) getInternalState( listener, "reportsDirectory" ) ) - .isSameAs( reportsDirectory ); - assertThat( (String) getInternalState( listener, "reportNameSuffix" ) ) - .isSameAs( reportNameSuffix ); - assertThat( (boolean) getInternalState( listener, "trimStackTrace" ) ) - .isEqualTo( true ); - assertThat( (Integer) getInternalState( listener, "rerunFailingTestsCount" ) ) - .isEqualTo( 5 ); - assertThat( (String) getInternalState( listener, "xsdSchemaLocation" ) ) - .isSameAs( schema ); - assertThat( (String) getInternalState( listener, "xsdVersion" ) ) - .isEqualTo( "V3" ); - assertThat( (Map) getInternalState( listener, "testClassMethodRunHistoryMap" ) ) - .isSameAs( testClassMethodRunHistory ); - assertThat( (boolean) getInternalState( listener, "phrasedFileName" ) ) - .isEqualTo( false ); - assertThat( (boolean) getInternalState( listener, "phrasedSuiteName" ) ) - .isEqualTo( false ); - assertThat( (boolean) getInternalState( listener, "phrasedClassName" ) ) - .isEqualTo( false ); - assertThat( (boolean) getInternalState( listener, "phrasedMethodName" ) ) - .isEqualTo( false ); + assertThat(extension.getVersion()).isEqualTo("3.0"); + extension.setVersion("V3"); + assertThat(extension.getVersion()).isEqualTo("V3"); + + assertThat(extension.isDisable()).isFalse(); + extension.setDisable(true); + assertThat(extension.isDisable()).isTrue(); + + StatelessReportEventListener listener = extension.createListener(config); + assertThat(listener).isInstanceOf(StatelessXmlReporter.class); + assertThat((File) getInternalState(listener, "reportsDirectory")).isSameAs(reportsDirectory); + assertThat((String) getInternalState(listener, "reportNameSuffix")).isSameAs(reportNameSuffix); + assertThat((boolean) getInternalState(listener, "trimStackTrace")).isEqualTo(true); + assertThat((Integer) getInternalState(listener, "rerunFailingTestsCount")) + .isEqualTo(5); + assertThat((String) getInternalState(listener, "xsdSchemaLocation")).isSameAs(schema); + assertThat((String) getInternalState(listener, "xsdVersion")).isEqualTo("V3"); + assertThat((Map) getInternalState(listener, "testClassMethodRunHistoryMap")) + .isSameAs(testClassMethodRunHistory); + assertThat((boolean) getInternalState(listener, "phrasedFileName")).isEqualTo(false); + assertThat((boolean) getInternalState(listener, "phrasedSuiteName")).isEqualTo(false); + assertThat((boolean) getInternalState(listener, "phrasedClassName")).isEqualTo(false); + assertThat((boolean) getInternalState(listener, "phrasedMethodName")).isEqualTo(false); } @Test - public void shouldCloneJUnit5XmlReporter() - { + public void shouldCloneJUnit5XmlReporter() { JUnit5Xml30StatelessReporter extension = new JUnit5Xml30StatelessReporter(); - extension.setDisable( true ); - extension.setVersion( "V1" ); - extension.setUsePhrasedFileName( true ); - extension.setUsePhrasedTestSuiteClassName( true ); - extension.setUsePhrasedTestCaseClassName( true ); - extension.setUsePhrasedTestCaseMethodName( true ); + extension.setDisable(true); + extension.setVersion("V1"); + extension.setUsePhrasedFileName(true); + extension.setUsePhrasedTestSuiteClassName(true); + extension.setUsePhrasedTestCaseClassName(true); + extension.setUsePhrasedTestCaseMethodName(true); ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); - Object clone = extension.clone( classLoader ); - assertThat( clone ) - .isNotSameAs( extension ); - assertThat( clone ) - .isInstanceOf( JUnit5Xml30StatelessReporter.class ); - assertThat( clone.toString() ) - .isEqualTo( "JUnit5Xml30StatelessReporter{version=V1, disable=true, usePhrasedFileName=true, " + Object clone = extension.clone(classLoader); + assertThat(clone).isNotSameAs(extension); + assertThat(clone).isInstanceOf(JUnit5Xml30StatelessReporter.class); + assertThat(clone.toString()) + .isEqualTo("JUnit5Xml30StatelessReporter{version=V1, disable=true, usePhrasedFileName=true, " + "usePhrasedTestSuiteClassName=true, usePhrasedTestCaseClassName=true, " - + "usePhrasedTestCaseMethodName=true}" ); - assertThat( ( (JUnit5Xml30StatelessReporter) clone ).isDisable() ) - .isTrue(); - assertThat( ( (JUnit5Xml30StatelessReporter) clone ).getVersion() ) - .isEqualTo( "V1" ); - assertThat( ( (JUnit5Xml30StatelessReporter) clone ).getUsePhrasedFileName() ) + + "usePhrasedTestCaseMethodName=true}"); + assertThat(((JUnit5Xml30StatelessReporter) clone).isDisable()).isTrue(); + assertThat(((JUnit5Xml30StatelessReporter) clone).getVersion()).isEqualTo("V1"); + assertThat(((JUnit5Xml30StatelessReporter) clone).getUsePhrasedFileName()) .isTrue(); - assertThat( ( (JUnit5Xml30StatelessReporter) clone ).getUsePhrasedTestCaseClassName() ) + assertThat(((JUnit5Xml30StatelessReporter) clone).getUsePhrasedTestCaseClassName()) .isTrue(); - assertThat( ( (JUnit5Xml30StatelessReporter) clone ).getUsePhrasedTestCaseMethodName() ) + assertThat(((JUnit5Xml30StatelessReporter) clone).getUsePhrasedTestCaseMethodName()) .isTrue(); - assertThat( ( (JUnit5Xml30StatelessReporter) clone ).getUsePhrasedTestSuiteClassName() ) + assertThat(((JUnit5Xml30StatelessReporter) clone).getUsePhrasedTestSuiteClassName()) .isTrue(); } @Test - public void shouldAssertToStringJUnit5ConsoleReporter() - { + public void shouldAssertToStringJUnit5ConsoleReporter() { JUnit5Xml30StatelessReporter extension = new JUnit5Xml30StatelessReporter(); - assertThat( extension.toString() ) - .isEqualTo( "JUnit5Xml30StatelessReporter{version=3.0, disable=false, " + assertThat(extension.toString()) + .isEqualTo("JUnit5Xml30StatelessReporter{version=3.0, disable=false, " + "usePhrasedFileName=false, usePhrasedTestSuiteClassName=false, " - + "usePhrasedTestCaseClassName=false, usePhrasedTestCaseMethodName=false}" ); + + "usePhrasedTestCaseClassName=false, usePhrasedTestCaseMethodName=false}"); } @Test - public void shouldCreateJUnit5ConsoleListener() - { - File target = new File( System.getProperty( "user.dir" ), "target" ); - File reportsDirectory = new File( target, "surefire-reports" ); + public void shouldCreateJUnit5ConsoleListener() { + File target = new File(System.getProperty("user.dir"), "target"); + File reportsDirectory = new File(target, "surefire-reports"); String reportNameSuffix = "suffix"; String schema = "https://maven.apache.org/surefire/maven-surefire-plugin/xsd/surefire-test-report-3.0.xsd"; Map> testClassMethodRunHistory = new HashMap<>(); - DefaultStatelessReportMojoConfiguration config = - new DefaultStatelessReportMojoConfiguration( reportsDirectory, reportNameSuffix, true, 5, schema, - testClassMethodRunHistory ); + DefaultStatelessReportMojoConfiguration config = new DefaultStatelessReportMojoConfiguration( + reportsDirectory, reportNameSuffix, true, 5, schema, testClassMethodRunHistory); JUnit5Xml30StatelessReporter extension = new JUnit5Xml30StatelessReporter(); - assertThat( extension.getVersion() ) - .isEqualTo( "3.0" ); - extension.setVersion( "V3" ); - assertThat( extension.getVersion() ) - .isEqualTo( "V3" ); - - assertThat( extension.isDisable() ) - .isFalse(); - extension.setDisable( true ); - assertThat( extension.isDisable() ) - .isTrue(); - - assertThat( extension.getUsePhrasedFileName() ) - .isFalse(); - extension.setUsePhrasedFileName( true ); - assertThat( extension.getUsePhrasedFileName() ) - .isTrue(); - - assertThat( extension.getUsePhrasedTestSuiteClassName() ) - .isFalse(); - extension.setUsePhrasedTestSuiteClassName( true ); - assertThat( extension.getUsePhrasedTestSuiteClassName() ) - .isTrue(); - - assertThat( extension.getUsePhrasedTestCaseClassName() ) - .isFalse(); - extension.setUsePhrasedTestCaseClassName( true ); - assertThat( extension.getUsePhrasedTestSuiteClassName() ) - .isTrue(); - - assertThat( extension.getUsePhrasedTestCaseMethodName() ) - .isFalse(); - extension.setUsePhrasedTestCaseMethodName( true ); - assertThat( extension.getUsePhrasedTestCaseMethodName() ) - .isTrue(); - - StatelessReportEventListener listener = extension.createListener( config ); - assertThat( listener ) - .isInstanceOf( StatelessXmlReporter.class ); - assertThat( (File) getInternalState( listener, "reportsDirectory" ) ) - .isSameAs( reportsDirectory ); - assertThat( (String) getInternalState( listener, "reportNameSuffix" ) ) - .isSameAs( reportNameSuffix ); - assertThat( (boolean) getInternalState( listener, "trimStackTrace" ) ) - .isEqualTo( true ); - assertThat( (Integer) getInternalState( listener, "rerunFailingTestsCount" ) ) - .isEqualTo( 5 ); - assertThat( (String) getInternalState( listener, "xsdSchemaLocation" ) ) - .isSameAs( schema ); - assertThat( (String) getInternalState( listener, "xsdVersion" ) ) - .isEqualTo( "V3" ); - assertThat( (Map) getInternalState( listener, "testClassMethodRunHistoryMap" ) ) - .isSameAs( testClassMethodRunHistory ); - assertThat( (boolean) getInternalState( listener, "phrasedFileName" ) ) - .isEqualTo( true ); - assertThat( (boolean) getInternalState( listener, "phrasedSuiteName" ) ) - .isEqualTo( true ); - assertThat( (boolean) getInternalState( listener, "phrasedClassName" ) ) - .isEqualTo( true ); - assertThat( (boolean) getInternalState( listener, "phrasedMethodName" ) ) - .isEqualTo( true ); + assertThat(extension.getVersion()).isEqualTo("3.0"); + extension.setVersion("V3"); + assertThat(extension.getVersion()).isEqualTo("V3"); + + assertThat(extension.isDisable()).isFalse(); + extension.setDisable(true); + assertThat(extension.isDisable()).isTrue(); + + assertThat(extension.getUsePhrasedFileName()).isFalse(); + extension.setUsePhrasedFileName(true); + assertThat(extension.getUsePhrasedFileName()).isTrue(); + + assertThat(extension.getUsePhrasedTestSuiteClassName()).isFalse(); + extension.setUsePhrasedTestSuiteClassName(true); + assertThat(extension.getUsePhrasedTestSuiteClassName()).isTrue(); + + assertThat(extension.getUsePhrasedTestCaseClassName()).isFalse(); + extension.setUsePhrasedTestCaseClassName(true); + assertThat(extension.getUsePhrasedTestSuiteClassName()).isTrue(); + + assertThat(extension.getUsePhrasedTestCaseMethodName()).isFalse(); + extension.setUsePhrasedTestCaseMethodName(true); + assertThat(extension.getUsePhrasedTestCaseMethodName()).isTrue(); + + StatelessReportEventListener listener = extension.createListener(config); + assertThat(listener).isInstanceOf(StatelessXmlReporter.class); + assertThat((File) getInternalState(listener, "reportsDirectory")).isSameAs(reportsDirectory); + assertThat((String) getInternalState(listener, "reportNameSuffix")).isSameAs(reportNameSuffix); + assertThat((boolean) getInternalState(listener, "trimStackTrace")).isEqualTo(true); + assertThat((Integer) getInternalState(listener, "rerunFailingTestsCount")) + .isEqualTo(5); + assertThat((String) getInternalState(listener, "xsdSchemaLocation")).isSameAs(schema); + assertThat((String) getInternalState(listener, "xsdVersion")).isEqualTo("V3"); + assertThat((Map) getInternalState(listener, "testClassMethodRunHistoryMap")) + .isSameAs(testClassMethodRunHistory); + assertThat((boolean) getInternalState(listener, "phrasedFileName")).isEqualTo(true); + assertThat((boolean) getInternalState(listener, "phrasedSuiteName")).isEqualTo(true); + assertThat((boolean) getInternalState(listener, "phrasedClassName")).isEqualTo(true); + assertThat((boolean) getInternalState(listener, "phrasedMethodName")).isEqualTo(true); } } diff --git a/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/extensions/StreamFeederTest.java b/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/extensions/StreamFeederTest.java index c7e3cd55a4..b3d8351706 100644 --- a/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/extensions/StreamFeederTest.java +++ b/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/extensions/StreamFeederTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire.extensions; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,14 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.surefire.extensions; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.nio.Buffer; +import java.nio.ByteBuffer; +import java.nio.channels.WritableByteChannel; +import java.util.Iterator; import org.apache.maven.plugin.surefire.log.api.ConsoleLogger; import org.apache.maven.surefire.api.booter.Command; @@ -28,13 +34,6 @@ import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.nio.Buffer; -import java.nio.ByteBuffer; -import java.nio.channels.WritableByteChannel; -import java.util.Iterator; - import static java.util.Arrays.asList; import static org.apache.maven.surefire.api.booter.Command.TEST_SET_FINISHED; import static org.apache.maven.surefire.api.booter.MasterProcessCommand.RUN_CLASS; @@ -49,120 +48,99 @@ /** * Tests for {@link StreamFeeder}. */ -public class StreamFeederTest -{ +public class StreamFeederTest { private final ByteArrayOutputStream out = new ByteArrayOutputStream(); - private final WritableByteChannel channel = mock( WritableByteChannel.class ); - private final CommandReader commandReader = mock( CommandReader.class ); + private final WritableByteChannel channel = mock(WritableByteChannel.class); + private final CommandReader commandReader = mock(CommandReader.class); private StreamFeeder streamFeeder; @Before - public void setup() throws IOException - { - final Iterator it = asList( new Command( RUN_CLASS, "pkg.ATest" ), TEST_SET_FINISHED ).iterator(); - when( commandReader.readNextCommand() ) - .thenAnswer( new Answer() - { - @Override - public Command answer( InvocationOnMock invocation ) - { - return it.hasNext() ? it.next() : null; - } - } ); + public void setup() throws IOException { + final Iterator it = + asList(new Command(RUN_CLASS, "pkg.ATest"), TEST_SET_FINISHED).iterator(); + when(commandReader.readNextCommand()).thenAnswer(new Answer() { + @Override + public Command answer(InvocationOnMock invocation) { + return it.hasNext() ? it.next() : null; + } + }); } @After - public void close() throws IOException - { - if ( streamFeeder != null ) - { + public void close() throws IOException { + if (streamFeeder != null) { streamFeeder.disable(); streamFeeder.close(); } } @Test - public void shouldEncodeCommandToStream() throws Exception - { - when( channel.write( any( ByteBuffer.class ) ) ) - .thenAnswer( new Answer() - { - @Override - public Object answer( InvocationOnMock invocation ) throws IOException - { - ByteBuffer bb = invocation.getArgument( 0 ); - ( (Buffer) bb ).flip(); - out.write( bb.array(), 0, ( (Buffer) bb ).limit() ); - return ( (Buffer) bb ).limit(); - } - } ); - - ConsoleLogger logger = mock( ConsoleLogger.class ); - streamFeeder = new StreamFeeder( "t", channel, commandReader, logger ); + public void shouldEncodeCommandToStream() throws Exception { + when(channel.write(any(ByteBuffer.class))).thenAnswer(new Answer() { + @Override + public Object answer(InvocationOnMock invocation) throws IOException { + ByteBuffer bb = invocation.getArgument(0); + ((Buffer) bb).flip(); + out.write(bb.array(), 0, ((Buffer) bb).limit()); + return ((Buffer) bb).limit(); + } + }); + + ConsoleLogger logger = mock(ConsoleLogger.class); + streamFeeder = new StreamFeeder("t", channel, commandReader, logger); streamFeeder.start(); streamFeeder.join(); String commands = out.toString(); String expected = new StringBuilder() - .append( ":maven-surefire-command:" ) - .append( (char) 13 ) - .append( ":run-testclass:" ) - .append( (char) 5 ) - .append( ":UTF-8:" ) - .append( (char) 0 ) - .append( (char) 0 ) - .append( (char) 0 ) - .append( (char) 9 ) - .append( ":" ) - .append( "pkg.ATest" ) - .append( ":" ) - .append( ":maven-surefire-command:" ) - .append( (char) 16 ) - .append( ":testset-finished:" ) - .toString(); - - assertThat( commands ) - .isEqualTo( expected ); - - verify( channel, times( 1 ) ) - .close(); - - assertThat( streamFeeder.getException() ) - .isNull(); - - verifyZeroInteractions( logger ); + .append(":maven-surefire-command:") + .append((char) 13) + .append(":run-testclass:") + .append((char) 5) + .append(":UTF-8:") + .append((char) 0) + .append((char) 0) + .append((char) 0) + .append((char) 9) + .append(":") + .append("pkg.ATest") + .append(":") + .append(":maven-surefire-command:") + .append((char) 16) + .append(":testset-finished:") + .toString(); + + assertThat(commands).isEqualTo(expected); + + verify(channel, times(1)).close(); + + assertThat(streamFeeder.getException()).isNull(); + + verifyZeroInteractions(logger); } @Test - public void shouldFailThread() throws Exception - { - when( channel.write( any( ByteBuffer.class ) ) ) - .thenAnswer( new Answer() - { - @Override - public Object answer( InvocationOnMock invocation ) throws IOException - { - throw new IOException(); - } - } ); - - ConsoleLogger logger = mock( ConsoleLogger.class ); - streamFeeder = new StreamFeeder( "t", channel, commandReader, logger ); + public void shouldFailThread() throws Exception { + when(channel.write(any(ByteBuffer.class))).thenAnswer(new Answer() { + @Override + public Object answer(InvocationOnMock invocation) throws IOException { + throw new IOException(); + } + }); + + ConsoleLogger logger = mock(ConsoleLogger.class); + streamFeeder = new StreamFeeder("t", channel, commandReader, logger); streamFeeder.start(); streamFeeder.join(); - assertThat( out.size() ) - .isZero(); + assertThat(out.size()).isZero(); - verify( channel, times( 1 ) ) - .close(); + verify(channel, times(1)).close(); - assertThat( streamFeeder.getException() ) - .isNotNull() - .isInstanceOf( IOException.class ); + assertThat(streamFeeder.getException()).isNotNull().isInstanceOf(IOException.class); - verifyZeroInteractions( logger ); + verifyZeroInteractions(logger); } } diff --git a/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/report/DefaultReporterFactoryTest.java b/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/report/DefaultReporterFactoryTest.java index b2f015b2f3..9d4c9f924a 100644 --- a/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/report/DefaultReporterFactoryTest.java +++ b/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/report/DefaultReporterFactoryTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire.report; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.surefire.report; import java.io.File; import java.util.ArrayDeque; @@ -27,19 +26,18 @@ import java.util.Queue; import junit.framework.TestCase; - import org.apache.maven.plugin.surefire.StartupReportConfiguration; import org.apache.maven.plugin.surefire.extensions.SurefireConsoleOutputReporter; import org.apache.maven.plugin.surefire.extensions.SurefireStatelessReporter; import org.apache.maven.plugin.surefire.extensions.SurefireStatelessTestsetInfoReporter; import org.apache.maven.plugin.surefire.log.api.ConsoleLogger; -import org.apache.maven.surefire.api.report.TestOutputReportEntry; -import org.apache.maven.surefire.api.report.TestReportListener; -import org.apache.maven.surefire.shared.utils.logging.MessageUtils; -import org.apache.maven.surefire.report.RunStatistics; import org.apache.maven.surefire.api.report.SafeThrowable; import org.apache.maven.surefire.api.report.StackTraceWriter; +import org.apache.maven.surefire.api.report.TestOutputReportEntry; +import org.apache.maven.surefire.api.report.TestReportListener; import org.apache.maven.surefire.api.suite.RunResult; +import org.apache.maven.surefire.report.RunStatistics; +import org.apache.maven.surefire.shared.utils.logging.MessageUtils; import static java.nio.charset.StandardCharsets.UTF_8; import static java.util.Arrays.asList; @@ -59,9 +57,7 @@ /** * */ -public class DefaultReporterFactoryTest - extends TestCase -{ +public class DefaultReporterFactoryTest extends TestCase { private static final String TEST_ONE = "testOne"; private static final String TEST_TWO = "testTwo"; @@ -76,356 +72,377 @@ public class DefaultReporterFactoryTest private static final String ERROR = "error"; - public void testMergeTestHistoryResult() - throws Exception - { - MessageUtils.setColorEnabled( false ); - File target = new File( System.getProperty( "user.dir" ), "target" ); - File reportsDirectory = new File( target, "tmp5" ); - StartupReportConfiguration reportConfig = - new StartupReportConfiguration( true, true, "PLAIN", false, reportsDirectory, false, null, - new File( reportsDirectory, "TESTHASH" ), false, 1, null, null, false, - new SurefireStatelessReporter(), new SurefireConsoleOutputReporter(), - new SurefireStatelessTestsetInfoReporter() ); + public void testMergeTestHistoryResult() throws Exception { + MessageUtils.setColorEnabled(false); + File target = new File(System.getProperty("user.dir"), "target"); + File reportsDirectory = new File(target, "tmp5"); + StartupReportConfiguration reportConfig = new StartupReportConfiguration( + true, + true, + "PLAIN", + false, + reportsDirectory, + false, + null, + new File(reportsDirectory, "TESTHASH"), + false, + 1, + null, + null, + false, + new SurefireStatelessReporter(), + new SurefireConsoleOutputReporter(), + new SurefireStatelessTestsetInfoReporter()); DummyTestReporter reporter = new DummyTestReporter(); - DefaultReporterFactory factory = new DefaultReporterFactory( reportConfig, reporter ); + DefaultReporterFactory factory = new DefaultReporterFactory(reportConfig, reporter); // First run, four tests failed and one passed Queue firstRunStats = new ArrayDeque<>(); - firstRunStats.add( new TestMethodStats( TEST_ONE, ReportEntryType.ERROR, new DummyStackTraceWriter( ERROR ) ) ); - firstRunStats.add( new TestMethodStats( TEST_TWO, ReportEntryType.ERROR, new DummyStackTraceWriter( ERROR ) ) ); - firstRunStats.add( - new TestMethodStats( TEST_THREE, ReportEntryType.FAILURE, new DummyStackTraceWriter( ASSERTION_FAIL ) ) ); + firstRunStats.add(new TestMethodStats(TEST_ONE, ReportEntryType.ERROR, new DummyStackTraceWriter(ERROR))); + firstRunStats.add(new TestMethodStats(TEST_TWO, ReportEntryType.ERROR, new DummyStackTraceWriter(ERROR))); firstRunStats.add( - new TestMethodStats( TEST_FOUR, ReportEntryType.FAILURE, new DummyStackTraceWriter( ASSERTION_FAIL ) ) ); + new TestMethodStats(TEST_THREE, ReportEntryType.FAILURE, new DummyStackTraceWriter(ASSERTION_FAIL))); firstRunStats.add( - new TestMethodStats( TEST_FIVE, ReportEntryType.SUCCESS, null ) ); + new TestMethodStats(TEST_FOUR, ReportEntryType.FAILURE, new DummyStackTraceWriter(ASSERTION_FAIL))); + firstRunStats.add(new TestMethodStats(TEST_FIVE, ReportEntryType.SUCCESS, null)); // Second run, two tests passed Queue secondRunStats = new ArrayDeque<>(); secondRunStats.add( - new TestMethodStats( TEST_ONE, ReportEntryType.FAILURE, new DummyStackTraceWriter( ASSERTION_FAIL ) ) ); - secondRunStats.add( new TestMethodStats( TEST_TWO, ReportEntryType.SUCCESS, null ) ); - secondRunStats.add( - new TestMethodStats( TEST_THREE, ReportEntryType.ERROR, new DummyStackTraceWriter( ERROR ) ) ); - secondRunStats.add( new TestMethodStats( TEST_FOUR, ReportEntryType.SUCCESS, null ) ); + new TestMethodStats(TEST_ONE, ReportEntryType.FAILURE, new DummyStackTraceWriter(ASSERTION_FAIL))); + secondRunStats.add(new TestMethodStats(TEST_TWO, ReportEntryType.SUCCESS, null)); + secondRunStats.add(new TestMethodStats(TEST_THREE, ReportEntryType.ERROR, new DummyStackTraceWriter(ERROR))); + secondRunStats.add(new TestMethodStats(TEST_FOUR, ReportEntryType.SUCCESS, null)); // Third run, another test passed Queue thirdRunStats = new ArrayDeque<>(); - thirdRunStats.add( new TestMethodStats( TEST_ONE, ReportEntryType.SUCCESS, null ) ); - thirdRunStats.add( - new TestMethodStats( TEST_THREE, ReportEntryType.ERROR, new DummyStackTraceWriter( ERROR ) ) ); - - TestSetRunListener firstRunListener = mock( TestSetRunListener.class ); - TestSetRunListener secondRunListener = mock( TestSetRunListener.class ); - TestSetRunListener thirdRunListener = mock( TestSetRunListener.class ); - when( firstRunListener.getTestMethodStats() ).thenReturn( firstRunStats ); - when( secondRunListener.getTestMethodStats() ).thenReturn( secondRunStats ); - when( thirdRunListener.getTestMethodStats() ).thenReturn( thirdRunStats ); - - factory.addListener( firstRunListener ); - factory.addListener( secondRunListener ); - factory.addListener( thirdRunListener ); - - invokeMethod( factory, "mergeTestHistoryResult" ); + thirdRunStats.add(new TestMethodStats(TEST_ONE, ReportEntryType.SUCCESS, null)); + thirdRunStats.add(new TestMethodStats(TEST_THREE, ReportEntryType.ERROR, new DummyStackTraceWriter(ERROR))); + + TestSetRunListener firstRunListener = mock(TestSetRunListener.class); + TestSetRunListener secondRunListener = mock(TestSetRunListener.class); + TestSetRunListener thirdRunListener = mock(TestSetRunListener.class); + when(firstRunListener.getTestMethodStats()).thenReturn(firstRunStats); + when(secondRunListener.getTestMethodStats()).thenReturn(secondRunStats); + when(thirdRunListener.getTestMethodStats()).thenReturn(thirdRunStats); + + factory.addListener(firstRunListener); + factory.addListener(secondRunListener); + factory.addListener(thirdRunListener); + + invokeMethod(factory, "mergeTestHistoryResult"); RunStatistics mergedStatistics = factory.getGlobalRunStatistics(); // Only TEST_THREE is a failing test, other three are flaky tests - assertEquals( 5, mergedStatistics.getCompletedCount() ); - assertEquals( 1, mergedStatistics.getErrors() ); - assertEquals( 0, mergedStatistics.getFailures() ); - assertEquals( 3, mergedStatistics.getFlakes() ); - assertEquals( 0, mergedStatistics.getSkipped() ); + assertEquals(5, mergedStatistics.getCompletedCount()); + assertEquals(1, mergedStatistics.getErrors()); + assertEquals(0, mergedStatistics.getFailures()); + assertEquals(3, mergedStatistics.getFlakes()); + assertEquals(0, mergedStatistics.getSkipped()); // Now test the result will be printed out correctly - factory.printTestFailures( flake ); - String[] expectedFlakeOutput = - { "Flakes: ", TEST_FOUR, " Run 1: " + ASSERTION_FAIL, " Run 2: PASS", "", TEST_ONE, - " Run 1: " + ERROR, " Run 2: " + ASSERTION_FAIL, " Run 3: PASS", "", TEST_TWO, " Run 1: " + ERROR, - " Run 2: PASS", "" }; - assertEquals( asList( expectedFlakeOutput ), reporter.getMessages() ); + factory.printTestFailures(flake); + String[] expectedFlakeOutput = { + "Flakes: ", + TEST_FOUR, + " Run 1: " + ASSERTION_FAIL, + " Run 2: PASS", + "", + TEST_ONE, + " Run 1: " + ERROR, + " Run 2: " + ASSERTION_FAIL, + " Run 3: PASS", + "", + TEST_TWO, + " Run 1: " + ERROR, + " Run 2: PASS", + "" + }; + assertEquals(asList(expectedFlakeOutput), reporter.getMessages()); reporter.reset(); - factory.printTestFailures( error ); - String[] expectedFailureOutput = - { "Errors: ", TEST_THREE, " Run 1: " + ASSERTION_FAIL, " Run 2: " + ERROR, " Run 3: " + ERROR, "" }; - assertEquals( asList( expectedFailureOutput ), reporter.getMessages() ); + factory.printTestFailures(error); + String[] expectedFailureOutput = { + "Errors: ", TEST_THREE, " Run 1: " + ASSERTION_FAIL, " Run 2: " + ERROR, " Run 3: " + ERROR, "" + }; + assertEquals(asList(expectedFailureOutput), reporter.getMessages()); reporter.reset(); - factory.printTestFailures( failure ); - assertEquals( emptyList(), reporter.getMessages() ); + factory.printTestFailures(failure); + assertEquals(emptyList(), reporter.getMessages()); } - static final class DummyTestReporter implements ConsoleLogger - { + static final class DummyTestReporter implements ConsoleLogger { private final List messages = new ArrayList<>(); @Override - public boolean isDebugEnabled() - { + public boolean isDebugEnabled() { return true; } @Override - public void debug( String message ) - { - messages.add( message ); + public void debug(String message) { + messages.add(message); } @Override - public boolean isInfoEnabled() - { + public boolean isInfoEnabled() { return true; } @Override - public void info( String message ) - { - messages.add( message ); + public void info(String message) { + messages.add(message); } @Override - public boolean isWarnEnabled() - { + public boolean isWarnEnabled() { return true; } @Override - public void warning( String message ) - { - messages.add( message ); + public void warning(String message) { + messages.add(message); } @Override - public boolean isErrorEnabled() - { + public boolean isErrorEnabled() { return true; } @Override - public void error( String message ) - { - messages.add( message ); + public void error(String message) { + messages.add(message); } @Override - public void error( String message, Throwable t ) - { - messages.add( message + " " + t.getLocalizedMessage() ); + public void error(String message, Throwable t) { + messages.add(message + " " + t.getLocalizedMessage()); } @Override - public void error( Throwable t ) - { - messages.add( t.getLocalizedMessage() ); + public void error(Throwable t) { + messages.add(t.getLocalizedMessage()); } - List getMessages() - { + List getMessages() { return messages; } - void reset() - { + void reset() { messages.clear(); } } - public void testGetTestResultType() - { + public void testGetTestResultType() { List emptyList = new ArrayList<>(); - assertEquals( unknown, getTestResultType( emptyList, 1 ) ); + assertEquals(unknown, getTestResultType(emptyList, 1)); List successList = new ArrayList<>(); - successList.add( ReportEntryType.SUCCESS ); - successList.add( ReportEntryType.SUCCESS ); - assertEquals( success, getTestResultType( successList, 1 ) ); + successList.add(ReportEntryType.SUCCESS); + successList.add(ReportEntryType.SUCCESS); + assertEquals(success, getTestResultType(successList, 1)); List failureErrorList = new ArrayList<>(); - failureErrorList.add( ReportEntryType.FAILURE ); - failureErrorList.add( ReportEntryType.ERROR ); - assertEquals( error, getTestResultType( failureErrorList, 1 ) ); + failureErrorList.add(ReportEntryType.FAILURE); + failureErrorList.add(ReportEntryType.ERROR); + assertEquals(error, getTestResultType(failureErrorList, 1)); List errorFailureList = new ArrayList<>(); - errorFailureList.add( ReportEntryType.ERROR ); - errorFailureList.add( ReportEntryType.FAILURE ); - assertEquals( error, getTestResultType( errorFailureList, 1 ) ); + errorFailureList.add(ReportEntryType.ERROR); + errorFailureList.add(ReportEntryType.FAILURE); + assertEquals(error, getTestResultType(errorFailureList, 1)); List flakeList = new ArrayList<>(); - flakeList.add( ReportEntryType.SUCCESS ); - flakeList.add( ReportEntryType.FAILURE ); - assertEquals( flake, getTestResultType( flakeList, 1 ) ); + flakeList.add(ReportEntryType.SUCCESS); + flakeList.add(ReportEntryType.FAILURE); + assertEquals(flake, getTestResultType(flakeList, 1)); - assertEquals( failure, getTestResultType( flakeList, 0 ) ); + assertEquals(failure, getTestResultType(flakeList, 0)); flakeList = new ArrayList<>(); - flakeList.add( ReportEntryType.ERROR ); - flakeList.add( ReportEntryType.SUCCESS ); - flakeList.add( ReportEntryType.FAILURE ); - assertEquals( flake, getTestResultType( flakeList, 1 ) ); + flakeList.add(ReportEntryType.ERROR); + flakeList.add(ReportEntryType.SUCCESS); + flakeList.add(ReportEntryType.FAILURE); + assertEquals(flake, getTestResultType(flakeList, 1)); - assertEquals( error, getTestResultType( flakeList, 0 ) ); + assertEquals(error, getTestResultType(flakeList, 0)); List skippedList = new ArrayList<>(); - skippedList.add( ReportEntryType.SKIPPED ); - assertEquals( skipped, getTestResultType( skippedList, 1 ) ); + skippedList.add(ReportEntryType.SKIPPED); + assertEquals(skipped, getTestResultType(skippedList, 1)); } - public void testLogger() - { - MessageUtils.setColorEnabled( false ); - File target = new File( System.getProperty( "user.dir" ), "target" ); - File reportsDirectory = new File( target, "tmp6" ); - StartupReportConfiguration reportConfig = - new StartupReportConfiguration( true, true, "PLAIN", false, reportsDirectory, false, null, - new File( reportsDirectory, "TESTHASH" ), false, 1, null, null, false, - new SurefireStatelessReporter(), new SurefireConsoleOutputReporter(), - new SurefireStatelessTestsetInfoReporter() ); + public void testLogger() { + MessageUtils.setColorEnabled(false); + File target = new File(System.getProperty("user.dir"), "target"); + File reportsDirectory = new File(target, "tmp6"); + StartupReportConfiguration reportConfig = new StartupReportConfiguration( + true, + true, + "PLAIN", + false, + reportsDirectory, + false, + null, + new File(reportsDirectory, "TESTHASH"), + false, + 1, + null, + null, + false, + new SurefireStatelessReporter(), + new SurefireConsoleOutputReporter(), + new SurefireStatelessTestsetInfoReporter()); DummyTestReporter reporter = new DummyTestReporter(); - DefaultReporterFactory factory = new DefaultReporterFactory( reportConfig, reporter ); + DefaultReporterFactory factory = new DefaultReporterFactory(reportConfig, reporter); TestReportListener runListener = factory.createTestReportListener(); - assertTrue( runListener.isDebugEnabled() ); - assertTrue( runListener.isInfoEnabled() ); - assertTrue( runListener.isWarnEnabled() ); - assertTrue( runListener.isErrorEnabled() ); + assertTrue(runListener.isDebugEnabled()); + assertTrue(runListener.isInfoEnabled()); + assertTrue(runListener.isWarnEnabled()); + assertTrue(runListener.isErrorEnabled()); - runListener.debug( "msg" ); - assertEquals( 1, reporter.getMessages().size() ); - assertEquals( "msg", reporter.getMessages().get( 0 ) ); + runListener.debug("msg"); + assertEquals(1, reporter.getMessages().size()); + assertEquals("msg", reporter.getMessages().get(0)); reporter.reset(); - runListener.info( "msg\n" ); - assertEquals( 1, reporter.getMessages().size() ); - assertEquals( "msg", reporter.getMessages().get( 0 ) ); + runListener.info("msg\n"); + assertEquals(1, reporter.getMessages().size()); + assertEquals("msg", reporter.getMessages().get(0)); reporter.reset(); - runListener.warning( "msg\r\n" ); - assertEquals( 1, reporter.getMessages().size() ); - assertEquals( "msg", reporter.getMessages().get( 0 ) ); + runListener.warning("msg\r\n"); + assertEquals(1, reporter.getMessages().size()); + assertEquals("msg", reporter.getMessages().get(0)); reporter.reset(); - runListener.error( "msg" ); - assertEquals( 1, reporter.getMessages().size() ); - assertEquals( "msg", reporter.getMessages().get( 0 ) ); + runListener.error("msg"); + assertEquals(1, reporter.getMessages().size()); + assertEquals("msg", reporter.getMessages().get(0)); reporter.reset(); - runListener.error( "msg\n", new Exception( "e" ) ); - assertEquals( 1, reporter.getMessages().size() ); - assertEquals( "msg e", reporter.getMessages().get( 0 ) ); + runListener.error("msg\n", new Exception("e")); + assertEquals(1, reporter.getMessages().size()); + assertEquals("msg e", reporter.getMessages().get(0)); reporter.reset(); - runListener.error( new Exception( "e" ) ); - assertEquals( 1, reporter.getMessages().size() ); - assertEquals( "e", reporter.getMessages().get( 0 ) ); + runListener.error(new Exception("e")); + assertEquals(1, reporter.getMessages().size()); + assertEquals("e", reporter.getMessages().get(0)); reporter.reset(); } - public void testCreateReporterWithZeroStatistics() - { - MessageUtils.setColorEnabled( false ); - File target = new File( System.getProperty( "user.dir" ), "target" ); - File reportsDirectory = new File( target, "tmp7" ); - StartupReportConfiguration reportConfig = - new StartupReportConfiguration( true, true, "PLAIN", false, reportsDirectory, false, null, - new File( reportsDirectory, "TESTHASH" ), false, 0, null, null, false, - new SurefireStatelessReporter(), new SurefireConsoleOutputReporter(), - new SurefireStatelessTestsetInfoReporter() ); - - assertTrue( reportConfig.isUseFile() ); - assertTrue( reportConfig.isPrintSummary() ); - assertEquals( "PLAIN", reportConfig.getReportFormat() ); - assertFalse( reportConfig.isRedirectTestOutputToFile() ); - assertEquals( reportsDirectory, reportConfig.getReportsDirectory() ); - assertFalse( reportConfig.isTrimStackTrace() ); - assertNull( reportConfig.getReportNameSuffix() ); - assertEquals( new File( reportsDirectory, "TESTHASH" ), reportConfig.getStatisticsFile() ); - assertFalse( reportConfig.isRequiresRunHistory() ); - assertEquals( 0, reportConfig.getRerunFailingTestsCount() ); - assertNull( reportConfig.getXsdSchemaLocation() ); - assertEquals( UTF_8, reportConfig.getEncoding() ); - assertFalse( reportConfig.isForking() ); - assertNotNull( reportConfig.getXmlReporter() ); - assertNotNull( reportConfig.getConsoleOutputReporter() ); - assertNotNull( reportConfig.getTestsetReporter() ); - assertNull( reportConfig.getStatisticsReporter() ); + public void testCreateReporterWithZeroStatistics() { + MessageUtils.setColorEnabled(false); + File target = new File(System.getProperty("user.dir"), "target"); + File reportsDirectory = new File(target, "tmp7"); + StartupReportConfiguration reportConfig = new StartupReportConfiguration( + true, + true, + "PLAIN", + false, + reportsDirectory, + false, + null, + new File(reportsDirectory, "TESTHASH"), + false, + 0, + null, + null, + false, + new SurefireStatelessReporter(), + new SurefireConsoleOutputReporter(), + new SurefireStatelessTestsetInfoReporter()); + + assertTrue(reportConfig.isUseFile()); + assertTrue(reportConfig.isPrintSummary()); + assertEquals("PLAIN", reportConfig.getReportFormat()); + assertFalse(reportConfig.isRedirectTestOutputToFile()); + assertEquals(reportsDirectory, reportConfig.getReportsDirectory()); + assertFalse(reportConfig.isTrimStackTrace()); + assertNull(reportConfig.getReportNameSuffix()); + assertEquals(new File(reportsDirectory, "TESTHASH"), reportConfig.getStatisticsFile()); + assertFalse(reportConfig.isRequiresRunHistory()); + assertEquals(0, reportConfig.getRerunFailingTestsCount()); + assertNull(reportConfig.getXsdSchemaLocation()); + assertEquals(UTF_8, reportConfig.getEncoding()); + assertFalse(reportConfig.isForking()); + assertNotNull(reportConfig.getXmlReporter()); + assertNotNull(reportConfig.getConsoleOutputReporter()); + assertNotNull(reportConfig.getTestsetReporter()); + assertNull(reportConfig.getStatisticsReporter()); DummyTestReporter reporter = new DummyTestReporter(); - DefaultReporterFactory factory = new DefaultReporterFactory( reportConfig, reporter ); - assertEquals( reportsDirectory, factory.getReportsDirectory() ); + DefaultReporterFactory factory = new DefaultReporterFactory(reportConfig, reporter); + assertEquals(reportsDirectory, factory.getReportsDirectory()); TestSetRunListener runListener = (TestSetRunListener) factory.createTestReportListener(); - Collection listeners = getInternalState( factory, "listeners" ); - assertEquals( 1, listeners.size() ); - assertTrue( listeners.contains( runListener ) ); + Collection listeners = getInternalState(factory, "listeners"); + assertEquals(1, listeners.size()); + assertTrue(listeners.contains(runListener)); - assertNotNull( runListener.getTestMethodStats() ); + assertNotNull(runListener.getTestMethodStats()); factory.runStarting(); factory.close(); RunStatistics statistics = factory.getGlobalRunStatistics(); - assertEquals( 0, statistics.getCompletedCount() ); - assertEquals( new RunResult( 0, 0, 0, 0 ), statistics.getRunResult() ); - assertEquals( 0, statistics.getFailures() ); - assertEquals( 0, statistics.getErrors() ); - assertEquals( 0, statistics.getSkipped() ); - assertEquals( 0, statistics.getFlakes() ); - assertEquals( "Tests run: 0, Failures: 0, Errors: 0, Skipped: 0", statistics.getSummary() ); - assertEquals( 0, statistics.getCompletedCount() ); + assertEquals(0, statistics.getCompletedCount()); + assertEquals(new RunResult(0, 0, 0, 0), statistics.getRunResult()); + assertEquals(0, statistics.getFailures()); + assertEquals(0, statistics.getErrors()); + assertEquals(0, statistics.getSkipped()); + assertEquals(0, statistics.getFlakes()); + assertEquals("Tests run: 0, Failures: 0, Errors: 0, Skipped: 0", statistics.getSummary()); + assertEquals(0, statistics.getCompletedCount()); List messages = reporter.getMessages(); - assertEquals( "", messages.get( 0 ) ); - assertEquals( "-------------------------------------------------------", messages.get( 1 ) ); - assertEquals( " T E S T S", messages.get( 2 ) ); - assertEquals( "-------------------------------------------------------", messages.get( 3 ) ); - assertEquals( "", messages.get( 4 ) ); - assertEquals( "Results:", messages.get( 5 ) ); - assertEquals( "", messages.get( 6 ) ); - assertEquals( "Tests run: 0, Failures: 0, Errors: 0, Skipped: 0", messages.get( 7 ) ); - assertEquals( "", messages.get( 8 ) ); - assertEquals( 9, messages.size() ); + assertEquals("", messages.get(0)); + assertEquals("-------------------------------------------------------", messages.get(1)); + assertEquals(" T E S T S", messages.get(2)); + assertEquals("-------------------------------------------------------", messages.get(3)); + assertEquals("", messages.get(4)); + assertEquals("Results:", messages.get(5)); + assertEquals("", messages.get(6)); + assertEquals("Tests run: 0, Failures: 0, Errors: 0, Skipped: 0", messages.get(7)); + assertEquals("", messages.get(8)); + assertEquals(9, messages.size()); } - static class DummyStackTraceWriter - implements StackTraceWriter - { + static class DummyStackTraceWriter implements StackTraceWriter { private final String stackTrace; - DummyStackTraceWriter( String stackTrace ) - { + DummyStackTraceWriter(String stackTrace) { this.stackTrace = stackTrace; } @Override - public String writeTraceToString() - { + public String writeTraceToString() { return ""; } @Override - public String writeTrimmedTraceToString() - { + public String writeTrimmedTraceToString() { return ""; } @Override - public String smartTrimmedStackTrace() - { + public String smartTrimmedStackTrace() { return stackTrace; } @Override - public SafeThrowable getThrowable() - { + public SafeThrowable getThrowable() { return null; } } diff --git a/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/report/StatelessXmlReporterTest.java b/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/report/StatelessXmlReporterTest.java index 47fb587fb7..d2e871f637 100644 --- a/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/report/StatelessXmlReporterTest.java +++ b/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/report/StatelessXmlReporterTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire.report; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,14 +16,7 @@ * specific language governing permissions and limitations * under the License. */ - -import junit.framework.TestCase; -import org.apache.maven.plugin.surefire.booterclient.output.DeserializedStacktraceWriter; -import org.apache.maven.surefire.api.report.ReportEntry; -import org.apache.maven.surefire.api.report.SimpleReportEntry; -import org.apache.maven.surefire.api.report.StackTraceWriter; -import org.apache.maven.surefire.shared.utils.xml.Xpp3Dom; -import org.apache.maven.surefire.shared.utils.xml.Xpp3DomBuilder; +package org.apache.maven.plugin.surefire.report; import java.io.ByteArrayOutputStream; import java.io.File; @@ -41,6 +32,14 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicInteger; +import junit.framework.TestCase; +import org.apache.maven.plugin.surefire.booterclient.output.DeserializedStacktraceWriter; +import org.apache.maven.surefire.api.report.ReportEntry; +import org.apache.maven.surefire.api.report.SimpleReportEntry; +import org.apache.maven.surefire.api.report.StackTraceWriter; +import org.apache.maven.surefire.shared.utils.xml.Xpp3Dom; +import org.apache.maven.surefire.shared.utils.xml.Xpp3DomBuilder; + import static java.nio.charset.StandardCharsets.UTF_8; import static java.nio.file.Files.readAllLines; import static org.apache.maven.plugin.surefire.report.ReportEntryType.ERROR; @@ -49,6 +48,7 @@ import static org.apache.maven.surefire.api.report.RunMode.NORMAL_RUN; import static org.apache.maven.surefire.api.report.RunMode.RERUN_TEST_AFTER_FAILURE; import static org.apache.maven.surefire.api.util.internal.ObjectUtils.systemProps; +import static org.apache.maven.surefire.api.util.internal.StringUtils.NL; import static org.apache.maven.surefire.shared.utils.StringUtils.isEmpty; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.doThrow; @@ -59,15 +59,12 @@ import static org.powermock.reflect.Whitebox.getInternalState; import static org.powermock.reflect.Whitebox.invokeMethod; import static org.powermock.reflect.Whitebox.setInternalState; -import static org.apache.maven.surefire.api.util.internal.StringUtils.NL; /** * */ -@SuppressWarnings( { "ResultOfMethodCallIgnored", "checkstyle:magicnumber" } ) -public class StatelessXmlReporterTest - extends TestCase -{ +@SuppressWarnings({"ResultOfMethodCallIgnored", "checkstyle:magicnumber"}) +public class StatelessXmlReporterTest extends TestCase { private static final String XSD = "https://maven.apache.org/surefire/maven-surefire-plugin/xsd/surefire-test-report-3.0.xsd"; private static final String TEST_ONE = "aTestMethod"; @@ -81,133 +78,147 @@ public class StatelessXmlReporterTest private File reportDir; @Override - protected void setUp() - throws Exception - { - stats = new TestSetStats( false, true ); - rerunStats = new TestSetStats( false, true ); - - File basedir = new File( "." ); - File target = new File( basedir.getCanonicalFile(), "target" ); + protected void setUp() throws Exception { + stats = new TestSetStats(false, true); + rerunStats = new TestSetStats(false, true); + + File basedir = new File("."); + File target = new File(basedir.getCanonicalFile(), "target"); target.mkdir(); String reportRelDir = getClass().getSimpleName() + "-" + FOLDER_POSTFIX.incrementAndGet(); - reportDir = new File( target, reportRelDir ); + reportDir = new File(target, reportRelDir); reportDir.mkdir(); } @Override - protected void tearDown() - { - if ( expectedReportFile != null ) - { + protected void tearDown() { + if (expectedReportFile != null) { expectedReportFile.delete(); } } - public void testFileNameWithoutSuffix() - { - StatelessXmlReporter reporter = - new StatelessXmlReporter( reportDir, null, false, 0, - new ConcurrentHashMap>(), XSD, "3.0", - false, false, false, false ); + public void testFileNameWithoutSuffix() { + StatelessXmlReporter reporter = new StatelessXmlReporter( + reportDir, + null, + false, + 0, + new ConcurrentHashMap>(), + XSD, + "3.0", + false, + false, + false, + false); reporter.cleanTestHistoryMap(); - ReportEntry reportEntry = new SimpleReportEntry( NORMAL_RUN, 0L, - getClass().getName(), null, getClass().getName(), null, 12 ); - WrappedReportEntry testSetReportEntry = new WrappedReportEntry( reportEntry, ReportEntryType.SUCCESS, - 12, null, null, systemProps() ); - stats.testSucceeded( testSetReportEntry ); - reporter.testSetCompleted( testSetReportEntry, stats ); - - expectedReportFile = new File( reportDir, "TEST-" + getClass().getName() + ".xml" ); - assertTrue( "Report file (" + expectedReportFile.getAbsolutePath() + ") doesn't exist", - expectedReportFile.exists() ); + ReportEntry reportEntry = new SimpleReportEntry( + NORMAL_RUN, 0L, getClass().getName(), null, getClass().getName(), null, 12); + WrappedReportEntry testSetReportEntry = + new WrappedReportEntry(reportEntry, ReportEntryType.SUCCESS, 12, null, null, systemProps()); + stats.testSucceeded(testSetReportEntry); + reporter.testSetCompleted(testSetReportEntry, stats); + + expectedReportFile = new File(reportDir, "TEST-" + getClass().getName() + ".xml"); + assertTrue( + "Report file (" + expectedReportFile.getAbsolutePath() + ") doesn't exist", + expectedReportFile.exists()); } - - public void testAllFieldsSerialized() - throws IOException - { - ReportEntry reportEntry = new SimpleReportEntry( NORMAL_RUN, 0L, - getClass().getName(), null, TEST_ONE, null, 12 ); + public void testAllFieldsSerialized() throws IOException { + ReportEntry reportEntry = + new SimpleReportEntry(NORMAL_RUN, 0L, getClass().getName(), null, TEST_ONE, null, 12); WrappedReportEntry testSetReportEntry = - new WrappedReportEntry( reportEntry, SUCCESS, 12, null, null, systemProps() ); - expectedReportFile = new File( reportDir, "TEST-" + getClass().getName() + ".xml" ); + new WrappedReportEntry(reportEntry, SUCCESS, 12, null, null, systemProps()); + expectedReportFile = new File(reportDir, "TEST-" + getClass().getName() + ".xml"); - stats.testSucceeded( testSetReportEntry ); - StackTraceWriter stackTraceWriter = new DeserializedStacktraceWriter( "A fud msg", "trimmed", "fail at foo" ); - Utf8RecodingDeferredFileOutputStream stdOut = new Utf8RecodingDeferredFileOutputStream( "fds" ); + stats.testSucceeded(testSetReportEntry); + StackTraceWriter stackTraceWriter = new DeserializedStacktraceWriter("A fud msg", "trimmed", "fail at foo"); + Utf8RecodingDeferredFileOutputStream stdOut = new Utf8RecodingDeferredFileOutputStream("fds"); String stdOutPrefix; String stdErrPrefix; - if ( defaultCharsetSupportsSpecialChar() ) - { + if (defaultCharsetSupportsSpecialChar()) { stdErrPrefix = "std-\u0115rr"; stdOutPrefix = "st]]>d-o\u00DCt"; - } - else - { + } else { stdErrPrefix = "std-err"; stdOutPrefix = "st]]>d-out"; } - stdOut.write( stdOutPrefix + "!\u0020\u0000\u001F", false ); - - Utf8RecodingDeferredFileOutputStream stdErr = new Utf8RecodingDeferredFileOutputStream( "fds" ); - - stdErr.write( stdErrPrefix + "?&-&£\u0020\u0000\u001F", false ); - WrappedReportEntry t2 = new WrappedReportEntry( new SimpleReportEntry( NORMAL_RUN, 0L, - getClass().getName(), null, TEST_TWO, null, stackTraceWriter, 13 ), - ReportEntryType.ERROR, 13, stdOut, stdErr ); - - stats.testSucceeded( t2 ); - StatelessXmlReporter reporter = new StatelessXmlReporter( reportDir, null, false, 0, - new ConcurrentHashMap>(), XSD, "3.0", false, false, false, false ); - reporter.testSetCompleted( testSetReportEntry, stats ); - - FileInputStream fileInputStream = new FileInputStream( expectedReportFile ); - - Xpp3Dom testSuite = Xpp3DomBuilder.build( new InputStreamReader( fileInputStream, UTF_8 ) ); - assertEquals( "testsuite", testSuite.getName() ); - Xpp3Dom properties = testSuite.getChild( "properties" ); - assertEquals( System.getProperties().size(), properties.getChildCount() ); - Xpp3Dom child = properties.getChild( 1 ); - assertFalse( isEmpty( child.getAttribute( "value" ) ) ); - assertFalse( isEmpty( child.getAttribute( "name" ) ) ); - - Xpp3Dom[] testcase = testSuite.getChildren( "testcase" ); + stdOut.write(stdOutPrefix + "!\u0020\u0000\u001F", false); + + Utf8RecodingDeferredFileOutputStream stdErr = new Utf8RecodingDeferredFileOutputStream("fds"); + + stdErr.write(stdErrPrefix + "?&-&£\u0020\u0000\u001F", false); + WrappedReportEntry t2 = new WrappedReportEntry( + new SimpleReportEntry(NORMAL_RUN, 0L, getClass().getName(), null, TEST_TWO, null, stackTraceWriter, 13), + ReportEntryType.ERROR, + 13, + stdOut, + stdErr); + + stats.testSucceeded(t2); + StatelessXmlReporter reporter = new StatelessXmlReporter( + reportDir, + null, + false, + 0, + new ConcurrentHashMap>(), + XSD, + "3.0", + false, + false, + false, + false); + reporter.testSetCompleted(testSetReportEntry, stats); + + FileInputStream fileInputStream = new FileInputStream(expectedReportFile); + + Xpp3Dom testSuite = Xpp3DomBuilder.build(new InputStreamReader(fileInputStream, UTF_8)); + assertEquals("testsuite", testSuite.getName()); + Xpp3Dom properties = testSuite.getChild("properties"); + assertEquals(System.getProperties().size(), properties.getChildCount()); + Xpp3Dom child = properties.getChild(1); + assertFalse(isEmpty(child.getAttribute("value"))); + assertFalse(isEmpty(child.getAttribute("name"))); + + Xpp3Dom[] testcase = testSuite.getChildren("testcase"); Xpp3Dom tca = testcase[0]; - assertEquals( TEST_ONE, tca.getAttribute( "name" ) ); - assertEquals( "0.012", tca.getAttribute( "time" ) ); - assertEquals( getClass().getName(), tca.getAttribute( "classname" ) ); + assertEquals(TEST_ONE, tca.getAttribute("name")); + assertEquals("0.012", tca.getAttribute("time")); + assertEquals(getClass().getName(), tca.getAttribute("classname")); Xpp3Dom tcb = testcase[1]; - assertEquals( TEST_TWO, tcb.getAttribute( "name" ) ); - assertEquals( "0.013", tcb.getAttribute( "time" ) ); - assertEquals( getClass().getName(), tcb.getAttribute( "classname" ) ); - Xpp3Dom errorNode = tcb.getChild( "error" ); - assertNotNull( errorNode ); - assertEquals( "A fud msg", errorNode.getAttribute( "message" ) ); - assertEquals( "fail at foo", errorNode.getAttribute( "type" ) ); - assertEquals( stdOutPrefix + "! &#0;&#31;", tcb.getChild( "system-out" ).getValue() ); - - - assertEquals( stdErrPrefix + "?&-&£ &#0;&#31;", tcb.getChild( "system-err" ).getValue() ); + assertEquals(TEST_TWO, tcb.getAttribute("name")); + assertEquals("0.013", tcb.getAttribute("time")); + assertEquals(getClass().getName(), tcb.getAttribute("classname")); + Xpp3Dom errorNode = tcb.getChild("error"); + assertNotNull(errorNode); + assertEquals("A fud msg", errorNode.getAttribute("message")); + assertEquals("fail at foo", errorNode.getAttribute("type")); + assertEquals( + stdOutPrefix + "! &#0;&#31;", + tcb.getChild("system-out").getValue()); + + assertEquals( + stdErrPrefix + "?&-&£ &#0;&#31;", + tcb.getChild("system-err").getValue()); } - public void testOutputRerunFlakyFailure() - throws IOException - { - WrappedReportEntry testSetReportEntry = - new WrappedReportEntry( new SimpleReportEntry( NORMAL_RUN, 0L, - getClass().getName(), null, TEST_ONE, null, 12 ), - ReportEntryType.SUCCESS, 12, null, null, systemProps() ); - expectedReportFile = new File( reportDir, "TEST-" + getClass().getName() + ".xml" ); - - stats.testSucceeded( testSetReportEntry ); - StackTraceWriter stackTraceWriterOne = new DeserializedStacktraceWriter( "A fud msg", "trimmed", - "fail at foo" ); + public void testOutputRerunFlakyFailure() throws IOException { + WrappedReportEntry testSetReportEntry = new WrappedReportEntry( + new SimpleReportEntry(NORMAL_RUN, 0L, getClass().getName(), null, TEST_ONE, null, 12), + ReportEntryType.SUCCESS, + 12, + null, + null, + systemProps()); + expectedReportFile = new File(reportDir, "TEST-" + getClass().getName() + ".xml"); + + stats.testSucceeded(testSetReportEntry); + StackTraceWriter stackTraceWriterOne = new DeserializedStacktraceWriter("A fud msg", "trimmed", "fail at foo"); StackTraceWriter stackTraceWriterTwo = - new DeserializedStacktraceWriter( "A fud msg two", "trimmed two", "fail at foo two" ); + new DeserializedStacktraceWriter("A fud msg two", "trimmed two", "fail at foo two"); String firstRunOut = "first run out"; String firstRunErr = "first run err"; @@ -215,293 +226,310 @@ public void testOutputRerunFlakyFailure() String secondRunErr = "second run err"; String cls = getClass().getName(); - WrappedReportEntry testTwoFirstError = new WrappedReportEntry( new SimpleReportEntry( NORMAL_RUN, 0L, - cls, null, TEST_TWO, null, stackTraceWriterOne, 5 ), - ReportEntryType.ERROR, 5, createStdOutput( firstRunOut ), createStdOutput( firstRunErr ) ); - - WrappedReportEntry testTwoSecondError = new WrappedReportEntry( new SimpleReportEntry( - RERUN_TEST_AFTER_FAILURE, 1L, cls, null, TEST_TWO, null, stackTraceWriterTwo, 13 ), - ReportEntryType.ERROR, 13, createStdOutput( secondRunOut ), createStdOutput( secondRunErr ) ); - - WrappedReportEntry testThreeFirstRun = new WrappedReportEntry( new SimpleReportEntry( NORMAL_RUN, 2L, - cls, null, TEST_THREE, null, stackTraceWriterOne, 13 ), - ReportEntryType.FAILURE, 13, createStdOutput( firstRunOut ), createStdOutput( firstRunErr ) ); - - WrappedReportEntry testThreeSecondRun = new WrappedReportEntry( new SimpleReportEntry( - RERUN_TEST_AFTER_FAILURE, 3L, cls, null, TEST_THREE, null, stackTraceWriterTwo, 2 ), - ReportEntryType.SUCCESS, 2, createStdOutput( secondRunOut ), createStdOutput( secondRunErr ) ); - - stats.testSucceeded( testTwoFirstError ); - stats.testSucceeded( testThreeFirstRun ); - rerunStats.testSucceeded( testTwoSecondError ); - rerunStats.testSucceeded( testThreeSecondRun ); - - StatelessXmlReporter reporter = - new StatelessXmlReporter( reportDir, null, false, 1, - new HashMap>(), XSD, "3.0", false, false, false, false ); - - reporter.testSetCompleted( testSetReportEntry, stats ); - reporter.testSetCompleted( testSetReportEntry, rerunStats ); - - FileInputStream fileInputStream = new FileInputStream( expectedReportFile ); - - Xpp3Dom testSuite = Xpp3DomBuilder.build( new InputStreamReader( fileInputStream, UTF_8 ) ); - assertEquals( "testsuite", testSuite.getName() ); - assertEquals( "0.012", testSuite.getAttribute( "time" ) ); - Xpp3Dom properties = testSuite.getChild( "properties" ); - assertEquals( System.getProperties().size(), properties.getChildCount() ); - Xpp3Dom child = properties.getChild( 1 ); - assertFalse( isEmpty( child.getAttribute( "value" ) ) ); - assertFalse( isEmpty( child.getAttribute( "name" ) ) ); - - Xpp3Dom[] testcase = testSuite.getChildren( "testcase" ); + WrappedReportEntry testTwoFirstError = new WrappedReportEntry( + new SimpleReportEntry(NORMAL_RUN, 0L, cls, null, TEST_TWO, null, stackTraceWriterOne, 5), + ReportEntryType.ERROR, + 5, + createStdOutput(firstRunOut), + createStdOutput(firstRunErr)); + + WrappedReportEntry testTwoSecondError = new WrappedReportEntry( + new SimpleReportEntry(RERUN_TEST_AFTER_FAILURE, 1L, cls, null, TEST_TWO, null, stackTraceWriterTwo, 13), + ReportEntryType.ERROR, + 13, + createStdOutput(secondRunOut), + createStdOutput(secondRunErr)); + + WrappedReportEntry testThreeFirstRun = new WrappedReportEntry( + new SimpleReportEntry(NORMAL_RUN, 2L, cls, null, TEST_THREE, null, stackTraceWriterOne, 13), + ReportEntryType.FAILURE, + 13, + createStdOutput(firstRunOut), + createStdOutput(firstRunErr)); + + WrappedReportEntry testThreeSecondRun = new WrappedReportEntry( + new SimpleReportEntry( + RERUN_TEST_AFTER_FAILURE, 3L, cls, null, TEST_THREE, null, stackTraceWriterTwo, 2), + ReportEntryType.SUCCESS, + 2, + createStdOutput(secondRunOut), + createStdOutput(secondRunErr)); + + stats.testSucceeded(testTwoFirstError); + stats.testSucceeded(testThreeFirstRun); + rerunStats.testSucceeded(testTwoSecondError); + rerunStats.testSucceeded(testThreeSecondRun); + + StatelessXmlReporter reporter = new StatelessXmlReporter( + reportDir, + null, + false, + 1, + new HashMap>(), + XSD, + "3.0", + false, + false, + false, + false); + + reporter.testSetCompleted(testSetReportEntry, stats); + reporter.testSetCompleted(testSetReportEntry, rerunStats); + + FileInputStream fileInputStream = new FileInputStream(expectedReportFile); + + Xpp3Dom testSuite = Xpp3DomBuilder.build(new InputStreamReader(fileInputStream, UTF_8)); + assertEquals("testsuite", testSuite.getName()); + assertEquals("0.012", testSuite.getAttribute("time")); + Xpp3Dom properties = testSuite.getChild("properties"); + assertEquals(System.getProperties().size(), properties.getChildCount()); + Xpp3Dom child = properties.getChild(1); + assertFalse(isEmpty(child.getAttribute("value"))); + assertFalse(isEmpty(child.getAttribute("name"))); + + Xpp3Dom[] testcase = testSuite.getChildren("testcase"); Xpp3Dom testCaseOne = testcase[0]; - assertEquals( TEST_ONE, testCaseOne.getAttribute( "name" ) ); - assertEquals( "0.012", testCaseOne.getAttribute( "time" ) ); - assertEquals( getClass().getName(), testCaseOne.getAttribute( "classname" ) ); + assertEquals(TEST_ONE, testCaseOne.getAttribute("name")); + assertEquals("0.012", testCaseOne.getAttribute("time")); + assertEquals(getClass().getName(), testCaseOne.getAttribute("classname")); Xpp3Dom testCaseTwo = testcase[1]; - assertEquals( TEST_TWO, testCaseTwo.getAttribute( "name" ) ); + assertEquals(TEST_TWO, testCaseTwo.getAttribute("name")); // Run time for a rerun failing test is the run time of the first run - assertEquals( "0.005", testCaseTwo.getAttribute( "time" ) ); - assertEquals( getClass().getName(), testCaseTwo.getAttribute( "classname" ) ); - Xpp3Dom errorNode = testCaseTwo.getChild( "error" ); - Xpp3Dom rerunErrorNode = testCaseTwo.getChild( "rerunError" ); - assertNotNull( errorNode ); - assertNotNull( rerunErrorNode ); + assertEquals("0.005", testCaseTwo.getAttribute("time")); + assertEquals(getClass().getName(), testCaseTwo.getAttribute("classname")); + Xpp3Dom errorNode = testCaseTwo.getChild("error"); + Xpp3Dom rerunErrorNode = testCaseTwo.getChild("rerunError"); + assertNotNull(errorNode); + assertNotNull(rerunErrorNode); - assertEquals( "A fud msg", errorNode.getAttribute( "message" ) ); - assertEquals( "fail at foo", errorNode.getAttribute( "type" ) ); + assertEquals("A fud msg", errorNode.getAttribute("message")); + assertEquals("fail at foo", errorNode.getAttribute("type")); // Check rerun error node contains all the information - assertEquals( firstRunOut, testCaseTwo.getChild( "system-out" ).getValue() ); - assertEquals( firstRunErr, testCaseTwo.getChild( "system-err" ).getValue() ); - assertEquals( secondRunOut, rerunErrorNode.getChild( "system-out" ).getValue() ); - assertEquals( secondRunErr, rerunErrorNode.getChild( "system-err" ).getValue() ); - assertEquals( "A fud msg two", rerunErrorNode.getAttribute( "message" ) ); - assertEquals( "fail at foo two", rerunErrorNode.getAttribute( "type" ) ); + assertEquals(firstRunOut, testCaseTwo.getChild("system-out").getValue()); + assertEquals(firstRunErr, testCaseTwo.getChild("system-err").getValue()); + assertEquals(secondRunOut, rerunErrorNode.getChild("system-out").getValue()); + assertEquals(secondRunErr, rerunErrorNode.getChild("system-err").getValue()); + assertEquals("A fud msg two", rerunErrorNode.getAttribute("message")); + assertEquals("fail at foo two", rerunErrorNode.getAttribute("type")); // Check flaky failure node Xpp3Dom testCaseThree = testcase[2]; - assertEquals( TEST_THREE, testCaseThree.getAttribute( "name" ) ); + assertEquals(TEST_THREE, testCaseThree.getAttribute("name")); // Run time for a flaky test is the run time of the first successful run - assertEquals( "0.002", testCaseThree.getAttribute( "time" ) ); - assertEquals( getClass().getName(), testCaseThree.getAttribute( "classname" ) ); - Xpp3Dom flakyFailureNode = testCaseThree.getChild( "flakyFailure" ); - assertNotNull( flakyFailureNode ); - assertEquals( firstRunOut, flakyFailureNode.getChild( "system-out" ).getValue() ); - assertEquals( firstRunErr, flakyFailureNode.getChild( "system-err" ).getValue() ); + assertEquals("0.002", testCaseThree.getAttribute("time")); + assertEquals(getClass().getName(), testCaseThree.getAttribute("classname")); + Xpp3Dom flakyFailureNode = testCaseThree.getChild("flakyFailure"); + assertNotNull(flakyFailureNode); + assertEquals(firstRunOut, flakyFailureNode.getChild("system-out").getValue()); + assertEquals(firstRunErr, flakyFailureNode.getChild("system-err").getValue()); // system-out and system-err should not be present for flaky failures - assertNull( testCaseThree.getChild( "system-out" ) ); - assertNull( testCaseThree.getChild( "system-err" ) ); + assertNull(testCaseThree.getChild("system-out")); + assertNull(testCaseThree.getChild("system-err")); } - public void testOutputRerunFlakyAssumption() - throws IOException - { - expectedReportFile = new File( reportDir, "TEST-" + getClass().getName() + ".xml" ); + public void testOutputRerunFlakyAssumption() throws IOException { + expectedReportFile = new File(reportDir, "TEST-" + getClass().getName() + ".xml"); - StackTraceWriter stackTraceWriterOne = new DeserializedStacktraceWriter( "A fud msg", "trimmed", - "fail at foo" ); + StackTraceWriter stackTraceWriterOne = new DeserializedStacktraceWriter("A fud msg", "trimmed", "fail at foo"); StackTraceWriter stackTraceWriterTwo = - new DeserializedStacktraceWriter( "A fud msg two", "trimmed two", "fail at foo two" ); + new DeserializedStacktraceWriter("A fud msg two", "trimmed two", "fail at foo two"); String firstRunOut = "first run out"; String firstRunErr = "first run err"; String secondRunOut = "second run out"; String secondRunErr = "second run err"; - WrappedReportEntry testTwoFirstError = - new WrappedReportEntry( new SimpleReportEntry( NORMAL_RUN, 1L, getClass().getName(), null, TEST_TWO, null, - stackTraceWriterOne, 5 ), ERROR, 5, createStdOutput( firstRunOut ), - createStdOutput( firstRunErr ) ); - - stats.testSucceeded( testTwoFirstError ); - - WrappedReportEntry testTwoSecondError = - new WrappedReportEntry( new SimpleReportEntry( RERUN_TEST_AFTER_FAILURE, 1L, getClass().getName(), null, - TEST_TWO, null, - stackTraceWriterTwo, 13 ), SKIPPED, 13, createStdOutput( secondRunOut ), - createStdOutput( secondRunErr ) ); - - rerunStats.testSucceeded( testTwoSecondError ); - - StatelessXmlReporter reporter = - new StatelessXmlReporter( reportDir, null, false, 1, - new HashMap<>(), XSD, "3.0", false, false, false, false ); - - WrappedReportEntry testSetReportEntry = - new WrappedReportEntry( new SimpleReportEntry( RERUN_TEST_AFTER_FAILURE, 1L, getClass().getName(), null, - null, null, - stackTraceWriterOne, 5 ), ERROR, 20, createStdOutput( firstRunOut ), - createStdOutput( firstRunErr ) ); - - reporter.testSetCompleted( testSetReportEntry, stats ); - reporter.testSetCompleted( testSetReportEntry, rerunStats ); - - FileInputStream fileInputStream = new FileInputStream( expectedReportFile ); - - Xpp3Dom testSuite = Xpp3DomBuilder.build( new InputStreamReader( fileInputStream, UTF_8 ) ); - assertEquals( "testsuite", testSuite.getName() ); - assertEquals( "0.02", testSuite.getAttribute( "time" ) ); - - Xpp3Dom[] testcase = testSuite.getChildren( "testcase" ); - assertEquals( 1, testcase.length ); + WrappedReportEntry testTwoFirstError = new WrappedReportEntry( + new SimpleReportEntry( + NORMAL_RUN, 1L, getClass().getName(), null, TEST_TWO, null, stackTraceWriterOne, 5), + ERROR, + 5, + createStdOutput(firstRunOut), + createStdOutput(firstRunErr)); + + stats.testSucceeded(testTwoFirstError); + + WrappedReportEntry testTwoSecondError = new WrappedReportEntry( + new SimpleReportEntry( + RERUN_TEST_AFTER_FAILURE, + 1L, + getClass().getName(), + null, + TEST_TWO, + null, + stackTraceWriterTwo, + 13), + SKIPPED, + 13, + createStdOutput(secondRunOut), + createStdOutput(secondRunErr)); + + rerunStats.testSucceeded(testTwoSecondError); + + StatelessXmlReporter reporter = new StatelessXmlReporter( + reportDir, null, false, 1, new HashMap<>(), XSD, "3.0", false, false, false, false); + + WrappedReportEntry testSetReportEntry = new WrappedReportEntry( + new SimpleReportEntry( + RERUN_TEST_AFTER_FAILURE, 1L, getClass().getName(), null, null, null, stackTraceWriterOne, 5), + ERROR, + 20, + createStdOutput(firstRunOut), + createStdOutput(firstRunErr)); + + reporter.testSetCompleted(testSetReportEntry, stats); + reporter.testSetCompleted(testSetReportEntry, rerunStats); + + FileInputStream fileInputStream = new FileInputStream(expectedReportFile); + + Xpp3Dom testSuite = Xpp3DomBuilder.build(new InputStreamReader(fileInputStream, UTF_8)); + assertEquals("testsuite", testSuite.getName()); + assertEquals("0.02", testSuite.getAttribute("time")); + + Xpp3Dom[] testcase = testSuite.getChildren("testcase"); + assertEquals(1, testcase.length); Xpp3Dom testCaseOne = testcase[0]; - assertEquals( getClass().getName(), testCaseOne.getAttribute( "classname" ) ); - assertEquals( TEST_TWO, testCaseOne.getAttribute( "name" ) ); - assertEquals( "0.005", testCaseOne.getAttribute( "time" ) ); + assertEquals(getClass().getName(), testCaseOne.getAttribute("classname")); + assertEquals(TEST_TWO, testCaseOne.getAttribute("name")); + assertEquals("0.005", testCaseOne.getAttribute("time")); Xpp3Dom[] testCaseElements = testCaseOne.getChildren(); - assertEquals( 3, testCaseElements.length ); - assertEquals( "error", testCaseElements[0].getName() ); - assertEquals( "system-out", testCaseElements[1].getName() ); - assertEquals( "system-err", testCaseElements[2].getName() ); - long linesWithComments = readAllLines( expectedReportFile.toPath(), UTF_8 ) - .stream() - .filter( line -> line.contains( "" ) ) - .count(); - assertEquals( 1, linesWithComments ); + assertEquals(3, testCaseElements.length); + assertEquals("error", testCaseElements[0].getName()); + assertEquals("system-out", testCaseElements[1].getName()); + assertEquals("system-err", testCaseElements[2].getName()); + long linesWithComments = readAllLines(expectedReportFile.toPath(), UTF_8).stream() + .filter(line -> line.contains("")) + .count(); + assertEquals(1, linesWithComments); } - public void testNoWritesOnDeferredFile() throws Exception - { - Utf8RecodingDeferredFileOutputStream out = new Utf8RecodingDeferredFileOutputStream( "test" ); + public void testNoWritesOnDeferredFile() throws Exception { + Utf8RecodingDeferredFileOutputStream out = new Utf8RecodingDeferredFileOutputStream("test"); out.free(); - out.write( "a", false ); - assertThat( (boolean) getInternalState( out, "isDirty" ) ) - .isFalse(); + out.write("a", false); + assertThat((boolean) getInternalState(out, "isDirty")).isFalse(); } - public void testLengthOnDeferredFile() throws Exception - { - Utf8RecodingDeferredFileOutputStream out = new Utf8RecodingDeferredFileOutputStream( "test" ); + public void testLengthOnDeferredFile() throws Exception { + Utf8RecodingDeferredFileOutputStream out = new Utf8RecodingDeferredFileOutputStream("test"); - assertThat( out.getByteCount() ).isZero(); + assertThat(out.getByteCount()).isZero(); - File f = File.createTempFile( "test", "tmp" ); - RandomAccessFile storage = new RandomAccessFile( f, "rw" ); - setInternalState( out, "storage", storage ); - setInternalState( out, "file", f.toPath() ); - storage.writeByte( 0 ); + File f = File.createTempFile("test", "tmp"); + RandomAccessFile storage = new RandomAccessFile(f, "rw"); + setInternalState(out, "storage", storage); + setInternalState(out, "file", f.toPath()); + storage.writeByte(0); storage.getFD().sync(); - assertThat( out.getByteCount() ).isEqualTo( 1 ); + assertThat(out.getByteCount()).isEqualTo(1); storage.close(); - assertThat( f.delete() ).isTrue(); - assertThat( out.getByteCount() ).isZero(); + assertThat(f.delete()).isTrue(); + assertThat(out.getByteCount()).isZero(); out.free(); } - @SuppressWarnings( "checkstyle:magicnumber" ) - public void testWritesOnDeferredFile() throws Exception - { - Utf8RecodingDeferredFileOutputStream out = new Utf8RecodingDeferredFileOutputStream( "test" ); - for ( int i = 0; i < 33_000; i++ ) - { - out.write( "A", false ); - out.write( "B", true ); + @SuppressWarnings("checkstyle:magicnumber") + public void testWritesOnDeferredFile() throws Exception { + Utf8RecodingDeferredFileOutputStream out = new Utf8RecodingDeferredFileOutputStream("test"); + for (int i = 0; i < 33_000; i++) { + out.write("A", false); + out.write("B", true); } - out.write( null, false ); - out.write( null, true ); + out.write(null, false); + out.write(null, true); - assertThat( out.getByteCount() ) - .isEqualTo( 33_000 * ( 1 + 1 + NL.length() ) + 4 + 4 + NL.length() ); + assertThat(out.getByteCount()).isEqualTo(33_000 * (1 + 1 + NL.length()) + 4 + 4 + NL.length()); - StringBuilder expectedContent = new StringBuilder( 150_000 ); - for ( int i = 0; i < 33_000; i++ ) - { - expectedContent.append( 'A' ).append( 'B' ).append( NL ); + StringBuilder expectedContent = new StringBuilder(150_000); + for (int i = 0; i < 33_000; i++) { + expectedContent.append('A').append('B').append(NL); } - expectedContent.append( "null" ).append( "null" ).append( NL ); - ByteArrayOutputStream read = new ByteArrayOutputStream( 150_000 ); - out.writeTo( read ); - assertThat( read.toString() ) - .isEqualTo( expectedContent.toString() ); + expectedContent.append("null").append("null").append(NL); + ByteArrayOutputStream read = new ByteArrayOutputStream(150_000); + out.writeTo(read); + assertThat(read.toString()).isEqualTo(expectedContent.toString()); out.free(); } - public void testFreeOnDeferredFile() throws Exception - { - Utf8RecodingDeferredFileOutputStream out = new Utf8RecodingDeferredFileOutputStream( "test" ); - setInternalState( out, "cache", ByteBuffer.allocate( 0 ) ); - Path path = mock( Path.class ); - File file = mock( File.class ); - when( path.toFile() ).thenReturn( file ); - setInternalState( out, "file", path ); - RandomAccessFile storage = mock( RandomAccessFile.class ); - doThrow( IOException.class ).when( storage ).close(); - setInternalState( out, "storage", storage ); + public void testFreeOnDeferredFile() throws Exception { + Utf8RecodingDeferredFileOutputStream out = new Utf8RecodingDeferredFileOutputStream("test"); + setInternalState(out, "cache", ByteBuffer.allocate(0)); + Path path = mock(Path.class); + File file = mock(File.class); + when(path.toFile()).thenReturn(file); + setInternalState(out, "file", path); + RandomAccessFile storage = mock(RandomAccessFile.class); + doThrow(IOException.class).when(storage).close(); + setInternalState(out, "storage", storage); out.free(); - assertThat( (boolean) getInternalState( out, "closed" ) ).isTrue(); - verify( file, times( 1 ) ).deleteOnExit(); + assertThat((boolean) getInternalState(out, "closed")).isTrue(); + verify(file, times(1)).deleteOnExit(); } - public void testCacheOnDeferredFile() throws Exception - { - Utf8RecodingDeferredFileOutputStream out = new Utf8RecodingDeferredFileOutputStream( "test" ); - byte[] b1 = invokeMethod( out, "getLargeCache", 1 ); - byte[] b2 = invokeMethod( out, "getLargeCache", 1 ); - assertThat( b1 ).isSameAs( b2 ); - assertThat( b1 ).hasSize( 1 ); - - byte[] b3 = invokeMethod( out, "getLargeCache", 2 ); - assertThat( b3 ).isNotSameAs( b1 ); - assertThat( b3 ).hasSize( 2 ); - - byte[] b4 = invokeMethod( out, "getLargeCache", 1 ); - assertThat( b4 ).isSameAs( b3 ); - assertThat( b3 ).hasSize( 2 ); + public void testCacheOnDeferredFile() throws Exception { + Utf8RecodingDeferredFileOutputStream out = new Utf8RecodingDeferredFileOutputStream("test"); + byte[] b1 = invokeMethod(out, "getLargeCache", 1); + byte[] b2 = invokeMethod(out, "getLargeCache", 1); + assertThat(b1).isSameAs(b2); + assertThat(b1).hasSize(1); + + byte[] b3 = invokeMethod(out, "getLargeCache", 2); + assertThat(b3).isNotSameAs(b1); + assertThat(b3).hasSize(2); + + byte[] b4 = invokeMethod(out, "getLargeCache", 1); + assertThat(b4).isSameAs(b3); + assertThat(b3).hasSize(2); } - public void testSyncOnDeferredFile() throws Exception - { - Utf8RecodingDeferredFileOutputStream out = new Utf8RecodingDeferredFileOutputStream( "test" ); - Buffer cache = ByteBuffer.wrap( new byte[] {1, 2, 3} ); - cache.position( 3 ); - setInternalState( out, "cache", cache ); - assertThat( (boolean) getInternalState( out, "isDirty" ) ).isFalse(); - setInternalState( out, "isDirty", true ); - File file = new File( reportDir, "test" ); - setInternalState( out, "file", file.toPath() ); - RandomAccessFile storage = new RandomAccessFile( file, "rw" ); - setInternalState( out, "storage", storage ); - invokeMethod( out, "sync" ); - assertThat( (boolean) getInternalState( out, "isDirty" ) ).isFalse(); - storage.seek( 0L ); - assertThat( storage.read() ).isEqualTo( 1 ); - assertThat( storage.read() ).isEqualTo( 2 ); - assertThat( storage.read() ).isEqualTo( 3 ); - assertThat( storage.read() ).isEqualTo( -1 ); - assertThat( storage.length() ).isEqualTo( 3L ); - assertThat( cache.position() ).isEqualTo( 0 ); - assertThat( cache.limit() ).isEqualTo( 3 ); - storage.seek( 3L ); - invokeMethod( out, "sync" ); - assertThat( (boolean) getInternalState( out, "isDirty" ) ).isFalse(); - assertThat( storage.length() ).isEqualTo( 3L ); - assertThat( out.getByteCount() ).isEqualTo( 3L ); - assertThat( (boolean) getInternalState( out, "closed" ) ).isFalse(); + public void testSyncOnDeferredFile() throws Exception { + Utf8RecodingDeferredFileOutputStream out = new Utf8RecodingDeferredFileOutputStream("test"); + Buffer cache = ByteBuffer.wrap(new byte[] {1, 2, 3}); + cache.position(3); + setInternalState(out, "cache", cache); + assertThat((boolean) getInternalState(out, "isDirty")).isFalse(); + setInternalState(out, "isDirty", true); + File file = new File(reportDir, "test"); + setInternalState(out, "file", file.toPath()); + RandomAccessFile storage = new RandomAccessFile(file, "rw"); + setInternalState(out, "storage", storage); + invokeMethod(out, "sync"); + assertThat((boolean) getInternalState(out, "isDirty")).isFalse(); + storage.seek(0L); + assertThat(storage.read()).isEqualTo(1); + assertThat(storage.read()).isEqualTo(2); + assertThat(storage.read()).isEqualTo(3); + assertThat(storage.read()).isEqualTo(-1); + assertThat(storage.length()).isEqualTo(3L); + assertThat(cache.position()).isEqualTo(0); + assertThat(cache.limit()).isEqualTo(3); + storage.seek(3L); + invokeMethod(out, "sync"); + assertThat((boolean) getInternalState(out, "isDirty")).isFalse(); + assertThat(storage.length()).isEqualTo(3L); + assertThat(out.getByteCount()).isEqualTo(3L); + assertThat((boolean) getInternalState(out, "closed")).isFalse(); out.free(); - assertThat( (boolean) getInternalState( out, "closed" ) ).isTrue(); - //todo assertThat( file ).doesNotExist(); + assertThat((boolean) getInternalState(out, "closed")).isTrue(); + // todo assertThat( file ).doesNotExist(); out.free(); - assertThat( (boolean) getInternalState( out, "closed" ) ).isTrue(); + assertThat((boolean) getInternalState(out, "closed")).isTrue(); } - private boolean defaultCharsetSupportsSpecialChar() - { + private boolean defaultCharsetSupportsSpecialChar() { // some charsets are not able to deal with \u0115 on both ways of the conversion - return "\u0115\u00DC".equals( new String( "\u0115\u00DC".getBytes() ) ); + return "\u0115\u00DC".equals(new String("\u0115\u00DC".getBytes())); } - private Utf8RecodingDeferredFileOutputStream createStdOutput( String content ) - throws IOException - { - Utf8RecodingDeferredFileOutputStream stdOut = new Utf8RecodingDeferredFileOutputStream( "fds2" ); - stdOut.write( content, false ); + private Utf8RecodingDeferredFileOutputStream createStdOutput(String content) throws IOException { + Utf8RecodingDeferredFileOutputStream stdOut = new Utf8RecodingDeferredFileOutputStream("fds2"); + stdOut.write(content, false); return stdOut; } } diff --git a/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/report/TestSetStatsTest.java b/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/report/TestSetStatsTest.java index 8916fa2179..f7cab66e70 100644 --- a/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/report/TestSetStatsTest.java +++ b/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/report/TestSetStatsTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire.report; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.surefire.report; import org.apache.maven.surefire.api.report.ReportEntry; import org.junit.Test; @@ -37,53 +36,41 @@ /** * tests for {@link TestSetStats}. */ -@RunWith( PowerMockRunner.class ) -@PowerMockIgnore( { "org.jacoco.agent.rt.*", "com.vladium.emma.rt.*" } ) -public class TestSetStatsTest -{ +@RunWith(PowerMockRunner.class) +@PowerMockIgnore({"org.jacoco.agent.rt.*", "com.vladium.emma.rt.*"}) +public class TestSetStatsTest { @Mock private ReportEntry reportEntry; @Test - public void shouldConcatenateWithTestGroup() - { - when( reportEntry.getNameWithGroup() ) - .thenReturn( "pkg.MyTest (my group)" ); - String actual = TestSetStats.concatenateWithTestGroup( buffer(), reportEntry, false ); - verify( reportEntry, times( 1 ) ).getNameWithGroup(); - verifyNoMoreInteractions( reportEntry ); - String expected = buffer().a( "pkg." ).strong( "MyTest (my group)" ).toString(); - assertThat( actual ) - .isEqualTo( expected ); + public void shouldConcatenateWithTestGroup() { + when(reportEntry.getNameWithGroup()).thenReturn("pkg.MyTest (my group)"); + String actual = TestSetStats.concatenateWithTestGroup(buffer(), reportEntry, false); + verify(reportEntry, times(1)).getNameWithGroup(); + verifyNoMoreInteractions(reportEntry); + String expected = buffer().a("pkg.").strong("MyTest (my group)").toString(); + assertThat(actual).isEqualTo(expected); } @Test - public void shouldConcatenateWithJUnit5TestGroup() - { - when( reportEntry.getReportNameWithGroup() ) - .thenReturn( "pkg.MyTest (my group)" ); - String actual = TestSetStats.concatenateWithTestGroup( buffer(), reportEntry, true ); - verify( reportEntry, atLeastOnce() ).getReportNameWithGroup(); - verifyNoMoreInteractions( reportEntry ); - String expected = buffer().strong( "pkg.MyTest (my group)" ).toString(); - assertThat( actual ) - .isEqualTo( expected ); + public void shouldConcatenateWithJUnit5TestGroup() { + when(reportEntry.getReportNameWithGroup()).thenReturn("pkg.MyTest (my group)"); + String actual = TestSetStats.concatenateWithTestGroup(buffer(), reportEntry, true); + verify(reportEntry, atLeastOnce()).getReportNameWithGroup(); + verifyNoMoreInteractions(reportEntry); + String expected = buffer().strong("pkg.MyTest (my group)").toString(); + assertThat(actual).isEqualTo(expected); } @Test - public void shouldFallBackToTestGroupIfJUnit5TestGroupIsNull() - { - when( reportEntry.getReportNameWithGroup() ) - .thenReturn( null ); - when( reportEntry.getNameWithGroup() ) - .thenReturn( "pkg.MyTest (my group)" ); - String actual = TestSetStats.concatenateWithTestGroup( buffer(), reportEntry, true ); - verify( reportEntry, atLeastOnce() ).getReportNameWithGroup(); - verify( reportEntry, atLeastOnce() ).getNameWithGroup(); - verifyNoMoreInteractions( reportEntry ); - String expected = buffer().a( "pkg." ).strong( "MyTest (my group)" ).toString(); - assertThat( actual ) - .isEqualTo( expected ); + public void shouldFallBackToTestGroupIfJUnit5TestGroupIsNull() { + when(reportEntry.getReportNameWithGroup()).thenReturn(null); + when(reportEntry.getNameWithGroup()).thenReturn("pkg.MyTest (my group)"); + String actual = TestSetStats.concatenateWithTestGroup(buffer(), reportEntry, true); + verify(reportEntry, atLeastOnce()).getReportNameWithGroup(); + verify(reportEntry, atLeastOnce()).getNameWithGroup(); + verifyNoMoreInteractions(reportEntry); + String expected = buffer().a("pkg.").strong("MyTest (my group)").toString(); + assertThat(actual).isEqualTo(expected); } - } diff --git a/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/report/WrappedReportEntryTest.java b/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/report/WrappedReportEntryTest.java index f021627a1b..0e08294a90 100644 --- a/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/report/WrappedReportEntryTest.java +++ b/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/report/WrappedReportEntryTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire.report; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,12 +16,12 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.surefire.report; +import junit.framework.TestCase; import org.apache.maven.surefire.api.report.ReportEntry; import org.apache.maven.surefire.api.report.SimpleReportEntry; -import junit.framework.TestCase; - import static org.apache.maven.plugin.surefire.report.ReportEntryType.ERROR; import static org.apache.maven.plugin.surefire.report.ReportEntryType.FAILURE; import static org.apache.maven.plugin.surefire.report.ReportEntryType.SKIPPED; @@ -33,132 +31,122 @@ /** * @author Kristian Rosenvold */ -public class WrappedReportEntryTest - extends TestCase -{ - public void testClassNameOnly() - { +public class WrappedReportEntryTest extends TestCase { + public void testClassNameOnly() { String className = "surefire.testcase.JunitParamsTest"; - WrappedReportEntry wr = - new WrappedReportEntry( new SimpleReportEntry( NORMAL_RUN, 1L, className, null, null, null ), - SUCCESS, 12, null, null ); + WrappedReportEntry wr = new WrappedReportEntry( + new SimpleReportEntry(NORMAL_RUN, 1L, className, null, null, null), SUCCESS, 12, null, null); final String reportName = wr.getReportSourceName(); - assertEquals( "surefire.testcase.JunitParamsTest.null", wr.getClassMethodName() ); - assertEquals( "surefire.testcase.JunitParamsTest", reportName ); - assertTrue( wr.isSucceeded() ); - assertFalse( wr.isErrorOrFailure() ); - assertFalse( wr.isSkipped() ); + assertEquals("surefire.testcase.JunitParamsTest.null", wr.getClassMethodName()); + assertEquals("surefire.testcase.JunitParamsTest", reportName); + assertTrue(wr.isSucceeded()); + assertFalse(wr.isErrorOrFailure()); + assertFalse(wr.isSkipped()); } - public void testRegular() - { + public void testRegular() { ReportEntry reportEntry = - new SimpleReportEntry( NORMAL_RUN, 1L, "surefire.testcase.JunitParamsTest", null, "testSum", null ); - WrappedReportEntry wr = new WrappedReportEntry( reportEntry, null, 12, null, null ); - assertEquals( "surefire.testcase.JunitParamsTest.testSum", wr.getClassMethodName() ); - assertEquals( "surefire.testcase.JunitParamsTest", wr.getReportSourceName() ); - assertEquals( "surefire.testcase.JunitParamsTest", wr.getReportSourceName( "" ) ); - assertEquals( "surefire.testcase.JunitParamsTest(BDD)", wr.getReportSourceName( "BDD" ) ); - assertEquals( "surefire.testcase.JunitParamsTest", wr.getSourceName( "" ) ); - assertEquals( "surefire.testcase.JunitParamsTest(BDD)", wr.getSourceName( "BDD" ) ); - assertEquals( "testSum", wr.getReportName() ); - assertFalse( wr.isSucceeded() ); - assertFalse( wr.isErrorOrFailure() ); - assertFalse( wr.isSkipped() ); - assertTrue( wr.getSystemProperties().isEmpty() ); - assertNull( wr.getGroup() ); - assertEquals( "surefire.testcase.JunitParamsTest", wr.getNameWithGroup() ); + new SimpleReportEntry(NORMAL_RUN, 1L, "surefire.testcase.JunitParamsTest", null, "testSum", null); + WrappedReportEntry wr = new WrappedReportEntry(reportEntry, null, 12, null, null); + assertEquals("surefire.testcase.JunitParamsTest.testSum", wr.getClassMethodName()); + assertEquals("surefire.testcase.JunitParamsTest", wr.getReportSourceName()); + assertEquals("surefire.testcase.JunitParamsTest", wr.getReportSourceName("")); + assertEquals("surefire.testcase.JunitParamsTest(BDD)", wr.getReportSourceName("BDD")); + assertEquals("surefire.testcase.JunitParamsTest", wr.getSourceName("")); + assertEquals("surefire.testcase.JunitParamsTest(BDD)", wr.getSourceName("BDD")); + assertEquals("testSum", wr.getReportName()); + assertFalse(wr.isSucceeded()); + assertFalse(wr.isErrorOrFailure()); + assertFalse(wr.isSkipped()); + assertTrue(wr.getSystemProperties().isEmpty()); + assertNull(wr.getGroup()); + assertEquals("surefire.testcase.JunitParamsTest", wr.getNameWithGroup()); } - public void testDisplayNames() - { - ReportEntry reportEntry = new SimpleReportEntry( NORMAL_RUN, 0L, - "surefire.testcase.JunitParamsTest", "dn1", "testSum", "dn2", "exception" ); - WrappedReportEntry wr = new WrappedReportEntry( reportEntry, ERROR, 12, null, null ); - assertEquals( "surefire.testcase.JunitParamsTest.testSum", wr.getClassMethodName() ); - assertEquals( "dn1", wr.getReportSourceName() ); - assertEquals( "dn1(BDD)", wr.getReportSourceName( "BDD" ) ); - assertEquals( "surefire.testcase.JunitParamsTest(BDD)", wr.getSourceName( "BDD" ) ); - assertEquals( "dn2", wr.getReportName() ); - assertFalse( wr.isSucceeded() ); - assertTrue( wr.isErrorOrFailure() ); - assertFalse( wr.isSkipped() ); - assertNull( wr.getStackTraceWriter() ); - assertEquals( "surefire.testcase.JunitParamsTest.testSum Time elapsed: 0.012 s", - wr.getElapsedTimeSummary() ); - assertEquals( "surefire.testcase.JunitParamsTest.testSum Time elapsed: 0.012 s <<< ERROR!", - wr.getOutput( false ) ); - assertEquals( "exception", wr.getMessage() ); + public void testDisplayNames() { + ReportEntry reportEntry = new SimpleReportEntry( + NORMAL_RUN, 0L, "surefire.testcase.JunitParamsTest", "dn1", "testSum", "dn2", "exception"); + WrappedReportEntry wr = new WrappedReportEntry(reportEntry, ERROR, 12, null, null); + assertEquals("surefire.testcase.JunitParamsTest.testSum", wr.getClassMethodName()); + assertEquals("dn1", wr.getReportSourceName()); + assertEquals("dn1(BDD)", wr.getReportSourceName("BDD")); + assertEquals("surefire.testcase.JunitParamsTest(BDD)", wr.getSourceName("BDD")); + assertEquals("dn2", wr.getReportName()); + assertFalse(wr.isSucceeded()); + assertTrue(wr.isErrorOrFailure()); + assertFalse(wr.isSkipped()); + assertNull(wr.getStackTraceWriter()); + assertEquals("surefire.testcase.JunitParamsTest.testSum Time elapsed: 0.012 s", wr.getElapsedTimeSummary()); + assertEquals( + "surefire.testcase.JunitParamsTest.testSum Time elapsed: 0.012 s <<< ERROR!", wr.getOutput(false)); + assertEquals("exception", wr.getMessage()); } - public void testEqualDisplayNames() - { - ReportEntry reportEntry = new SimpleReportEntry( NORMAL_RUN, 1L, "surefire.testcase.JunitParamsTest", - "surefire.testcase.JunitParamsTest", "testSum", "testSum" ); - WrappedReportEntry wr = new WrappedReportEntry( reportEntry, FAILURE, 12, null, null ); - assertEquals( "surefire.testcase.JunitParamsTest", wr.getReportSourceName() ); - assertEquals( "surefire.testcase.JunitParamsTest(BDD)", wr.getReportSourceName( "BDD" ) ); - assertEquals( "testSum", wr.getReportName() ); - assertFalse( wr.isSucceeded() ); - assertTrue( wr.isErrorOrFailure() ); - assertFalse( wr.isSkipped() ); + public void testEqualDisplayNames() { + ReportEntry reportEntry = new SimpleReportEntry( + NORMAL_RUN, + 1L, + "surefire.testcase.JunitParamsTest", + "surefire.testcase.JunitParamsTest", + "testSum", + "testSum"); + WrappedReportEntry wr = new WrappedReportEntry(reportEntry, FAILURE, 12, null, null); + assertEquals("surefire.testcase.JunitParamsTest", wr.getReportSourceName()); + assertEquals("surefire.testcase.JunitParamsTest(BDD)", wr.getReportSourceName("BDD")); + assertEquals("testSum", wr.getReportName()); + assertFalse(wr.isSucceeded()); + assertTrue(wr.isErrorOrFailure()); + assertFalse(wr.isSkipped()); } - public void testGetReportNameWithParams() - { + public void testGetReportNameWithParams() { String className = "[0] 1\u002C 2\u002C 3 (testSum)"; - ReportEntry reportEntry = new SimpleReportEntry( NORMAL_RUN, 1L, className, null, null, null ); - WrappedReportEntry wr = new WrappedReportEntry( reportEntry, SKIPPED, 12, null, null ); + ReportEntry reportEntry = new SimpleReportEntry(NORMAL_RUN, 1L, className, null, null, null); + WrappedReportEntry wr = new WrappedReportEntry(reportEntry, SKIPPED, 12, null, null); final String reportName = wr.getReportSourceName(); - assertEquals( "[0] 1, 2, 3 (testSum)", reportName ); - assertFalse( wr.isSucceeded() ); - assertFalse ( wr.isErrorOrFailure() ); - assertTrue( wr.isSkipped() ); + assertEquals("[0] 1, 2, 3 (testSum)", reportName); + assertFalse(wr.isSucceeded()); + assertFalse(wr.isErrorOrFailure()); + assertTrue(wr.isSkipped()); } - public void testGetReportNameWithGroupWhenSourceTextIsNull() - { + public void testGetReportNameWithGroupWhenSourceTextIsNull() { String className = "ClassName"; String classText = null; - ReportEntry reportEntry = new SimpleReportEntry( NORMAL_RUN, 1L, className, classText, null, null ); - WrappedReportEntry wr = new WrappedReportEntry( reportEntry, SKIPPED, 12, null, null ); - assertEquals( className, wr.getReportNameWithGroup() ); + ReportEntry reportEntry = new SimpleReportEntry(NORMAL_RUN, 1L, className, classText, null, null); + WrappedReportEntry wr = new WrappedReportEntry(reportEntry, SKIPPED, 12, null, null); + assertEquals(className, wr.getReportNameWithGroup()); } - public void testGetReportNameWithGroupWhenSourceTextIsEmpty() - { + public void testGetReportNameWithGroupWhenSourceTextIsEmpty() { String className = "ClassName"; String classText = ""; - ReportEntry reportEntry = new SimpleReportEntry( NORMAL_RUN, 1L, className, classText, null, null ); - WrappedReportEntry wr = new WrappedReportEntry( reportEntry, SKIPPED, 12, null, null ); - assertEquals( className, wr.getReportNameWithGroup() ); + ReportEntry reportEntry = new SimpleReportEntry(NORMAL_RUN, 1L, className, classText, null, null); + WrappedReportEntry wr = new WrappedReportEntry(reportEntry, SKIPPED, 12, null, null); + assertEquals(className, wr.getReportNameWithGroup()); } - public void testGetReportNameWithGroupWhenSourceTextIsBlank() - { + public void testGetReportNameWithGroupWhenSourceTextIsBlank() { String className = "ClassName"; String classText = " "; - ReportEntry reportEntry = new SimpleReportEntry( NORMAL_RUN, 1L, className, classText, null, null ); - WrappedReportEntry wr = new WrappedReportEntry( reportEntry, SKIPPED, 12, null, null ); - assertEquals( className, wr.getReportNameWithGroup() ); + ReportEntry reportEntry = new SimpleReportEntry(NORMAL_RUN, 1L, className, classText, null, null); + WrappedReportEntry wr = new WrappedReportEntry(reportEntry, SKIPPED, 12, null, null); + assertEquals(className, wr.getReportNameWithGroup()); } - public void testGetReportNameWithGroupWhenSourceTextIsProvided() - { + public void testGetReportNameWithGroupWhenSourceTextIsProvided() { String className = "ClassName"; String classText = "The Class Name"; - ReportEntry reportEntry = new SimpleReportEntry( NORMAL_RUN, 1L, className, classText, null, null ); - WrappedReportEntry wr = new WrappedReportEntry( reportEntry, SKIPPED, 12, null, null ); - assertEquals( classText, wr.getReportNameWithGroup() ); + ReportEntry reportEntry = new SimpleReportEntry(NORMAL_RUN, 1L, className, classText, null, null); + WrappedReportEntry wr = new WrappedReportEntry(reportEntry, SKIPPED, 12, null, null); + assertEquals(classText, wr.getReportNameWithGroup()); } - public void testElapsed() - { + public void testElapsed() { String className = "[0] 1\u002C 2\u002C 3 (testSum)"; - ReportEntry reportEntry = new SimpleReportEntry( NORMAL_RUN, 1L, className, null, null, null ); - WrappedReportEntry wr = new WrappedReportEntry( reportEntry, null, 12, null, null ); + ReportEntry reportEntry = new SimpleReportEntry(NORMAL_RUN, 1L, className, null, null, null); + WrappedReportEntry wr = new WrappedReportEntry(reportEntry, null, 12, null, null); String elapsedTimeSummary = wr.getElapsedTimeSummary(); - assertEquals( "[0] 1, 2, 3 (testSum) Time elapsed: 0.012 s", - elapsedTimeSummary ); + assertEquals("[0] 1, 2, 3 (testSum) Time elapsed: 0.012 s", elapsedTimeSummary); } } diff --git a/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/runorder/RunEntryStatisticsMapTest.java b/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/runorder/RunEntryStatisticsMapTest.java index 8fd7535e93..324d515848 100644 --- a/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/runorder/RunEntryStatisticsMapTest.java +++ b/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/runorder/RunEntryStatisticsMapTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire.runorder; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.surefire.runorder; import java.io.ByteArrayInputStream; import java.io.File; @@ -29,251 +28,193 @@ import java.util.List; import java.util.Map; -import org.apache.maven.surefire.api.runorder.RunEntryStatistics; -import org.apache.maven.surefire.api.runorder.RunEntryStatisticsMap; +import junit.framework.TestCase; import org.apache.maven.surefire.api.report.ReportEntry; import org.apache.maven.surefire.api.report.SimpleReportEntry; - -import junit.framework.TestCase; +import org.apache.maven.surefire.api.runorder.RunEntryStatistics; +import org.apache.maven.surefire.api.runorder.RunEntryStatisticsMap; import org.apache.maven.surefire.api.util.SureFireFileManager; import org.apache.maven.surefire.api.util.internal.ClassMethod; import static java.nio.charset.StandardCharsets.UTF_8; import static org.apache.maven.surefire.api.report.RunMode.NORMAL_RUN; -import static org.apache.maven.surefire.shared.io.IOUtils.readLines; import static org.apache.maven.surefire.api.util.internal.StringUtils.NL; +import static org.apache.maven.surefire.shared.io.IOUtils.readLines; import static org.assertj.core.api.Assertions.assertThat; import static org.powermock.reflect.Whitebox.getInternalState; /** * @author Kristian Rosenvold */ -public class RunEntryStatisticsMapTest - extends TestCase -{ - public void testPrioritizedClassRuntime() - { - final RunEntryStatisticsMap runEntryStatisticsMap = RunEntryStatisticsMap.fromStream( getStatisticsFile() ); - final List> list = Arrays.asList( A.class, B.class, C.class ); +public class RunEntryStatisticsMapTest extends TestCase { + public void testPrioritizedClassRuntime() { + final RunEntryStatisticsMap runEntryStatisticsMap = RunEntryStatisticsMap.fromStream(getStatisticsFile()); + final List> list = Arrays.asList(A.class, B.class, C.class); final List> prioritizedTestsClassRunTime = - runEntryStatisticsMap.getPrioritizedTestsClassRunTime( list, 2 ); - assertEquals( C.class, prioritizedTestsClassRunTime.get( 0 ) ); - assertEquals( B.class, prioritizedTestsClassRunTime.get( 1 ) ); - assertEquals( A.class, prioritizedTestsClassRunTime.get( 2 ) ); + runEntryStatisticsMap.getPrioritizedTestsClassRunTime(list, 2); + assertEquals(C.class, prioritizedTestsClassRunTime.get(0)); + assertEquals(B.class, prioritizedTestsClassRunTime.get(1)); + assertEquals(A.class, prioritizedTestsClassRunTime.get(2)); } - public void testPrioritizedFailureFirst() - { - final RunEntryStatisticsMap runEntryStatisticsMap = RunEntryStatisticsMap.fromStream( getStatisticsFile() ); - final List> list = Arrays.asList( A.class, B.class, NewClass.class, C.class ); + public void testPrioritizedFailureFirst() { + final RunEntryStatisticsMap runEntryStatisticsMap = RunEntryStatisticsMap.fromStream(getStatisticsFile()); + final List> list = Arrays.asList(A.class, B.class, NewClass.class, C.class); final List> prioritizedTestsClassRunTime = - runEntryStatisticsMap.getPrioritizedTestsByFailureFirst( list ); - assertEquals( A.class, prioritizedTestsClassRunTime.get( 0 ) ); - assertEquals( NewClass.class, prioritizedTestsClassRunTime.get( 1 ) ); - assertEquals( C.class, prioritizedTestsClassRunTime.get( 2 ) ); - assertEquals( B.class, prioritizedTestsClassRunTime.get( 3 ) ); + runEntryStatisticsMap.getPrioritizedTestsByFailureFirst(list); + assertEquals(A.class, prioritizedTestsClassRunTime.get(0)); + assertEquals(NewClass.class, prioritizedTestsClassRunTime.get(1)); + assertEquals(C.class, prioritizedTestsClassRunTime.get(2)); + assertEquals(B.class, prioritizedTestsClassRunTime.get(3)); } - private InputStream getStatisticsFile() - { + private InputStream getStatisticsFile() { String content = "0,17,org.apache.maven.plugin.surefire.runorder.RunEntryStatisticsMapTest$A,testA\n" + "2,42,org.apache.maven.plugin.surefire.runorder.RunEntryStatisticsMapTest$B,testB\n" + "1,100,org.apache.maven.plugin.surefire.runorder.RunEntryStatisticsMapTest$C,testC\n"; - return new ByteArrayInputStream( content.getBytes( UTF_8 ) ); + return new ByteArrayInputStream(content.getBytes(UTF_8)); } - @SuppressWarnings( "checkstyle:magicnumber" ) - public void testSerializeClass() - throws Exception - { - File data = SureFireFileManager.createTempFile( "surefire-unit", "test" ); + @SuppressWarnings("checkstyle:magicnumber") + public void testSerializeClass() throws Exception { + File data = SureFireFileManager.createTempFile("surefire-unit", "test"); RunEntryStatisticsMap newResults = new RunEntryStatisticsMap(); - ReportEntry reportEntry = new SimpleReportEntry( NORMAL_RUN, 0L, - "abc", null, null, null, 42 ); - newResults.add( newResults.createNextGeneration( reportEntry ) ); - newResults.serialize( data ); - try ( InputStream io = new FileInputStream( data ) ) - { - List lines = readLines( io, UTF_8 ); - - assertThat( lines ) - .hasSize( 1 ); - - assertThat( lines ) - .containsSequence( "1,42,abc," ); + ReportEntry reportEntry = new SimpleReportEntry(NORMAL_RUN, 0L, "abc", null, null, null, 42); + newResults.add(newResults.createNextGeneration(reportEntry)); + newResults.serialize(data); + try (InputStream io = new FileInputStream(data)) { + List lines = readLines(io, UTF_8); + + assertThat(lines).hasSize(1); + + assertThat(lines).containsSequence("1,42,abc,"); } } - @SuppressWarnings( "checkstyle:magicnumber" ) - public void testDeserializeClass() - throws Exception - { - File data = SureFireFileManager.createTempFile( "surefire-unit", "test" ); - Files.write( data.toPath(), "1,42,abc".getBytes( UTF_8 ) ); - RunEntryStatisticsMap existingEntries = RunEntryStatisticsMap.fromFile( data ); - Map runEntryStatistics = getInternalState( existingEntries, "runEntryStatistics" ); - assertThat( runEntryStatistics ) - .hasSize( 1 ); + @SuppressWarnings("checkstyle:magicnumber") + public void testDeserializeClass() throws Exception { + File data = SureFireFileManager.createTempFile("surefire-unit", "test"); + Files.write(data.toPath(), "1,42,abc".getBytes(UTF_8)); + RunEntryStatisticsMap existingEntries = RunEntryStatisticsMap.fromFile(data); + Map runEntryStatistics = getInternalState(existingEntries, "runEntryStatistics"); + assertThat(runEntryStatistics).hasSize(1); ClassMethod cm = (ClassMethod) runEntryStatistics.keySet().iterator().next(); - assertThat( cm.getClazz() ) - .isEqualTo( "abc" ); - assertThat( cm.getMethod() ) - .isNull(); - RunEntryStatistics statistics = (RunEntryStatistics) runEntryStatistics.values().iterator().next(); - assertThat( statistics.getRunTime() ) - .isEqualTo( 42 ); - assertThat( statistics.getSuccessfulBuilds() ) - .isEqualTo( 1 ); + assertThat(cm.getClazz()).isEqualTo("abc"); + assertThat(cm.getMethod()).isNull(); + RunEntryStatistics statistics = + (RunEntryStatistics) runEntryStatistics.values().iterator().next(); + assertThat(statistics.getRunTime()).isEqualTo(42); + assertThat(statistics.getSuccessfulBuilds()).isEqualTo(1); } - @SuppressWarnings( "checkstyle:magicnumber" ) - public void testSerialize() - throws Exception - { - File data = SureFireFileManager.createTempFile( "surefire-unit", "test" ); - RunEntryStatisticsMap existingEntries = RunEntryStatisticsMap.fromFile( data ); + @SuppressWarnings("checkstyle:magicnumber") + public void testSerialize() throws Exception { + File data = SureFireFileManager.createTempFile("surefire-unit", "test"); + RunEntryStatisticsMap existingEntries = RunEntryStatisticsMap.fromFile(data); RunEntryStatisticsMap newResults = new RunEntryStatisticsMap(); - ReportEntry reportEntry1 = new SimpleReportEntry( NORMAL_RUN, 0L, - "abc", null, "method1", null, 42 ); - ReportEntry reportEntry2 = new SimpleReportEntry( NORMAL_RUN, 0L, - "abc", null, "willFail", null, 17 ); - ReportEntry reportEntry3 = new SimpleReportEntry( NORMAL_RUN, 0L, - "abc", null, "method3", null, 100 ); + ReportEntry reportEntry1 = new SimpleReportEntry(NORMAL_RUN, 0L, "abc", null, "method1", null, 42); + ReportEntry reportEntry2 = new SimpleReportEntry(NORMAL_RUN, 0L, "abc", null, "willFail", null, 17); + ReportEntry reportEntry3 = new SimpleReportEntry(NORMAL_RUN, 0L, "abc", null, "method3", null, 100); - newResults.add( existingEntries.createNextGeneration( reportEntry1 ) ); - newResults.add( existingEntries.createNextGeneration( reportEntry2 ) ); - newResults.add( existingEntries.createNextGeneration( reportEntry3 ) ); + newResults.add(existingEntries.createNextGeneration(reportEntry1)); + newResults.add(existingEntries.createNextGeneration(reportEntry2)); + newResults.add(existingEntries.createNextGeneration(reportEntry3)); - newResults.serialize( data ); - try ( InputStream io = new FileInputStream( data ) ) - { - List lines = readLines( io, UTF_8 ); + newResults.serialize(data); + try (InputStream io = new FileInputStream(data)) { + List lines = readLines(io, UTF_8); - assertThat( lines ) - .hasSize( 3 ); + assertThat(lines).hasSize(3); - assertThat( lines ) - .containsSequence( "1,17,abc,willFail", "1,42,abc,method1", "1,100,abc,method3" ); + assertThat(lines).containsSequence("1,17,abc,willFail", "1,42,abc,method1", "1,100,abc,method3"); } - RunEntryStatisticsMap nextRun = RunEntryStatisticsMap.fromFile( data ); + RunEntryStatisticsMap nextRun = RunEntryStatisticsMap.fromFile(data); newResults = new RunEntryStatisticsMap(); - ReportEntry newRunReportEntry1 = new SimpleReportEntry( NORMAL_RUN, 0L, - "abc", null, "method1", null, 52 ); - ReportEntry newRunReportEntry2 = new SimpleReportEntry( NORMAL_RUN, 0L, - "abc", null, "willFail", null, 27 ); - ReportEntry newRunReportEntry3 = new SimpleReportEntry( NORMAL_RUN, 0L, - "abc", null, "method3", null, 110 ); + ReportEntry newRunReportEntry1 = new SimpleReportEntry(NORMAL_RUN, 0L, "abc", null, "method1", null, 52); + ReportEntry newRunReportEntry2 = new SimpleReportEntry(NORMAL_RUN, 0L, "abc", null, "willFail", null, 27); + ReportEntry newRunReportEntry3 = new SimpleReportEntry(NORMAL_RUN, 0L, "abc", null, "method3", null, 110); - newResults.add( nextRun.createNextGeneration( newRunReportEntry1 ) ); - newResults.add( nextRun.createNextGenerationFailure( newRunReportEntry2 ) ); - newResults.add( nextRun.createNextGeneration( newRunReportEntry3 ) ); + newResults.add(nextRun.createNextGeneration(newRunReportEntry1)); + newResults.add(nextRun.createNextGenerationFailure(newRunReportEntry2)); + newResults.add(nextRun.createNextGeneration(newRunReportEntry3)); - newResults.serialize( data ); - try ( InputStream io = new FileInputStream( data ) ) - { - List lines = readLines( io, UTF_8 ); + newResults.serialize(data); + try (InputStream io = new FileInputStream(data)) { + List lines = readLines(io, UTF_8); - assertThat( lines ) - .hasSize( 3 ); + assertThat(lines).hasSize(3); - assertThat( lines ) - .containsSequence( "0,27,abc,willFail", "2,52,abc,method1", "2,110,abc,method3" ); + assertThat(lines).containsSequence("0,27,abc,willFail", "2,52,abc,method1", "2,110,abc,method3"); } } - @SuppressWarnings( "checkstyle:magicnumber" ) - public void testMultiLineTestMethodName() throws IOException - { - File data = SureFireFileManager.createTempFile( "surefire-unit", "test" ); - RunEntryStatisticsMap reportEntries = RunEntryStatisticsMap.fromFile( data ); - ReportEntry reportEntry = new SimpleReportEntry( NORMAL_RUN, 0L, - "abc", null, "line1\nline2" + NL + " line3", null, 42 ); - reportEntries.add( reportEntries.createNextGeneration( reportEntry ) ); - - reportEntries.serialize( data ); - try ( InputStream io = new FileInputStream( data ) ) - { - List lines = readLines( io, UTF_8 ); - - assertThat( lines ) - .hasSize( 3 ); - - assertThat( lines ) - .containsSequence( "1,42,abc,line1", " line2", " line3" ); + @SuppressWarnings("checkstyle:magicnumber") + public void testMultiLineTestMethodName() throws IOException { + File data = SureFireFileManager.createTempFile("surefire-unit", "test"); + RunEntryStatisticsMap reportEntries = RunEntryStatisticsMap.fromFile(data); + ReportEntry reportEntry = + new SimpleReportEntry(NORMAL_RUN, 0L, "abc", null, "line1\nline2" + NL + " line3", null, 42); + reportEntries.add(reportEntries.createNextGeneration(reportEntry)); + + reportEntries.serialize(data); + try (InputStream io = new FileInputStream(data)) { + List lines = readLines(io, UTF_8); + + assertThat(lines).hasSize(3); + + assertThat(lines).containsSequence("1,42,abc,line1", " line2", " line3"); } - RunEntryStatisticsMap nextRun = RunEntryStatisticsMap.fromFile( data ); - assertThat( data.delete() ).isTrue(); - nextRun.serialize( data ); - try ( InputStream io = new FileInputStream( data ) ) - { - List lines = readLines( io, UTF_8 ); + RunEntryStatisticsMap nextRun = RunEntryStatisticsMap.fromFile(data); + assertThat(data.delete()).isTrue(); + nextRun.serialize(data); + try (InputStream io = new FileInputStream(data)) { + List lines = readLines(io, UTF_8); - assertThat( lines ) - .hasSize( 3 ); + assertThat(lines).hasSize(3); - assertThat( lines ) - .containsSequence( "1,42,abc,line1", " line2", " line3" ); + assertThat(lines).containsSequence("1,42,abc,line1", " line2", " line3"); } } - @SuppressWarnings( "checkstyle:magicnumber" ) - public void testCombinedMethodNames() throws IOException - { - File data = SureFireFileManager.createTempFile( "surefire-unit", "test" ); - RunEntryStatisticsMap reportEntries = RunEntryStatisticsMap.fromFile( data ); - reportEntries.add( reportEntries.createNextGeneration( new SimpleReportEntry( NORMAL_RUN, 0L, - "abc", null, "line1\nline2", null, 42 ) ) ); - reportEntries.add( reportEntries.createNextGeneration( new SimpleReportEntry( NORMAL_RUN, 0L, - "abc", null, "test", null, 10 ) ) ); - - reportEntries.serialize( data ); - try ( InputStream io = new FileInputStream( data ) ) - { - List lines = readLines( io, UTF_8 ); - - assertThat( lines ) - .hasSize( 3 ); - - assertThat( lines ) - .containsSequence( "1,10,abc,test", - "1,42,abc,line1", - " line2" ); + @SuppressWarnings("checkstyle:magicnumber") + public void testCombinedMethodNames() throws IOException { + File data = SureFireFileManager.createTempFile("surefire-unit", "test"); + RunEntryStatisticsMap reportEntries = RunEntryStatisticsMap.fromFile(data); + reportEntries.add(reportEntries.createNextGeneration( + new SimpleReportEntry(NORMAL_RUN, 0L, "abc", null, "line1\nline2", null, 42))); + reportEntries.add(reportEntries.createNextGeneration( + new SimpleReportEntry(NORMAL_RUN, 0L, "abc", null, "test", null, 10))); + + reportEntries.serialize(data); + try (InputStream io = new FileInputStream(data)) { + List lines = readLines(io, UTF_8); + + assertThat(lines).hasSize(3); + + assertThat(lines).containsSequence("1,10,abc,test", "1,42,abc,line1", " line2"); } - RunEntryStatisticsMap nextRun = RunEntryStatisticsMap.fromFile( data ); - assertThat( data.delete() ).isTrue(); - nextRun.serialize( data ); - try ( InputStream io = new FileInputStream( data ) ) - { - List lines = readLines( io, UTF_8 ); + RunEntryStatisticsMap nextRun = RunEntryStatisticsMap.fromFile(data); + assertThat(data.delete()).isTrue(); + nextRun.serialize(data); + try (InputStream io = new FileInputStream(data)) { + List lines = readLines(io, UTF_8); - assertThat( lines ) - .hasSize( 3 ); + assertThat(lines).hasSize(3); - assertThat( lines ) - .containsSequence( "1,10,abc,test", - "1,42,abc,line1", - " line2" ); + assertThat(lines).containsSequence("1,10,abc,test", "1,42,abc,line1", " line2"); } } - class A - { - } + class A {} - class B - { - } + class B {} - class C - { - } + class C {} - class NewClass - { - } + class NewClass {} } diff --git a/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/util/DependenciesScannerTest.java b/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/util/DependenciesScannerTest.java index 9f6b349c3d..05b3391313 100644 --- a/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/util/DependenciesScannerTest.java +++ b/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/util/DependenciesScannerTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire.util; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,10 +16,18 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.surefire.util; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; +import java.io.File; +import java.io.FileOutputStream; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.zip.ZipEntry; +import java.util.zip.ZipOutputStream; import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.DefaultArtifact; @@ -33,205 +39,210 @@ import org.junit.Test; import org.junit.rules.TemporaryFolder; -import java.io.File; -import java.io.FileOutputStream; -import java.util.Arrays; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.zip.ZipEntry; -import java.util.zip.ZipOutputStream; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; /** * @author Aslak Knutsen */ -public class DependenciesScannerTest -{ +public class DependenciesScannerTest { @Rule public TemporaryFolder tempFolder = new TemporaryFolder(); @Test - public void testLocateTestClasses() - throws Exception - { - File testFile = writeTestFile( "DependenciesScannerTest-tests.jar", - "org/test/TestA.class", "org/test/TestB.class" ); + public void testLocateTestClasses() throws Exception { + File testFile = + writeTestFile("DependenciesScannerTest-tests.jar", "org/test/TestA.class", "org/test/TestB.class"); // use target as people can configure ide to compile in an other place than maven - Artifact artifact = - new DefaultArtifact( "org.surefire.dependency", "test-jar", VersionRange.createFromVersion( "1.0" ), "test", - "jar", "tests", null ); - artifact.setFile( testFile ); + Artifact artifact = new DefaultArtifact( + "org.surefire.dependency", + "test-jar", + VersionRange.createFromVersion("1.0"), + "test", + "jar", + "tests", + null); + artifact.setFile(testFile); List scanDependencies = new ArrayList<>(); - scanDependencies.add( "org.surefire.dependency:test-jar" ); + scanDependencies.add("org.surefire.dependency:test-jar"); List include = new ArrayList<>(); - include.add( "**/*A.java" ); + include.add("**/*A.java"); List exclude = new ArrayList<>(); - List dependenciesToScan = - filterArtifactsAsFiles( scanDependencies, Collections.singletonList( artifact ) ); + List dependenciesToScan = filterArtifactsAsFiles(scanDependencies, Collections.singletonList(artifact)); - DependencyScanner scanner = - new DependencyScanner( dependenciesToScan, new TestListResolver( include, exclude ) ); + DependencyScanner scanner = new DependencyScanner(dependenciesToScan, new TestListResolver(include, exclude)); ScanResult classNames = scanner.scan(); - assertNotNull( classNames ); - assertEquals( 1, classNames.size() ); + assertNotNull(classNames); + assertEquals(1, classNames.size()); Map props = new HashMap<>(); - classNames.writeTo( props ); - assertEquals( 1, props.size() ); + classNames.writeTo(props); + assertEquals(1, props.size()); } /** * Test for artifact with classifier */ @Test - public void testLocateTestClassesFromArtifactWithClassifier() - throws Exception - { - File testJarFile = writeTestFile( "DependenciesScannerTest2-1.0-tests-jdk15.jar", "org/test/TestA.class", - "org/test/other/TestAA.class", "org/test/TestB.class" ); - Artifact testArtifact = - new DefaultArtifact( "org.surefire.dependency", "dependent-artifact2", - VersionRange.createFromVersion( "1.0" ), "test", "jar", "tests-jdk15", null ); - testArtifact.setFile( testJarFile ); + public void testLocateTestClassesFromArtifactWithClassifier() throws Exception { + File testJarFile = writeTestFile( + "DependenciesScannerTest2-1.0-tests-jdk15.jar", "org/test/TestA.class", + "org/test/other/TestAA.class", "org/test/TestB.class"); + Artifact testArtifact = new DefaultArtifact( + "org.surefire.dependency", + "dependent-artifact2", + VersionRange.createFromVersion("1.0"), + "test", + "jar", + "tests-jdk15", + null); + testArtifact.setFile(testJarFile); List scanDependencies = new ArrayList<>(); - scanDependencies.add( "org.surefire.dependency:dependent-artifact2:*:*:tests-jdk15" ); + scanDependencies.add("org.surefire.dependency:dependent-artifact2:*:*:tests-jdk15"); List include = new ArrayList<>(); - include.add( "**/*A.java" ); + include.add("**/*A.java"); List exclude = new ArrayList<>(); + List filesToScan = filterArtifactsAsFiles(scanDependencies, Collections.singletonList(testArtifact)); - List filesToScan = filterArtifactsAsFiles( scanDependencies, Collections.singletonList( testArtifact ) ); - - DependencyScanner scanner = - new DependencyScanner( filesToScan, new TestListResolver( include, exclude ) ); + DependencyScanner scanner = new DependencyScanner(filesToScan, new TestListResolver(include, exclude)); ScanResult classNames = scanner.scan(); - assertNotNull( classNames ); - assertEquals( 2, classNames.size() ); + assertNotNull(classNames); + assertEquals(2, classNames.size()); Map props = new HashMap<>(); - classNames.writeTo( props ); - assertEquals( 2, props.size() ); + classNames.writeTo(props); + assertEquals(2, props.size()); } /** * Test with type when two artifacts are present, should only find the class in jar with correct type */ @Test - public void testLocateTestClassesFromMultipleArtifactsWithType() - throws Exception - { + public void testLocateTestClassesFromMultipleArtifactsWithType() throws Exception { File jarFile = - writeTestFile( "DependenciesScannerTest3-1.0.jar", "org/test/ClassA.class", "org/test/ClassB.class" ); - Artifact mainArtifact = new DefaultArtifact( "org.surefire.dependency", "dependent-artifact3", - VersionRange.createFromVersion( "1.0" ), "test", "jar", null, - new DefaultArtifactHandler() ); - mainArtifact.setFile( jarFile ); + writeTestFile("DependenciesScannerTest3-1.0.jar", "org/test/ClassA.class", "org/test/ClassB.class"); + Artifact mainArtifact = new DefaultArtifact( + "org.surefire.dependency", + "dependent-artifact3", + VersionRange.createFromVersion("1.0"), + "test", + "jar", + null, + new DefaultArtifactHandler()); + mainArtifact.setFile(jarFile); File testJarFile = - writeTestFile( "DependenciesScannerTest3-1.0-tests.jar", "org/test/TestA.class", "org/test/TestB.class" ); - Artifact testArtifact = new DefaultArtifact( "org.surefire.dependency", "dependent-artifact3", - VersionRange.createFromVersion( "1.0" ), "test", "test-jar", null, - new DefaultArtifactHandler() ); - testArtifact.setFile( testJarFile ); + writeTestFile("DependenciesScannerTest3-1.0-tests.jar", "org/test/TestA.class", "org/test/TestB.class"); + Artifact testArtifact = new DefaultArtifact( + "org.surefire.dependency", + "dependent-artifact3", + VersionRange.createFromVersion("1.0"), + "test", + "test-jar", + null, + new DefaultArtifactHandler()); + testArtifact.setFile(testJarFile); List scanDependencies = new ArrayList<>(); - scanDependencies.add( "org.surefire.dependency:dependent-artifact3:test-jar" ); + scanDependencies.add("org.surefire.dependency:dependent-artifact3:test-jar"); List include = new ArrayList(); - include.add( "**/*A.java" ); + include.add("**/*A.java"); List exclude = new ArrayList(); - List artifacts = Arrays.asList( mainArtifact, testArtifact ); + List artifacts = Arrays.asList(mainArtifact, testArtifact); - List filesToScan = filterArtifactsAsFiles( scanDependencies, artifacts ); + List filesToScan = filterArtifactsAsFiles(scanDependencies, artifacts); - DependencyScanner scanner = new DependencyScanner( filesToScan, new TestListResolver( include, exclude ) ); + DependencyScanner scanner = new DependencyScanner(filesToScan, new TestListResolver(include, exclude)); ScanResult classNames = scanner.scan(); - assertNotNull( classNames ); - assertEquals( 1, classNames.size() ); - assertEquals( "org.test.TestA", classNames.getClassName( 0 ) ); + assertNotNull(classNames); + assertEquals(1, classNames.size()); + assertEquals("org.test.TestA", classNames.getClassName(0)); Map props = new HashMap<>(); - classNames.writeTo( props ); - assertEquals( 1, props.size() ); + classNames.writeTo(props); + assertEquals(1, props.size()); } /** * Test to pick the right version of an artifact to scan */ @Test - public void testLocateTestClassesFromMultipleVersionsOfArtifact() - throws Exception - { + public void testLocateTestClassesFromMultipleVersionsOfArtifact() throws Exception { File jarFile10 = - writeTestFile( "DependenciesScannerTest4-1.0.jar", "org/test/ClassA.class", "org/test/ClassB.class" ); - Artifact artifact10 = new DefaultArtifact( "org.surefire.dependency", "dependent-artifact4", - VersionRange.createFromVersion( "1.0" ), "test", "jar", null, - new DefaultArtifactHandler() ); - artifact10.setFile( jarFile10 ); + writeTestFile("DependenciesScannerTest4-1.0.jar", "org/test/ClassA.class", "org/test/ClassB.class"); + Artifact artifact10 = new DefaultArtifact( + "org.surefire.dependency", + "dependent-artifact4", + VersionRange.createFromVersion("1.0"), + "test", + "jar", + null, + new DefaultArtifactHandler()); + artifact10.setFile(jarFile10); File jarFile20 = - writeTestFile( "DependenciesScannerTest4-2.0.jar", "org/test2/ClassA.class", "org/test2/ClassB.class" ); - Artifact artifact20 = new DefaultArtifact( "org.surefire.dependency", "dependent-artifact4", - VersionRange.createFromVersion( "2.0" ), "test", "jar", null, - new DefaultArtifactHandler() ); - artifact20.setFile( jarFile20 ); + writeTestFile("DependenciesScannerTest4-2.0.jar", "org/test2/ClassA.class", "org/test2/ClassB.class"); + Artifact artifact20 = new DefaultArtifact( + "org.surefire.dependency", + "dependent-artifact4", + VersionRange.createFromVersion("2.0"), + "test", + "jar", + null, + new DefaultArtifactHandler()); + artifact20.setFile(jarFile20); List scanDependencies = new ArrayList<>(); - scanDependencies.add( "org.surefire.dependency:dependent-artifact4:*:2.0" ); + scanDependencies.add("org.surefire.dependency:dependent-artifact4:*:2.0"); List include = new ArrayList<>(); - include.add( "**/*A.java" ); + include.add("**/*A.java"); List exclude = new ArrayList<>(); - List artifacts = Arrays.asList( artifact10, artifact20 ); + List artifacts = Arrays.asList(artifact10, artifact20); - List filesToScan = filterArtifactsAsFiles( scanDependencies, artifacts ); - DependencyScanner scanner = new DependencyScanner( filesToScan, new TestListResolver( include, exclude ) ); + List filesToScan = filterArtifactsAsFiles(scanDependencies, artifacts); + DependencyScanner scanner = new DependencyScanner(filesToScan, new TestListResolver(include, exclude)); ScanResult classNames = scanner.scan(); - assertNotNull( classNames ); - assertEquals( 1, classNames.size() ); - assertEquals( "org.test2.ClassA", classNames.getClassName( 0 ) ); + assertNotNull(classNames); + assertEquals(1, classNames.size()); + assertEquals("org.test2.ClassA", classNames.getClassName(0)); Map props = new HashMap(); - classNames.writeTo( props ); - assertEquals( 1, props.size() ); - assertFalse( props.values().contains( "org.test.ClassA" ) ); + classNames.writeTo(props); + assertEquals(1, props.size()); + assertFalse(props.values().contains("org.test.ClassA")); } - private static List filterArtifactsAsFiles( List scanDependencies, List artifacts ) - { + private static List filterArtifactsAsFiles(List scanDependencies, List artifacts) { List filesToScan = new ArrayList<>(); - for ( Artifact a : DependencyScanner.filter( artifacts, scanDependencies ) ) - { - filesToScan.add( a.getFile() ); + for (Artifact a : DependencyScanner.filter(artifacts, scanDependencies)) { + filesToScan.add(a.getFile()); } return filesToScan; } - private File writeTestFile( String fileName, String... entries ) - throws Exception - { - File output = tempFolder.newFile( fileName ); + private File writeTestFile(String fileName, String... entries) throws Exception { + File output = tempFolder.newFile(fileName); - try ( ZipOutputStream out = new ZipOutputStream( new FileOutputStream( output ) ) ) - { - for ( String entry : entries ) - { - out.putNextEntry( new ZipEntry( entry ) ); + try (ZipOutputStream out = new ZipOutputStream(new FileOutputStream(output))) { + for (String entry : entries) { + out.putNextEntry(new ZipEntry(entry)); out.closeEntry(); } return output; diff --git a/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/util/DirectoryScannerTest.java b/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/util/DirectoryScannerTest.java index 89963831cb..349e711704 100644 --- a/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/util/DirectoryScannerTest.java +++ b/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/util/DirectoryScannerTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire.util; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,12 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.surefire.util; + +import java.io.File; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; import org.apache.maven.surefire.api.testset.TestListResolver; import org.apache.maven.surefire.api.util.ScanResult; @@ -26,15 +30,10 @@ import org.junit.runner.RunWith; import org.junit.runners.Parameterized; -import java.io.File; -import java.util.Arrays; -import java.util.HashMap; -import java.util.Map; - import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.greaterThanOrEqualTo; +import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue; import static org.junit.runners.Parameterized.Parameter; import static org.junit.runners.Parameterized.Parameters; @@ -42,45 +41,40 @@ /** * @author Kristian Rosenvold */ -@RunWith( Parameterized.class ) -public class DirectoryScannerTest -{ - @Parameters( name = "\"{0}\" should count {1} classes" ) - public static Iterable data() - { - return Arrays.asList( new Object[][] - { - { "**/*ZT*A.java", is( 3 ) }, - { "**/*ZT*A.java#testMethod", is( 3 ) }, - { "**/*ZT?A.java#testMethod, !*ZT2A", is( 2 ) }, - { "**/*ZT?A.java#testMethod, !*ZT2A#testMethod", is( 3 ) }, - { "#testMethod", is( greaterThanOrEqualTo( 3 ) ) } - } ); +@RunWith(Parameterized.class) +public class DirectoryScannerTest { + @Parameters(name = "\"{0}\" should count {1} classes") + public static Iterable data() { + return Arrays.asList(new Object[][] { + {"**/*ZT*A.java", is(3)}, + {"**/*ZT*A.java#testMethod", is(3)}, + {"**/*ZT?A.java#testMethod, !*ZT2A", is(2)}, + {"**/*ZT?A.java#testMethod, !*ZT2A#testMethod", is(3)}, + {"#testMethod", is(greaterThanOrEqualTo(3))} + }); } - @Parameter( 0 ) - @SuppressWarnings( "checkstyle:visibilitymodifier" ) + @Parameter(0) + @SuppressWarnings("checkstyle:visibilitymodifier") public String filter; - @Parameter( 1 ) - @SuppressWarnings( "checkstyle:visibilitymodifier" ) + @Parameter(1) + @SuppressWarnings("checkstyle:visibilitymodifier") public Matcher expectedClassesCount; @Test - public void locateTestClasses() - throws Exception - { + public void locateTestClasses() throws Exception { // use target as people can configure ide to compile in an other place than maven - File baseDir = new File( new File( "target/test-classes" ).getCanonicalPath() ); - TestListResolver resolver = new TestListResolver( filter ); - DirectoryScanner surefireDirectoryScanner = new DirectoryScanner( baseDir, resolver ); + File baseDir = new File(new File("target/test-classes").getCanonicalPath()); + TestListResolver resolver = new TestListResolver(filter); + DirectoryScanner surefireDirectoryScanner = new DirectoryScanner(baseDir, resolver); ScanResult classNames = surefireDirectoryScanner.scan(); - assertThat( classNames, is( notNullValue() ) ); - assertThat( classNames.size(), is( expectedClassesCount ) ); + assertThat(classNames, is(notNullValue())); + assertThat(classNames.size(), is(expectedClassesCount)); Map props = new HashMap<>(); - classNames.writeTo( props ); - assertThat( props.values(), hasSize( expectedClassesCount ) ); + classNames.writeTo(props); + assertThat(props.values(), hasSize(expectedClassesCount)); } } diff --git a/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/util/ScannerUtilTest.java b/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/util/ScannerUtilTest.java index 6c75ecd00f..838ad4a345 100644 --- a/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/util/ScannerUtilTest.java +++ b/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/util/ScannerUtilTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire.util; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.surefire.util; import org.junit.Test; @@ -26,30 +25,24 @@ /** * Unit test for {@link ScannerUtil} */ -public class ScannerUtilTest -{ +public class ScannerUtilTest { @Test - public void shouldConvertJarFileResourceToJavaClassName() - { - String className = ScannerUtil.convertJarFileResourceToJavaClassName( "org/apache/pkg/MyService.class" ); + public void shouldConvertJarFileResourceToJavaClassName() { + String className = ScannerUtil.convertJarFileResourceToJavaClassName("org/apache/pkg/MyService.class"); - assertThat( className ) - .isEqualTo( "org.apache.pkg.MyService" ); + assertThat(className).isEqualTo("org.apache.pkg.MyService"); - className = ScannerUtil.convertJarFileResourceToJavaClassName( "META-INF/MANIFEST.MF" ); + className = ScannerUtil.convertJarFileResourceToJavaClassName("META-INF/MANIFEST.MF"); - assertThat( className ) - .isEqualTo( "META-INF.MANIFEST.MF" ); + assertThat(className).isEqualTo("META-INF.MANIFEST.MF"); } @Test - public void shouldBeClassFile() - { - assertThat( ScannerUtil.isJavaClassFile( "META-INF/MANIFEST.MF" ) ) - .isFalse(); + public void shouldBeClassFile() { + assertThat(ScannerUtil.isJavaClassFile("META-INF/MANIFEST.MF")).isFalse(); - assertThat( ScannerUtil.isJavaClassFile( "org/apache/pkg/MyService.class" ) ) + assertThat(ScannerUtil.isJavaClassFile("org/apache/pkg/MyService.class")) .isTrue(); } } diff --git a/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/util/SpecificFileFilterTest.java b/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/util/SpecificFileFilterTest.java index 0a84ad0d0d..cb6fa4f887 100644 --- a/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/util/SpecificFileFilterTest.java +++ b/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/util/SpecificFileFilterTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire.util; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,48 +16,42 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.surefire.util; -import static org.apache.maven.plugin.surefire.util.ScannerUtil.convertSlashToSystemFileSeparator; import junit.framework.TestCase; +import static org.apache.maven.plugin.surefire.util.ScannerUtil.convertSlashToSystemFileSeparator; + /** * @author Kristian Rosenvold */ @Deprecated -public class SpecificFileFilterTest - extends TestCase -{ - public void testMatchSingleCharacterWildcard() - { - SpecificFileFilter filter = createFileFilter( "org/apache/maven/surefire/?pecificTestClassFilter.class" ); - assertTrue( filter.accept( getFile() ) ); +public class SpecificFileFilterTest extends TestCase { + public void testMatchSingleCharacterWildcard() { + SpecificFileFilter filter = createFileFilter("org/apache/maven/surefire/?pecificTestClassFilter.class"); + assertTrue(filter.accept(getFile())); } - public void testMatchSingleSegmentWordWildcard() - { - SpecificFileFilter filter = createFileFilter( "org/apache/maven/surefire/*TestClassFilter.class" ); - assertTrue( filter.accept( getFile() ) ); + public void testMatchSingleSegmentWordWildcard() { + SpecificFileFilter filter = createFileFilter("org/apache/maven/surefire/*TestClassFilter.class"); + assertTrue(filter.accept(getFile())); } - public void testMatchMultiSegmentWildcard() - { - SpecificFileFilter filter = createFileFilter( "org/**/SpecificTestClassFilter.class" ); - assertTrue( filter.accept( getFile() ) ); + public void testMatchMultiSegmentWildcard() { + SpecificFileFilter filter = createFileFilter("org/**/SpecificTestClassFilter.class"); + assertTrue(filter.accept(getFile())); } - public void testMatchSingleSegmentWildcard() - { - SpecificFileFilter filter = createFileFilter( "org/*/maven/surefire/SpecificTestClassFilter.class" ); - assertTrue( filter.accept( getFile() ) ); + public void testMatchSingleSegmentWildcard() { + SpecificFileFilter filter = createFileFilter("org/*/maven/surefire/SpecificTestClassFilter.class"); + assertTrue(filter.accept(getFile())); } - private SpecificFileFilter createFileFilter( String s ) - { - return new SpecificFileFilter( new String[]{ s } ); + private SpecificFileFilter createFileFilter(String s) { + return new SpecificFileFilter(new String[] {s}); } - private String getFile() - { - return convertSlashToSystemFileSeparator( "org/apache/maven/surefire/SpecificTestClassFilter.class" ); + private String getFile() { + return convertSlashToSystemFileSeparator("org/apache/maven/surefire/SpecificTestClassFilter.class"); } } diff --git a/maven-surefire-common/src/test/java/org/apache/maven/surefire/JUnit4SuiteTest.java b/maven-surefire-common/src/test/java/org/apache/maven/surefire/JUnit4SuiteTest.java index 509cc67fc1..316bc0407b 100644 --- a/maven-surefire-common/src/test/java/org/apache/maven/surefire/JUnit4SuiteTest.java +++ b/maven-surefire-common/src/test/java/org/apache/maven/surefire/JUnit4SuiteTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire; import junit.framework.JUnit4TestAdapter; import junit.framework.Test; @@ -74,56 +73,54 @@ * @author Tibor Digana (tibor17) * @since 2.19 */ -public class JUnit4SuiteTest extends TestCase -{ - public static Test suite() - { +public class JUnit4SuiteTest extends TestCase { + public static Test suite() { TestSuite suite = new TestSuite(); - suite.addTestSuite( RelocatorTest.class ); - suite.addTestSuite( RunStatisticsTest.class ); - suite.addTestSuite( FileReporterTest.class ); - suite.addTestSuite( org.apache.maven.surefire.report.ConsoleOutputFileReporterTest.class ); - suite.addTestSuite( SurefirePropertiesTest.class ); - suite.addTestSuite( SpecificFileFilterTest.class ); - suite.addTest( new JUnit4TestAdapter( DirectoryScannerTest.class ) ); - suite.addTest( new JUnit4TestAdapter( DependenciesScannerTest.class ) ); - suite.addTestSuite( RunEntryStatisticsMapTest.class ); - suite.addTestSuite( WrappedReportEntryTest.class ); - suite.addTestSuite( StatelessXmlReporterTest.class ); - suite.addTestSuite( DefaultReporterFactoryTest.class ); - suite.addTestSuite( ForkingRunListenerTest.class ); - suite.addTest( new JUnit4TestAdapter( ForkConfigurationTest.class ) ); - suite.addTestSuite( BooterDeserializerStartupConfigurationTest.class ); - suite.addTestSuite( BooterDeserializerProviderConfigurationTest.class ); - suite.addTest( new JUnit4TestAdapter( TestProvidingInputStreamTest.class ) ); - suite.addTest( new JUnit4TestAdapter( TestLessInputStreamBuilderTest.class ) ); - suite.addTest( new JUnit4TestAdapter( SPITest.class ) ); - suite.addTest( new JUnit4TestAdapter( SurefireHelperTest.class ) ); - suite.addTest( new JUnit4TestAdapter( AbstractSurefireMojoTest.class ) ); - suite.addTest( new JUnit4TestAdapter( DefaultForkConfigurationTest.class ) ); - suite.addTest( new JUnit4TestAdapter( JarManifestForkConfigurationTest.class ) ); - suite.addTest( new JUnit4TestAdapter( ModularClasspathForkConfigurationTest.class ) ); - suite.addTest( new JUnit4TestAdapter( AbstractSurefireMojoJava7PlusTest.class ) ); - suite.addTest( new JUnit4TestAdapter( AbstractSurefireMojoToolchainsTest.class ) ); - suite.addTest( new JUnit4TestAdapter( ScannerUtilTest.class ) ); - suite.addTest( new JUnit4TestAdapter( MojoMocklessTest.class ) ); - suite.addTest( new JUnit4TestAdapter( ForkClientTest.class ) ); - suite.addTest( new JUnit4TestAdapter( ForkedProcessEventNotifierTest.class ) ); - suite.addTest( new JUnit4TestAdapter( ConsoleOutputReporterTest.class ) ); - suite.addTest( new JUnit4TestAdapter( StatelessReporterTest.class ) ); - suite.addTest( new JUnit4TestAdapter( TestSetStatsTest.class ) ); - suite.addTest( new JUnit4TestAdapter( StatelessTestsetInfoReporterTest.class ) ); - suite.addTest( new JUnit4TestAdapter( CommonReflectorTest.class ) ); - suite.addTest( new JUnit4TestAdapter( ForkStarterTest.class ) ); - suite.addTest( new JUnit4TestAdapter( ForkChannelTest.class ) ); - suite.addTest( new JUnit4TestAdapter( StreamFeederTest.class ) ); - suite.addTest( new JUnit4TestAdapter( E2ETest.class ) ); - suite.addTest( new JUnit4TestAdapter( ThreadedStreamConsumerTest.class ) ); - suite.addTest( new JUnit4TestAdapter( EventDecoderTest.class ) ); - suite.addTest( new JUnit4TestAdapter( EventConsumerThreadTest.class ) ); - suite.addTest( new JUnit4TestAdapter( ChecksumCalculatorTest.class ) ); - suite.addTest( new JUnit4TestAdapter( AbstractSurefireMojoJunitCoreProvidersInfoTest.class ) ); - suite.addTest( new JUnit4TestAdapter( AbstractSurefireMojoProvidersInfoTest.class ) ); + suite.addTestSuite(RelocatorTest.class); + suite.addTestSuite(RunStatisticsTest.class); + suite.addTestSuite(FileReporterTest.class); + suite.addTestSuite(org.apache.maven.surefire.report.ConsoleOutputFileReporterTest.class); + suite.addTestSuite(SurefirePropertiesTest.class); + suite.addTestSuite(SpecificFileFilterTest.class); + suite.addTest(new JUnit4TestAdapter(DirectoryScannerTest.class)); + suite.addTest(new JUnit4TestAdapter(DependenciesScannerTest.class)); + suite.addTestSuite(RunEntryStatisticsMapTest.class); + suite.addTestSuite(WrappedReportEntryTest.class); + suite.addTestSuite(StatelessXmlReporterTest.class); + suite.addTestSuite(DefaultReporterFactoryTest.class); + suite.addTestSuite(ForkingRunListenerTest.class); + suite.addTest(new JUnit4TestAdapter(ForkConfigurationTest.class)); + suite.addTestSuite(BooterDeserializerStartupConfigurationTest.class); + suite.addTestSuite(BooterDeserializerProviderConfigurationTest.class); + suite.addTest(new JUnit4TestAdapter(TestProvidingInputStreamTest.class)); + suite.addTest(new JUnit4TestAdapter(TestLessInputStreamBuilderTest.class)); + suite.addTest(new JUnit4TestAdapter(SPITest.class)); + suite.addTest(new JUnit4TestAdapter(SurefireHelperTest.class)); + suite.addTest(new JUnit4TestAdapter(AbstractSurefireMojoTest.class)); + suite.addTest(new JUnit4TestAdapter(DefaultForkConfigurationTest.class)); + suite.addTest(new JUnit4TestAdapter(JarManifestForkConfigurationTest.class)); + suite.addTest(new JUnit4TestAdapter(ModularClasspathForkConfigurationTest.class)); + suite.addTest(new JUnit4TestAdapter(AbstractSurefireMojoJava7PlusTest.class)); + suite.addTest(new JUnit4TestAdapter(AbstractSurefireMojoToolchainsTest.class)); + suite.addTest(new JUnit4TestAdapter(ScannerUtilTest.class)); + suite.addTest(new JUnit4TestAdapter(MojoMocklessTest.class)); + suite.addTest(new JUnit4TestAdapter(ForkClientTest.class)); + suite.addTest(new JUnit4TestAdapter(ForkedProcessEventNotifierTest.class)); + suite.addTest(new JUnit4TestAdapter(ConsoleOutputReporterTest.class)); + suite.addTest(new JUnit4TestAdapter(StatelessReporterTest.class)); + suite.addTest(new JUnit4TestAdapter(TestSetStatsTest.class)); + suite.addTest(new JUnit4TestAdapter(StatelessTestsetInfoReporterTest.class)); + suite.addTest(new JUnit4TestAdapter(CommonReflectorTest.class)); + suite.addTest(new JUnit4TestAdapter(ForkStarterTest.class)); + suite.addTest(new JUnit4TestAdapter(ForkChannelTest.class)); + suite.addTest(new JUnit4TestAdapter(StreamFeederTest.class)); + suite.addTest(new JUnit4TestAdapter(E2ETest.class)); + suite.addTest(new JUnit4TestAdapter(ThreadedStreamConsumerTest.class)); + suite.addTest(new JUnit4TestAdapter(EventDecoderTest.class)); + suite.addTest(new JUnit4TestAdapter(EventConsumerThreadTest.class)); + suite.addTest(new JUnit4TestAdapter(ChecksumCalculatorTest.class)); + suite.addTest(new JUnit4TestAdapter(AbstractSurefireMojoJunitCoreProvidersInfoTest.class)); + suite.addTest(new JUnit4TestAdapter(AbstractSurefireMojoProvidersInfoTest.class)); return suite; } } diff --git a/maven-surefire-common/src/test/java/org/apache/maven/surefire/extensions/ForkChannelTest.java b/maven-surefire-common/src/test/java/org/apache/maven/surefire/extensions/ForkChannelTest.java index b5dbb63ed8..966bcb2397 100644 --- a/maven-surefire-common/src/test/java/org/apache/maven/surefire/extensions/ForkChannelTest.java +++ b/maven-surefire-common/src/test/java/org/apache/maven/surefire/extensions/ForkChannelTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.extensions; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,19 +16,10 @@ * specific language governing permissions and limitations * under the License. */ - -import org.apache.maven.plugin.surefire.booterclient.MockReporter; -import org.apache.maven.plugin.surefire.booterclient.lazytestprovider.TestLessInputStream; -import org.apache.maven.plugin.surefire.booterclient.lazytestprovider.TestLessInputStream.TestLessInputStreamBuilder; -import org.apache.maven.plugin.surefire.extensions.SurefireForkNodeFactory; -import org.apache.maven.plugin.surefire.log.api.ConsoleLogger; -import org.apache.maven.surefire.api.event.ControlByeEvent; -import org.apache.maven.surefire.api.event.Event; -import org.apache.maven.surefire.api.fork.ForkNodeArguments; -import org.apache.maven.surefire.extensions.util.CountdownCloseable; -import org.junit.Test; +package org.apache.maven.surefire.extensions; import javax.annotation.Nonnull; + import java.io.Closeable; import java.io.File; import java.io.IOException; @@ -45,6 +34,17 @@ import java.util.concurrent.CountDownLatch; import java.util.concurrent.atomic.AtomicBoolean; +import org.apache.maven.plugin.surefire.booterclient.MockReporter; +import org.apache.maven.plugin.surefire.booterclient.lazytestprovider.TestLessInputStream; +import org.apache.maven.plugin.surefire.booterclient.lazytestprovider.TestLessInputStream.TestLessInputStreamBuilder; +import org.apache.maven.plugin.surefire.extensions.SurefireForkNodeFactory; +import org.apache.maven.plugin.surefire.log.api.ConsoleLogger; +import org.apache.maven.surefire.api.event.ControlByeEvent; +import org.apache.maven.surefire.api.event.Event; +import org.apache.maven.surefire.api.fork.ForkNodeArguments; +import org.apache.maven.surefire.extensions.util.CountdownCloseable; +import org.junit.Test; + import static java.nio.charset.StandardCharsets.US_ASCII; import static java.util.concurrent.TimeUnit.MILLISECONDS; import static org.assertj.core.api.Assertions.assertThat; @@ -55,186 +55,154 @@ /** * */ -public class ForkChannelTest -{ +public class ForkChannelTest { private static final long TESTCASE_TIMEOUT = 30_000L; private final AtomicBoolean hasError = new AtomicBoolean(); - @Test( timeout = TESTCASE_TIMEOUT ) - public void shouldRequestReplyMessagesViaTCP() throws Exception - { + @Test(timeout = TESTCASE_TIMEOUT) + public void shouldRequestReplyMessagesViaTCP() throws Exception { final MockReporter reporter = new MockReporter(); final String sessionId = UUID.randomUUID().toString(); - ForkNodeArguments forkNodeArguments = new ForkNodeArguments() - { + ForkNodeArguments forkNodeArguments = new ForkNodeArguments() { @Override - public File getEventStreamBinaryFile() - { + public File getEventStreamBinaryFile() { return null; } @Override - public File getCommandStreamBinaryFile() - { + public File getCommandStreamBinaryFile() { return null; } @Nonnull @Override - public String getSessionId() - { + public String getSessionId() { return sessionId; } @Override - public int getForkChannelId() - { + public int getForkChannelId() { return 1; } @Override @Nonnull - public File dumpStreamText( @Nonnull String text ) - { - return new File( "" ); + public File dumpStreamText(@Nonnull String text) { + return new File(""); } @Nonnull @Override - public File dumpStreamException( @Nonnull Throwable t ) - { - return new File( "" ); + public File dumpStreamException(@Nonnull Throwable t) { + return new File(""); } @Override - public void logWarningAtEnd( @Nonnull String text ) - { - } + public void logWarningAtEnd(@Nonnull String text) {} @Override @Nonnull - public ConsoleLogger getConsoleLogger() - { + public ConsoleLogger getConsoleLogger() { return reporter; } @Nonnull @Override - public Object getConsoleLock() - { + public Object getConsoleLock() { return reporter; } }; ForkNodeFactory factory = new SurefireForkNodeFactory(); - try ( ForkChannel channel = factory.createForkChannel( forkNodeArguments ) ) - { - assertThat( channel.getArguments().getForkChannelId() ) - .isEqualTo( 1 ); + try (ForkChannel channel = factory.createForkChannel(forkNodeArguments)) { + assertThat(channel.getArguments().getForkChannelId()).isEqualTo(1); - assertThat( channel.getCountdownCloseablePermits() ) - .isEqualTo( 3 ); + assertThat(channel.getCountdownCloseablePermits()).isEqualTo(3); String localHost = InetAddress.getLoopbackAddress().getHostAddress(); - assertThat( channel.getForkNodeConnectionString() ) - .startsWith( "tcp://" + localHost + ":" ) - .isNotEqualTo( "tcp://" + localHost + ":" ) - .endsWith( "?sessionId=" + sessionId ); + assertThat(channel.getForkNodeConnectionString()) + .startsWith("tcp://" + localHost + ":") + .isNotEqualTo("tcp://" + localHost + ":") + .endsWith("?sessionId=" + sessionId); - URI uri = new URI( channel.getForkNodeConnectionString() ); + URI uri = new URI(channel.getForkNodeConnectionString()); - assertThat( uri.getPort() ) - .isPositive(); + assertThat(uri.getPort()).isPositive(); final TestLessInputStreamBuilder builder = new TestLessInputStreamBuilder(); TestLessInputStream commandReader = builder.build(); - final CountDownLatch isCloseableCalled = new CountDownLatch( 1 ); - Closeable closeable = new Closeable() - { + final CountDownLatch isCloseableCalled = new CountDownLatch(1); + Closeable closeable = new Closeable() { @Override - public void close() - { + public void close() { isCloseableCalled.countDown(); } }; - CountdownCloseable cc = new CountdownCloseable( closeable, 2 ); + CountdownCloseable cc = new CountdownCloseable(closeable, 2); Consumer consumer = new Consumer(); - Client client = new Client( uri.getPort(), sessionId ); + Client client = new Client(uri.getPort(), sessionId); client.start(); channel.tryConnectToClient(); - channel.bindCommandReader( commandReader, null ); - ReadableByteChannel stdOut = mock( ReadableByteChannel.class ); - when( stdOut.read( any( ByteBuffer.class ) ) ).thenReturn( -1 ); - channel.bindEventHandler( consumer, cc, stdOut ); + channel.bindCommandReader(commandReader, null); + ReadableByteChannel stdOut = mock(ReadableByteChannel.class); + when(stdOut.read(any(ByteBuffer.class))).thenReturn(-1); + channel.bindEventHandler(consumer, cc, stdOut); commandReader.noop(); - client.join( TESTCASE_TIMEOUT ); + client.join(TESTCASE_TIMEOUT); - assertThat( hasError.get() ) - .isFalse(); + assertThat(hasError.get()).isFalse(); - assertThat( isCloseableCalled.await( TESTCASE_TIMEOUT, MILLISECONDS ) ) - .isTrue(); + assertThat(isCloseableCalled.await(TESTCASE_TIMEOUT, MILLISECONDS)).isTrue(); - assertThat( reporter.getEvents() ) - .describedAs( "The decoder captured the list of stream errors: " + reporter.getData().toString() ) - .isEmpty(); + assertThat(reporter.getEvents()) + .describedAs("The decoder captured the list of stream errors: " + + reporter.getData().toString()) + .isEmpty(); - assertThat( consumer.lines ) - .hasSize( 1 ); + assertThat(consumer.lines).hasSize(1); - assertThat( consumer.lines.element() ) - .isInstanceOf( ControlByeEvent.class ); + assertThat(consumer.lines.element()).isInstanceOf(ControlByeEvent.class); } } - private static class Consumer implements EventHandler - { + private static class Consumer implements EventHandler { final Queue lines = new ConcurrentLinkedQueue<>(); @Override - public void handleEvent( @Nonnull Event s ) - { - lines.add( s ); + public void handleEvent(@Nonnull Event s) { + lines.add(s); } } - private final class Client extends Thread - { + private final class Client extends Thread { private final int port; private final String sessionId; - private Client( int port, String sessionId ) - { + private Client(int port, String sessionId) { this.port = port; this.sessionId = sessionId; } @Override - public void run() - { - try ( Socket socket = new Socket( InetAddress.getLoopbackAddress().getHostAddress(), port ) ) - { - socket.getOutputStream().write( sessionId.getBytes( US_ASCII ) ); + public void run() { + try (Socket socket = new Socket(InetAddress.getLoopbackAddress().getHostAddress(), port)) { + socket.getOutputStream().write(sessionId.getBytes(US_ASCII)); byte[] data = new byte[128]; - int readLength = socket.getInputStream().read( data ); - String token = new String( data, 0, readLength, US_ASCII ); - assertThat( token ).isEqualTo( ":maven-surefire-command:\u0004:noop:" ); - socket.getOutputStream().write( ":maven-surefire-event:\u0003:bye:".getBytes( US_ASCII ) ); - } - catch ( IOException e ) - { - hasError.set( true ); + int readLength = socket.getInputStream().read(data); + String token = new String(data, 0, readLength, US_ASCII); + assertThat(token).isEqualTo(":maven-surefire-command:\u0004:noop:"); + socket.getOutputStream().write(":maven-surefire-event:\u0003:bye:".getBytes(US_ASCII)); + } catch (IOException e) { + hasError.set(true); e.printStackTrace(); - throw new IllegalStateException( e ); - } - catch ( RuntimeException e ) - { - hasError.set( true ); + throw new IllegalStateException(e); + } catch (RuntimeException e) { + hasError.set(true); e.printStackTrace(); throw e; } diff --git a/maven-surefire-common/src/test/java/org/apache/maven/surefire/extensions/StatelessTestsetInfoReporterTest.java b/maven-surefire-common/src/test/java/org/apache/maven/surefire/extensions/StatelessTestsetInfoReporterTest.java index 58d2803e84..a7bd1b0ac6 100644 --- a/maven-surefire-common/src/test/java/org/apache/maven/surefire/extensions/StatelessTestsetInfoReporterTest.java +++ b/maven-surefire-common/src/test/java/org/apache/maven/surefire/extensions/StatelessTestsetInfoReporterTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.extensions; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,12 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.extensions; + +import java.io.File; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; +import java.util.List; import org.apache.maven.plugin.surefire.extensions.SurefireStatelessTestsetInfoReporter; import org.apache.maven.plugin.surefire.extensions.junit5.JUnit5StatelessTestsetInfoReporter; @@ -35,11 +39,6 @@ import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.modules.junit4.PowerMockRunner; -import java.io.File; -import java.nio.charset.Charset; -import java.nio.charset.StandardCharsets; -import java.util.List; - import static java.util.Collections.singletonList; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.anyString; @@ -54,10 +53,9 @@ /** * tests for {@link SurefireStatelessTestsetInfoReporter} and {@link JUnit5StatelessTestsetInfoReporter}. */ -@RunWith( PowerMockRunner.class ) -@PowerMockIgnore( { "org.jacoco.agent.rt.*", "com.vladium.emma.rt.*" } ) -public class StatelessTestsetInfoReporterTest -{ +@RunWith(PowerMockRunner.class) +@PowerMockIgnore({"org.jacoco.agent.rt.*", "com.vladium.emma.rt.*"}) +public class StatelessTestsetInfoReporterTest { @Mock private ConsoleLogger consoleLogger; @@ -68,162 +66,135 @@ public class StatelessTestsetInfoReporterTest private WrappedReportEntry eventTestsetFinished; @Test - public void shouldCloneReporter() - { + public void shouldCloneReporter() { SurefireStatelessTestsetInfoReporter extension = new SurefireStatelessTestsetInfoReporter(); - extension.setDisable( true ); + extension.setDisable(true); ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); - Object clone = extension.clone( classLoader ); - assertThat( clone ) - .isNotSameAs( extension ); - assertThat( clone ) - .isInstanceOf( SurefireStatelessTestsetInfoReporter.class ); - assertThat( clone.toString() ) - .isEqualTo( "SurefireStatelessTestsetInfoReporter{disable=true}" ); - assertThat( ( (SurefireStatelessTestsetInfoReporter) clone ).isDisable() ) - .isTrue(); + Object clone = extension.clone(classLoader); + assertThat(clone).isNotSameAs(extension); + assertThat(clone).isInstanceOf(SurefireStatelessTestsetInfoReporter.class); + assertThat(clone.toString()).isEqualTo("SurefireStatelessTestsetInfoReporter{disable=true}"); + assertThat(((SurefireStatelessTestsetInfoReporter) clone).isDisable()).isTrue(); } @Test - public void shouldAssertToStringReporter() - { + public void shouldAssertToStringReporter() { SurefireStatelessTestsetInfoReporter extension = new SurefireStatelessTestsetInfoReporter(); - assertThat( extension.toString() ) - .isEqualTo( "SurefireStatelessTestsetInfoReporter{disable=false}" ); + assertThat(extension.toString()).isEqualTo("SurefireStatelessTestsetInfoReporter{disable=false}"); } @Test - public void shouldCreateFileReporterListener() - { - File target = new File( System.getProperty( "user.dir" ), "target" ); - File reportsDirectory = new File( target, "surefire-reports" ); + public void shouldCreateFileReporterListener() { + File target = new File(System.getProperty("user.dir"), "target"); + File reportsDirectory = new File(target, "surefire-reports"); String reportNameSuffix = "suffix"; Charset encoding = StandardCharsets.UTF_8; SurefireStatelessTestsetInfoReporter extension = new SurefireStatelessTestsetInfoReporter(); - assertThat( extension.isDisable() ) - .isFalse(); - extension.setDisable( true ); - assertThat( extension.isDisable() ) - .isTrue(); + assertThat(extension.isDisable()).isFalse(); + extension.setDisable(true); + assertThat(extension.isDisable()).isTrue(); StatelessTestsetInfoFileReportEventListener listener = - extension.createListener( reportsDirectory, reportNameSuffix, encoding ); - assertThat( listener ) - .isInstanceOf( FileReporter.class ); - assertThat( listener.getReportsDirectory() ) - .isSameAs( reportsDirectory ); - assertThat( listener.getReportNameSuffix() ) - .isSameAs( reportNameSuffix ); - assertThat( listener.getEncoding() ) - .isSameAs( encoding ); - assertThat( (boolean) getInternalState( listener, "usePhrasedFileName" ) ) - .isEqualTo( false ); - assertThat( (boolean) getInternalState( listener, "usePhrasedClassNameInRunning" ) ) - .isEqualTo( false ); - assertThat( (boolean) getInternalState( listener, "usePhrasedClassNameInTestCaseSummary" ) ) - .isEqualTo( false ); + extension.createListener(reportsDirectory, reportNameSuffix, encoding); + assertThat(listener).isInstanceOf(FileReporter.class); + assertThat(listener.getReportsDirectory()).isSameAs(reportsDirectory); + assertThat(listener.getReportNameSuffix()).isSameAs(reportNameSuffix); + assertThat(listener.getEncoding()).isSameAs(encoding); + assertThat((boolean) getInternalState(listener, "usePhrasedFileName")).isEqualTo(false); + assertThat((boolean) getInternalState(listener, "usePhrasedClassNameInRunning")) + .isEqualTo(false); + assertThat((boolean) getInternalState(listener, "usePhrasedClassNameInTestCaseSummary")) + .isEqualTo(false); } @Test - public void shouldCreateConsoleReporterListener() - { + public void shouldCreateConsoleReporterListener() { SurefireStatelessTestsetInfoReporter extension = new SurefireStatelessTestsetInfoReporter(); - assertThat( extension.isDisable() ) - .isFalse(); - extension.setDisable( true ); - assertThat( extension.isDisable() ) - .isTrue(); + assertThat(extension.isDisable()).isFalse(); + extension.setDisable(true); + assertThat(extension.isDisable()).isTrue(); StatelessTestsetInfoConsoleReportEventListener listener = - extension.createListener( consoleLogger ); - assertThat( listener ) - .isInstanceOf( ConsoleReporter.class ); - assertThat( listener.getConsoleLogger() ) - .isSameAs( consoleLogger ); - assertThat( (boolean) getInternalState( listener, "usePhrasedClassNameInRunning" ) ) - .isEqualTo( false ); - assertThat( (boolean) getInternalState( listener, "usePhrasedClassNameInTestCaseSummary" ) ) - .isEqualTo( false ); + extension.createListener(consoleLogger); + assertThat(listener).isInstanceOf(ConsoleReporter.class); + assertThat(listener.getConsoleLogger()).isSameAs(consoleLogger); + assertThat((boolean) getInternalState(listener, "usePhrasedClassNameInRunning")) + .isEqualTo(false); + assertThat((boolean) getInternalState(listener, "usePhrasedClassNameInTestCaseSummary")) + .isEqualTo(false); } @Test - public void shouldCloneJUnit5Reporter() - { + public void shouldCloneJUnit5Reporter() { JUnit5StatelessTestsetInfoReporter extension = new JUnit5StatelessTestsetInfoReporter(); - extension.setDisable( true ); - extension.setUsePhrasedFileName( true ); - extension.setUsePhrasedClassNameInTestCaseSummary( true ); - extension.setUsePhrasedClassNameInRunning( true ); + extension.setDisable(true); + extension.setUsePhrasedFileName(true); + extension.setUsePhrasedClassNameInTestCaseSummary(true); + extension.setUsePhrasedClassNameInRunning(true); ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); - Object clone = extension.clone( classLoader ); - assertThat( clone ) - .isNotSameAs( extension ); - assertThat( clone ) - .isInstanceOf( JUnit5StatelessTestsetInfoReporter.class ); - assertThat( clone.toString() ) - .isEqualTo( "JUnit5StatelessTestsetInfoReporter{disable=true, usePhrasedFileName=true, " - + "usePhrasedClassNameInRunning=true, usePhrasedClassNameInTestCaseSummary=true}" ); - assertThat( ( (JUnit5StatelessTestsetInfoReporter) clone ).isDisable() ) - .isTrue(); - assertThat( ( (JUnit5StatelessTestsetInfoReporter) clone ).isUsePhrasedFileName() ) + Object clone = extension.clone(classLoader); + assertThat(clone).isNotSameAs(extension); + assertThat(clone).isInstanceOf(JUnit5StatelessTestsetInfoReporter.class); + assertThat(clone.toString()) + .isEqualTo("JUnit5StatelessTestsetInfoReporter{disable=true, usePhrasedFileName=true, " + + "usePhrasedClassNameInRunning=true, usePhrasedClassNameInTestCaseSummary=true}"); + assertThat(((JUnit5StatelessTestsetInfoReporter) clone).isDisable()).isTrue(); + assertThat(((JUnit5StatelessTestsetInfoReporter) clone).isUsePhrasedFileName()) .isTrue(); - assertThat( ( (JUnit5StatelessTestsetInfoReporter) clone ).isUsePhrasedClassNameInTestCaseSummary() ) + assertThat(((JUnit5StatelessTestsetInfoReporter) clone).isUsePhrasedClassNameInTestCaseSummary()) .isTrue(); - assertThat( ( (JUnit5StatelessTestsetInfoReporter) clone ).isUsePhrasedClassNameInRunning() ) + assertThat(((JUnit5StatelessTestsetInfoReporter) clone).isUsePhrasedClassNameInRunning()) .isTrue(); } @Test - public void shouldAssertToStringJUnit5Reporter() - { + public void shouldAssertToStringJUnit5Reporter() { JUnit5StatelessTestsetInfoReporter extension = new JUnit5StatelessTestsetInfoReporter(); - assertThat( extension.toString() ) - .isEqualTo( "JUnit5StatelessTestsetInfoReporter{disable=false, usePhrasedFileName=false, " - + "usePhrasedClassNameInRunning=false, usePhrasedClassNameInTestCaseSummary=false}" ); + assertThat(extension.toString()) + .isEqualTo("JUnit5StatelessTestsetInfoReporter{disable=false, usePhrasedFileName=false, " + + "usePhrasedClassNameInRunning=false, usePhrasedClassNameInTestCaseSummary=false}"); } @Test - public void shouldReportTestsetLifecycle() - { - ConsoleReporter consoleReporter = new ConsoleReporter( consoleLogger, false, false ); - MessageUtils.setColorEnabled( false ); - - when( eventTestsetStarting.getNameWithGroup() ).thenReturn( "pkg.MyTest" ); - when( eventTestsetFinished.getNameWithGroup() ).thenReturn( "pkg.MyTest" ); - when( eventTestsetFinished.getElapsedTimeVerbose() ).thenReturn( "Time elapsed: 1.03 s" ); - - consoleReporter.testSetStarting( eventTestsetStarting ); - ArgumentCaptor logs = ArgumentCaptor.forClass( String.class ); - verify( consoleLogger, times( 1 ) ).info( logs.capture() ); - verifyNoMoreInteractions( consoleLogger ); - assertThat( logs.getAllValues() ) - .hasSize( 1 ) - .contains( "Running pkg.MyTest" ); - - TestSetStats testSetStats = new TestSetStats( false, true ); + public void shouldReportTestsetLifecycle() { + ConsoleReporter consoleReporter = new ConsoleReporter(consoleLogger, false, false); + MessageUtils.setColorEnabled(false); + + when(eventTestsetStarting.getNameWithGroup()).thenReturn("pkg.MyTest"); + when(eventTestsetFinished.getNameWithGroup()).thenReturn("pkg.MyTest"); + when(eventTestsetFinished.getElapsedTimeVerbose()).thenReturn("Time elapsed: 1.03 s"); + + consoleReporter.testSetStarting(eventTestsetStarting); + ArgumentCaptor logs = ArgumentCaptor.forClass(String.class); + verify(consoleLogger, times(1)).info(logs.capture()); + verifyNoMoreInteractions(consoleLogger); + assertThat(logs.getAllValues()).hasSize(1).contains("Running pkg.MyTest"); + + TestSetStats testSetStats = new TestSetStats(false, true); testSetStats.testStart(); - testSetStats.testFailure( eventTestsetFinished ); - assertThat( testSetStats.getCompletedCount() ).isEqualTo( 1 ); - assertThat( testSetStats.getFailures() ).isEqualTo( 1 ); - assertThat( testSetStats.getErrors() ).isEqualTo( 0 ); - assertThat( testSetStats.getSkipped() ).isEqualTo( 0 ); - reset( consoleLogger ); - consoleReporter.testSetCompleted( eventTestsetFinished, testSetStats, singletonList( "pkg.MyTest failed" ) ); + testSetStats.testFailure(eventTestsetFinished); + assertThat(testSetStats.getCompletedCount()).isEqualTo(1); + assertThat(testSetStats.getFailures()).isEqualTo(1); + assertThat(testSetStats.getErrors()).isEqualTo(0); + assertThat(testSetStats.getSkipped()).isEqualTo(0); + reset(consoleLogger); + consoleReporter.testSetCompleted(eventTestsetFinished, testSetStats, singletonList("pkg.MyTest failed")); consoleReporter.reset(); - verify( consoleLogger, never() ).info( anyString() ); - verify( consoleLogger, never() ).warning( anyString() ); - logs = ArgumentCaptor.forClass( String.class ); - verify( consoleLogger, times( 2 ) ).error( logs.capture() ); + verify(consoleLogger, never()).info(anyString()); + verify(consoleLogger, never()).warning(anyString()); + logs = ArgumentCaptor.forClass(String.class); + verify(consoleLogger, times(2)).error(logs.capture()); List messages = logs.getAllValues(); - assertThat( messages ) - .hasSize( 2 ) + assertThat(messages) + .hasSize(2) .containsSequence( "Tests run: 1, Failures: 1, Errors: 0, Skipped: 0, Time elapsed: 1.03 s " - + "<<< FAILURE! - in pkg.MyTest", "pkg.MyTest failed" ); - verifyNoMoreInteractions( consoleLogger ); + + "<<< FAILURE! - in pkg.MyTest", + "pkg.MyTest failed"); + verifyNoMoreInteractions(consoleLogger); } } diff --git a/maven-surefire-common/src/test/java/org/apache/maven/surefire/providerapi/ProviderDetectorTest.java b/maven-surefire-common/src/test/java/org/apache/maven/surefire/providerapi/ProviderDetectorTest.java index 161b4c631a..77eff14d48 100644 --- a/maven-surefire-common/src/test/java/org/apache/maven/surefire/providerapi/ProviderDetectorTest.java +++ b/maven-surefire-common/src/test/java/org/apache/maven/surefire/providerapi/ProviderDetectorTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.providerapi; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.providerapi; import java.io.IOException; import java.util.Collections; @@ -44,15 +43,13 @@ import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; - /** * Unit test for ProviderDetector. * * @author Slawomir Jaranowski */ -@RunWith( MockitoJUnitRunner.class ) -public class ProviderDetectorTest -{ +@RunWith(MockitoJUnitRunner.class) +public class ProviderDetectorTest { @Mock private ServiceLoader serviceLoader; @@ -64,140 +61,135 @@ public class ProviderDetectorTest private ProviderDetector providerDetector; @Test - public void emptyProviderList() throws Exception - { + public void emptyProviderList() throws Exception { // given - ProviderInfo providerInfo1 = mock( ProviderInfo.class ); - ProviderInfo providerInfo2 = mock( ProviderInfo.class ); + ProviderInfo providerInfo1 = mock(ProviderInfo.class); + ProviderInfo providerInfo2 = mock(ProviderInfo.class); // no manually configured providers - when( serviceLoader.lookup( eq( SurefireProvider.class ), any( ClassLoader.class ) ) ) - .thenReturn( Collections.emptySet() ); + when(serviceLoader.lookup(eq(SurefireProvider.class), any(ClassLoader.class))) + .thenReturn(Collections.emptySet()); // all well known providers are not applicable - when( providerInfo1.isApplicable() ).thenReturn( false ); - when( providerInfo2.isApplicable() ).thenReturn( false ); + when(providerInfo1.isApplicable()).thenReturn(false); + when(providerInfo2.isApplicable()).thenReturn(false); // when - List providerInfoList = providerDetector.resolve( null, providerInfo1, providerInfo2 ); + List providerInfoList = providerDetector.resolve(null, providerInfo1, providerInfo2); // then - assertThat( providerInfoList ).isEmpty(); + assertThat(providerInfoList).isEmpty(); - verify( serviceLoader ).lookup( eq( SurefireProvider.class ), any( ClassLoader.class ) ); + verify(serviceLoader).lookup(eq(SurefireProvider.class), any(ClassLoader.class)); - verify( providerInfo1 ).isApplicable(); - verify( providerInfo2 ).isApplicable(); + verify(providerInfo1).isApplicable(); + verify(providerInfo2).isApplicable(); - verifyNoMoreInteractions( logger, serviceLoader, providerInfo1, providerInfo2 ); + verifyNoMoreInteractions(logger, serviceLoader, providerInfo1, providerInfo2); } @Test - public void onlyFirstAutomaticallyProviderIsReturned() throws Exception - { + public void onlyFirstAutomaticallyProviderIsReturned() throws Exception { // given - ProviderInfo providerInfo1 = mock( ProviderInfo.class ); - ProviderInfo providerInfo2 = mock( ProviderInfo.class ); + ProviderInfo providerInfo1 = mock(ProviderInfo.class); + ProviderInfo providerInfo2 = mock(ProviderInfo.class); // no manually configured providers - when( serviceLoader.lookup( eq( SurefireProvider.class ), any( ClassLoader.class ) ) ) - .thenReturn( Collections.emptySet() ); + when(serviceLoader.lookup(eq(SurefireProvider.class), any(ClassLoader.class))) + .thenReturn(Collections.emptySet()); // first well known providers are applicable - when( providerInfo1.isApplicable() ).thenReturn( true ); + when(providerInfo1.isApplicable()).thenReturn(true); // when - List providerInfoList = providerDetector.resolve( null, providerInfo1, providerInfo2 ); + List providerInfoList = providerDetector.resolve(null, providerInfo1, providerInfo2); // then - only first is returned - assertThat( providerInfoList ).containsExactly( providerInfo1 ); + assertThat(providerInfoList).containsExactly(providerInfo1); - verify( serviceLoader ).lookup( eq( SurefireProvider.class ), any( ClassLoader.class ) ); + verify(serviceLoader).lookup(eq(SurefireProvider.class), any(ClassLoader.class)); - verify( providerInfo1 ).isApplicable(); - verify( providerInfo1 ).getProviderName(); + verify(providerInfo1).isApplicable(); + verify(providerInfo1).getProviderName(); // second provider is not checked - verify( providerInfo2, never() ).isApplicable(); + verify(providerInfo2, never()).isApplicable(); - verify( logger ).info( anyString() ); + verify(logger).info(anyString()); - verifyNoMoreInteractions( logger, serviceLoader, providerInfo1, providerInfo2 ); + verifyNoMoreInteractions(logger, serviceLoader, providerInfo1, providerInfo2); } @Test - public void allManuallyConfiguredProviderAreReturned() throws IOException - { + public void allManuallyConfiguredProviderAreReturned() throws IOException { // given - ProviderInfo providerInfo1 = mock( ProviderInfo.class ); - ProviderInfo providerInfo2 = mock( ProviderInfo.class ); + ProviderInfo providerInfo1 = mock(ProviderInfo.class); + ProviderInfo providerInfo2 = mock(ProviderInfo.class); // manually configured providers - when( serviceLoader.lookup( eq( SurefireProvider.class ), any( ClassLoader.class ) ) ) - .thenReturn( new HashSet<>( asList( "provider1", "provider2" ) ) ); + when(serviceLoader.lookup(eq(SurefireProvider.class), any(ClassLoader.class))) + .thenReturn(new HashSet<>(asList("provider1", "provider2"))); - when( providerInfo1.getProviderName() ).thenReturn( "provider1" ); - when( providerInfo2.getProviderName() ).thenReturn( "provider2" ); + when(providerInfo1.getProviderName()).thenReturn("provider1"); + when(providerInfo2.getProviderName()).thenReturn("provider2"); // when - List providerInfoList = providerDetector.resolve( null, providerInfo1, providerInfo2 ); + List providerInfoList = providerDetector.resolve(null, providerInfo1, providerInfo2); // then - all providers on list - assertThat( providerInfoList ).containsExactly( providerInfo1, providerInfo2 ); + assertThat(providerInfoList).containsExactly(providerInfo1, providerInfo2); - verify( serviceLoader ).lookup( eq( SurefireProvider.class ), any( ClassLoader.class ) ); + verify(serviceLoader).lookup(eq(SurefireProvider.class), any(ClassLoader.class)); - verify( providerInfo1, times( 3 ) ).getProviderName(); - verify( providerInfo2, times( 2 ) ).getProviderName(); + verify(providerInfo1, times(3)).getProviderName(); + verify(providerInfo2, times(2)).getProviderName(); // don't check - if it should be used ??? - verify( providerInfo1, never() ).isApplicable(); - verify( providerInfo1, never() ).isApplicable(); + verify(providerInfo1, never()).isApplicable(); + verify(providerInfo1, never()).isApplicable(); - verify( logger, times( 2 ) ).info( anyString() ); + verify(logger, times(2)).info(anyString()); - verifyNoMoreInteractions( logger, serviceLoader, providerInfo1, providerInfo2 ); + verifyNoMoreInteractions(logger, serviceLoader, providerInfo1, providerInfo2); } @Test - public void dynamicallyProviderAreReturned() throws IOException - { + public void dynamicallyProviderAreReturned() throws IOException { // given - ProviderInfo providerInfo1 = mock( ProviderInfo.class ); - ProviderInfo providerInfo2 = mock( ProviderInfo.class ); - ProviderInfo dynProviderInfo = mock( ProviderInfo.class ); + ProviderInfo providerInfo1 = mock(ProviderInfo.class); + ProviderInfo providerInfo2 = mock(ProviderInfo.class); + ProviderInfo dynProviderInfo = mock(ProviderInfo.class); - ConfigurableProviderInfo dynamicProvider = mock( ConfigurableProviderInfo.class ); + ConfigurableProviderInfo dynamicProvider = mock(ConfigurableProviderInfo.class); // manually configured providers - when( serviceLoader.lookup( eq( SurefireProvider.class ), any( ClassLoader.class ) ) ) - .thenReturn( new HashSet<>( asList( "unKnown", "provider2" ) ) ); + when(serviceLoader.lookup(eq(SurefireProvider.class), any(ClassLoader.class))) + .thenReturn(new HashSet<>(asList("unKnown", "provider2"))); - when( dynamicProvider.instantiate( anyString() ) ).thenReturn( dynProviderInfo ); + when(dynamicProvider.instantiate(anyString())).thenReturn(dynProviderInfo); - when( providerInfo1.getProviderName() ).thenReturn( "provider1" ); - when( providerInfo2.getProviderName() ).thenReturn( "provider2" ); + when(providerInfo1.getProviderName()).thenReturn("provider1"); + when(providerInfo2.getProviderName()).thenReturn("provider2"); // when - List providerInfoList = providerDetector.resolve( dynamicProvider, providerInfo1, providerInfo2 ); + List providerInfoList = providerDetector.resolve(dynamicProvider, providerInfo1, providerInfo2); // then - all providers on list - assertThat( providerInfoList ).containsExactly( dynProviderInfo, providerInfo2 ); + assertThat(providerInfoList).containsExactly(dynProviderInfo, providerInfo2); - verify( serviceLoader ).lookup( eq( SurefireProvider.class ), any( ClassLoader.class ) ); + verify(serviceLoader).lookup(eq(SurefireProvider.class), any(ClassLoader.class)); - verify( dynamicProvider ).instantiate( "unKnown" ); + verify(dynamicProvider).instantiate("unKnown"); - verify( providerInfo1, times( 2 ) ).getProviderName(); - verify( providerInfo2, times( 3 ) ).getProviderName(); + verify(providerInfo1, times(2)).getProviderName(); + verify(providerInfo2, times(3)).getProviderName(); // don't check - if it should be used ??? - verify( providerInfo1, never() ).isApplicable(); - verify( dynamicProvider, never() ).isApplicable(); + verify(providerInfo1, never()).isApplicable(); + verify(dynamicProvider, never()).isApplicable(); - verify( logger, times( 2 ) ).info( anyString() ); + verify(logger, times(2)).info(anyString()); - verifyNoMoreInteractions( logger, serviceLoader, dynamicProvider, providerInfo1, providerInfo2 ); + verifyNoMoreInteractions(logger, serviceLoader, dynamicProvider, providerInfo1, providerInfo2); } - } diff --git a/maven-surefire-common/src/test/java/org/apache/maven/surefire/report/ConsoleOutputFileReporterTest.java b/maven-surefire-common/src/test/java/org/apache/maven/surefire/report/ConsoleOutputFileReporterTest.java index 6b0ee446a6..ca9382fb5a 100644 --- a/maven-surefire-common/src/test/java/org/apache/maven/surefire/report/ConsoleOutputFileReporterTest.java +++ b/maven-surefire-common/src/test/java/org/apache/maven/surefire/report/ConsoleOutputFileReporterTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.report; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.report; import java.io.File; import java.io.IOException; @@ -42,32 +41,29 @@ /** * */ -public class ConsoleOutputFileReporterTest - extends TestCase -{ +public class ConsoleOutputFileReporterTest extends TestCase { /* * Test method for 'org.codehaus.surefire.report.ConsoleOutputFileReporter.testSetCompleted(ReportEntry report)' */ - public void testFileNameWithoutSuffix() throws IOException - { - File reportDir = new File( new File( System.getProperty( "user.dir" ), "target" ), "tmp1" ); + public void testFileNameWithoutSuffix() throws IOException { + File reportDir = new File(new File(System.getProperty("user.dir"), "target"), "tmp1"); //noinspection ResultOfMethodCallIgnored reportDir.mkdirs(); - TestSetReportEntry reportEntry = - new SimpleReportEntry( NORMAL_RUN, 1L, getClass().getName(), null, getClass().getName(), null ); - ConsoleOutputFileReporter reporter = new ConsoleOutputFileReporter( reportDir, null, false, null, "UTF-8" ); - reporter.testSetStarting( reportEntry ); - reporter.writeTestOutput( (TestOutputReportEntry) stdOut( "some " ) ); - reporter.testSetCompleted( reportEntry ); + TestSetReportEntry reportEntry = new SimpleReportEntry( + NORMAL_RUN, 1L, getClass().getName(), null, getClass().getName(), null); + ConsoleOutputFileReporter reporter = new ConsoleOutputFileReporter(reportDir, null, false, null, "UTF-8"); + reporter.testSetStarting(reportEntry); + reporter.writeTestOutput((TestOutputReportEntry) stdOut("some ")); + reporter.testSetCompleted(reportEntry); reporter.close(); - File expectedReportFile = new File( reportDir, getClass().getName() + "-output.txt" ); + File expectedReportFile = new File(reportDir, getClass().getName() + "-output.txt"); - assertTrue( "Report file (" + expectedReportFile.getAbsolutePath() + ") doesn't exist", - expectedReportFile.exists() ); + assertTrue( + "Report file (" + expectedReportFile.getAbsolutePath() + ") doesn't exist", + expectedReportFile.exists()); - assertThat( FileUtils.fileRead( expectedReportFile, US_ASCII.name() ) ) - .contains( "some " ); + assertThat(FileUtils.fileRead(expectedReportFile, US_ASCII.name())).contains("some "); //noinspection ResultOfMethodCallIgnored expectedReportFile.delete(); @@ -76,97 +72,86 @@ public void testFileNameWithoutSuffix() throws IOException /* * Test method for 'org.codehaus.surefire.report.ConsoleOutputFileReporter.testSetCompleted(ReportEntry report)' */ - public void testFileNameWithSuffix() throws IOException - { - File reportDir = new File( new File( System.getProperty( "user.dir" ), "target" ), "tmp2" ); + public void testFileNameWithSuffix() throws IOException { + File reportDir = new File(new File(System.getProperty("user.dir"), "target"), "tmp2"); String suffixText = "sampleSuffixText"; - TestSetReportEntry reportEntry = - new SimpleReportEntry( NORMAL_RUN, 1L, getClass().getName(), null, getClass().getName(), null ); - ConsoleOutputFileReporter reporter = - new ConsoleOutputFileReporter( reportDir, suffixText, false, null, "UTF-8" ); - reporter.testSetStarting( reportEntry ); - reporter.writeTestOutput( stdOutln( null ) ); - reporter.writeTestOutput( stdOutln( "some " ) ); - reporter.testSetCompleted( reportEntry ); + TestSetReportEntry reportEntry = new SimpleReportEntry( + NORMAL_RUN, 1L, getClass().getName(), null, getClass().getName(), null); + ConsoleOutputFileReporter reporter = new ConsoleOutputFileReporter(reportDir, suffixText, false, null, "UTF-8"); + reporter.testSetStarting(reportEntry); + reporter.writeTestOutput(stdOutln(null)); + reporter.writeTestOutput(stdOutln("some ")); + reporter.testSetCompleted(reportEntry); reporter.close(); - File expectedReportFile = new File( reportDir, getClass().getName() + "-" + suffixText + "-output.txt" ); + File expectedReportFile = new File(reportDir, getClass().getName() + "-" + suffixText + "-output.txt"); - assertTrue( "Report file (" + expectedReportFile.getAbsolutePath() + ") doesn't exist", - expectedReportFile.exists() ); + assertTrue( + "Report file (" + expectedReportFile.getAbsolutePath() + ") doesn't exist", + expectedReportFile.exists()); - assertThat( FileUtils.fileRead( expectedReportFile, US_ASCII.name() ) ) - .contains( "some " ); + assertThat(FileUtils.fileRead(expectedReportFile, US_ASCII.name())).contains("some "); - assertThat( expectedReportFile ) - .hasSize( 9 + 2 * System.lineSeparator().length() ); + assertThat(expectedReportFile).hasSize(9 + 2 * System.lineSeparator().length()); //noinspection ResultOfMethodCallIgnored expectedReportFile.delete(); } - public void testNullReportFile() throws IOException - { - File reportDir = new File( new File( System.getProperty( "user.dir" ), "target" ), "tmp3" ); - ConsoleOutputFileReporter reporter = new ConsoleOutputFileReporter( reportDir, null, false, null, "UTF-8" ); - reporter.writeTestOutput( (TestOutputReportEntry) stdOut( "some text" ) ); - reporter.testSetCompleted( - new SimpleReportEntry( NORMAL_RUN, 1L, getClass().getName(), null, getClass().getName(), null ) ); + public void testNullReportFile() throws IOException { + File reportDir = new File(new File(System.getProperty("user.dir"), "target"), "tmp3"); + ConsoleOutputFileReporter reporter = new ConsoleOutputFileReporter(reportDir, null, false, null, "UTF-8"); + reporter.writeTestOutput((TestOutputReportEntry) stdOut("some text")); + reporter.testSetCompleted(new SimpleReportEntry( + NORMAL_RUN, 1L, getClass().getName(), null, getClass().getName(), null)); reporter.close(); - File expectedReportFile = new File( reportDir, "null-output.txt" ); + File expectedReportFile = new File(reportDir, "null-output.txt"); - assertTrue( "Report file (" + expectedReportFile.getAbsolutePath() + ") doesn't exist", - expectedReportFile.exists() ); + assertTrue( + "Report file (" + expectedReportFile.getAbsolutePath() + ") doesn't exist", + expectedReportFile.exists()); - assertThat( FileUtils.fileRead( expectedReportFile, US_ASCII.name() ) ) - .contains( "some " ); + assertThat(FileUtils.fileRead(expectedReportFile, US_ASCII.name())).contains("some "); //noinspection ResultOfMethodCallIgnored expectedReportFile.delete(); } - public void testConcurrentAccessReportFile() throws Exception - { - File reportDir = new File( new File( System.getProperty( "user.dir" ), "target" ), "tmp4" ); - final ConsoleOutputFileReporter reporter = - new ConsoleOutputFileReporter( reportDir, null, false, null, "UTF-8" ); - reporter.testSetStarting( - new SimpleReportEntry( NORMAL_RUN, 1L, getClass().getName(), null, getClass().getName(), null ) ); - ExecutorService scheduler = Executors.newFixedThreadPool( 10 ); + public void testConcurrentAccessReportFile() throws Exception { + File reportDir = new File(new File(System.getProperty("user.dir"), "target"), "tmp4"); + final ConsoleOutputFileReporter reporter = new ConsoleOutputFileReporter(reportDir, null, false, null, "UTF-8"); + reporter.testSetStarting(new SimpleReportEntry( + NORMAL_RUN, 1L, getClass().getName(), null, getClass().getName(), null)); + ExecutorService scheduler = Executors.newFixedThreadPool(10); final ArrayList> jobs = new ArrayList<>(); - for ( int i = 0; i < 10; i++ ) - { - jobs.add( new Callable() - { + for (int i = 0; i < 10; i++) { + jobs.add(new Callable() { @Override - public Void call() - { - reporter.writeTestOutput( (TestOutputReportEntry) stdOut( "some text\n" ) ); + public Void call() { + reporter.writeTestOutput((TestOutputReportEntry) stdOut("some text\n")); return null; } - } ); + }); } - scheduler.invokeAll( jobs ); + scheduler.invokeAll(jobs); scheduler.shutdown(); reporter.close(); - File expectedReportFile = new File( reportDir, getClass().getName() + "-output.txt" ); + File expectedReportFile = new File(reportDir, getClass().getName() + "-output.txt"); - assertTrue( "Report file (" + expectedReportFile.getAbsolutePath() + ") doesn't exist", - expectedReportFile.exists() ); + assertTrue( + "Report file (" + expectedReportFile.getAbsolutePath() + ") doesn't exist", + expectedReportFile.exists()); - assertThat( FileUtils.fileRead( expectedReportFile, US_ASCII.name() ) ) - .contains( "some text" ); + assertThat(FileUtils.fileRead(expectedReportFile, US_ASCII.name())).contains("some text"); StringBuilder expectedText = new StringBuilder(); - for ( int i = 0; i < 10; i++ ) - { - expectedText.append( "some text\n" ); + for (int i = 0; i < 10; i++) { + expectedText.append("some text\n"); } - assertThat( FileUtils.fileRead( expectedReportFile, US_ASCII.name() ) ) - .isEqualTo( expectedText.toString() ); + assertThat(FileUtils.fileRead(expectedReportFile, US_ASCII.name())).isEqualTo(expectedText.toString()); //noinspection ResultOfMethodCallIgnored expectedReportFile.delete(); diff --git a/maven-surefire-common/src/test/java/org/apache/maven/surefire/report/FileReporterTest.java b/maven-surefire-common/src/test/java/org/apache/maven/surefire/report/FileReporterTest.java index beecd50730..98478237cc 100644 --- a/maven-surefire-common/src/test/java/org/apache/maven/surefire/report/FileReporterTest.java +++ b/maven-surefire-common/src/test/java/org/apache/maven/surefire/report/FileReporterTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.report; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.report; import java.io.File; import java.nio.charset.Charset; @@ -36,9 +35,7 @@ /** * */ -public class FileReporterTest - extends TestCase -{ +public class FileReporterTest extends TestCase { private FileReporter reporter; @@ -46,40 +43,39 @@ public class FileReporterTest private static final String TEST_NAME = "org.apache.maven.surefire.report.FileReporterTest"; - public void testFileNameWithoutSuffix() - { - File reportDir = new File( "target" ); - reportEntry = new SimpleReportEntry( NORMAL_RUN, 1L, getClass().getName(), null, TEST_NAME, null ); + public void testFileNameWithoutSuffix() { + File reportDir = new File("target"); + reportEntry = new SimpleReportEntry(NORMAL_RUN, 1L, getClass().getName(), null, TEST_NAME, null); WrappedReportEntry wrappedReportEntry = - new WrappedReportEntry( reportEntry, ReportEntryType.SUCCESS, 12, null, null ); - reporter = new FileReporter( reportDir, null, Charset.defaultCharset(), false, false, false ); - reporter.testSetCompleted( wrappedReportEntry, createTestSetStats(), new ArrayList() ); + new WrappedReportEntry(reportEntry, ReportEntryType.SUCCESS, 12, null, null); + reporter = new FileReporter(reportDir, null, Charset.defaultCharset(), false, false, false); + reporter.testSetCompleted(wrappedReportEntry, createTestSetStats(), new ArrayList()); - File expectedReportFile = new File( reportDir, TEST_NAME + ".txt" ); - assertTrue( "Report file (" + expectedReportFile.getAbsolutePath() + ") doesn't exist", - expectedReportFile.exists() ); + File expectedReportFile = new File(reportDir, TEST_NAME + ".txt"); + assertTrue( + "Report file (" + expectedReportFile.getAbsolutePath() + ") doesn't exist", + expectedReportFile.exists()); //noinspection ResultOfMethodCallIgnored expectedReportFile.delete(); } - private TestSetStats createTestSetStats() - { - return new TestSetStats( true, true ); + private TestSetStats createTestSetStats() { + return new TestSetStats(true, true); } - public void testFileNameWithSuffix() - { - File reportDir = new File( "target" ); + public void testFileNameWithSuffix() { + File reportDir = new File("target"); String suffixText = "sampleSuffixText"; - reportEntry = new SimpleReportEntry( NORMAL_RUN, 1L, getClass().getName(), null, TEST_NAME, null ); + reportEntry = new SimpleReportEntry(NORMAL_RUN, 1L, getClass().getName(), null, TEST_NAME, null); WrappedReportEntry wrappedReportEntry = - new WrappedReportEntry( reportEntry, ReportEntryType.SUCCESS, 12, null, null ); - reporter = new FileReporter( reportDir, suffixText, Charset.defaultCharset(), false, false, false ); - reporter.testSetCompleted( wrappedReportEntry, createTestSetStats(), new ArrayList() ); + new WrappedReportEntry(reportEntry, ReportEntryType.SUCCESS, 12, null, null); + reporter = new FileReporter(reportDir, suffixText, Charset.defaultCharset(), false, false, false); + reporter.testSetCompleted(wrappedReportEntry, createTestSetStats(), new ArrayList()); - File expectedReportFile = new File( reportDir, TEST_NAME + "-" + suffixText + ".txt" ); - assertTrue( "Report file (" + expectedReportFile.getAbsolutePath() + ") doesn't exist", - expectedReportFile.exists() ); + File expectedReportFile = new File(reportDir, TEST_NAME + "-" + suffixText + ".txt"); + assertTrue( + "Report file (" + expectedReportFile.getAbsolutePath() + ") doesn't exist", + expectedReportFile.exists()); //noinspection ResultOfMethodCallIgnored expectedReportFile.delete(); } diff --git a/maven-surefire-common/src/test/java/org/apache/maven/surefire/report/RunStatisticsTest.java b/maven-surefire-common/src/test/java/org/apache/maven/surefire/report/RunStatisticsTest.java index b05561a2a0..a3206e00a3 100644 --- a/maven-surefire-common/src/test/java/org/apache/maven/surefire/report/RunStatisticsTest.java +++ b/maven-surefire-common/src/test/java/org/apache/maven/surefire/report/RunStatisticsTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.report; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,23 +16,21 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.report; import junit.framework.TestCase; /** * */ -public class RunStatisticsTest - extends TestCase -{ - public void testSetRunStatistics() - { +public class RunStatisticsTest extends TestCase { + public void testSetRunStatistics() { RunStatistics statistics = new RunStatistics(); - statistics.set( 10, 5, 2, 1, 2 ); - assertEquals( 10, statistics.getCompletedCount() ); - assertEquals( 5, statistics.getErrors() ); - assertEquals( 2, statistics.getFailures() ); - assertEquals( 1, statistics.getSkipped() ); - assertEquals( 2, statistics.getFlakes() ); + statistics.set(10, 5, 2, 1, 2); + assertEquals(10, statistics.getCompletedCount()); + assertEquals(5, statistics.getErrors()); + assertEquals(2, statistics.getFailures()); + assertEquals(1, statistics.getSkipped()); + assertEquals(2, statistics.getFlakes()); } } diff --git a/maven-surefire-common/src/test/java/org/apache/maven/surefire/spi/CustomizedImpl.java b/maven-surefire-common/src/test/java/org/apache/maven/surefire/spi/CustomizedImpl.java index e2f654c3c8..b0e1b5025b 100644 --- a/maven-surefire-common/src/test/java/org/apache/maven/surefire/spi/CustomizedImpl.java +++ b/maven-surefire-common/src/test/java/org/apache/maven/surefire/spi/CustomizedImpl.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.spi; /* @@ -23,12 +41,9 @@ * @author Tibor Digana (tibor17) * @since 2.20 */ -public class CustomizedImpl - implements IDefault -{ +public class CustomizedImpl implements IDefault { @Override - public boolean isDefault() - { + public boolean isDefault() { return false; } } diff --git a/maven-surefire-common/src/test/java/org/apache/maven/surefire/spi/DefaultImpl.java b/maven-surefire-common/src/test/java/org/apache/maven/surefire/spi/DefaultImpl.java index 207f56261e..e7450fb9b8 100644 --- a/maven-surefire-common/src/test/java/org/apache/maven/surefire/spi/DefaultImpl.java +++ b/maven-surefire-common/src/test/java/org/apache/maven/surefire/spi/DefaultImpl.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.spi; /* @@ -23,12 +41,9 @@ * @author Tibor Digana (tibor17) * @since 2.20 */ -public class DefaultImpl - implements IDefault -{ +public class DefaultImpl implements IDefault { @Override - public boolean isDefault() - { + public boolean isDefault() { return true; } } diff --git a/maven-surefire-common/src/test/java/org/apache/maven/surefire/spi/EmptyServiceInterface.java b/maven-surefire-common/src/test/java/org/apache/maven/surefire/spi/EmptyServiceInterface.java index 30abd698ff..9493d56652 100644 --- a/maven-surefire-common/src/test/java/org/apache/maven/surefire/spi/EmptyServiceInterface.java +++ b/maven-surefire-common/src/test/java/org/apache/maven/surefire/spi/EmptyServiceInterface.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.spi; /* @@ -19,12 +37,10 @@ * under the License. */ - /** * @author Tibor Digana (tibor17) * @since 2.20 */ -public interface EmptyServiceInterface -{ +public interface EmptyServiceInterface { String whoAmI(); } diff --git a/maven-surefire-common/src/test/java/org/apache/maven/surefire/spi/ExistingServiceInterface.java b/maven-surefire-common/src/test/java/org/apache/maven/surefire/spi/ExistingServiceInterface.java index 45e3ab4f8c..8416e0d9c8 100644 --- a/maven-surefire-common/src/test/java/org/apache/maven/surefire/spi/ExistingServiceInterface.java +++ b/maven-surefire-common/src/test/java/org/apache/maven/surefire/spi/ExistingServiceInterface.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.spi; /* @@ -19,12 +37,10 @@ * under the License. */ - /** * @author Tibor Digana (tibor17) * @since 2.20 */ -public interface ExistingServiceInterface -{ +public interface ExistingServiceInterface { String whoAmI(); } diff --git a/maven-surefire-common/src/test/java/org/apache/maven/surefire/spi/IDefault.java b/maven-surefire-common/src/test/java/org/apache/maven/surefire/spi/IDefault.java index 740798de3d..c268590dc4 100644 --- a/maven-surefire-common/src/test/java/org/apache/maven/surefire/spi/IDefault.java +++ b/maven-surefire-common/src/test/java/org/apache/maven/surefire/spi/IDefault.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.spi; /* @@ -23,8 +41,7 @@ * @author Tibor Digana (tibor17) * @since 2.20 */ -public interface IDefault -{ +public interface IDefault { /** * @return {@code true} if SPI implementation vendor is maven-surefire-plugin or maven-failsafe-plugin. * {@code false} if customized by users. diff --git a/maven-surefire-common/src/test/java/org/apache/maven/surefire/spi/NoServiceInterface.java b/maven-surefire-common/src/test/java/org/apache/maven/surefire/spi/NoServiceInterface.java index e28a07c107..7358c94a82 100644 --- a/maven-surefire-common/src/test/java/org/apache/maven/surefire/spi/NoServiceInterface.java +++ b/maven-surefire-common/src/test/java/org/apache/maven/surefire/spi/NoServiceInterface.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.spi; /* @@ -19,12 +37,10 @@ * under the License. */ - /** * @author Tibor Digana (tibor17) * @since 2.20 */ -public interface NoServiceInterface -{ +public interface NoServiceInterface { void dummyService(); } diff --git a/maven-surefire-common/src/test/java/org/apache/maven/surefire/spi/SPITest.java b/maven-surefire-common/src/test/java/org/apache/maven/surefire/spi/SPITest.java index f6affc36cd..66ecea7ed9 100644 --- a/maven-surefire-common/src/test/java/org/apache/maven/surefire/spi/SPITest.java +++ b/maven-surefire-common/src/test/java/org/apache/maven/surefire/spi/SPITest.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.spi; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.spi; import java.io.IOException; @@ -31,45 +30,33 @@ * @author Tibor Digana (tibor17) * @since 2.20 */ -public class SPITest -{ +public class SPITest { private final ServiceLoader spi = new ServiceLoader(); private final ClassLoader ctx = currentThread().getContextClassLoader(); @Test - public void shouldNotLoadSpiDoesNotExist() throws IOException - { - assertThat( spi.lookup( NoServiceInterface.class, ctx ) ) - .isEmpty(); + public void shouldNotLoadSpiDoesNotExist() throws IOException { + assertThat(spi.lookup(NoServiceInterface.class, ctx)).isEmpty(); - assertThat( spi.load( NoServiceInterface.class, ctx ) ) - .isEmpty(); + assertThat(spi.load(NoServiceInterface.class, ctx)).isEmpty(); } @Test - public void shouldNotLoadEmptySpi() throws IOException - { - assertThat( spi.lookup( EmptyServiceInterface.class, ctx ) ) - .isEmpty(); + public void shouldNotLoadEmptySpi() throws IOException { + assertThat(spi.lookup(EmptyServiceInterface.class, ctx)).isEmpty(); - assertThat( spi.load( EmptyServiceInterface.class, ctx ) ) - .isEmpty(); + assertThat(spi.load(EmptyServiceInterface.class, ctx)).isEmpty(); } @Test - public void shouldLoad2SpiObjects() throws IOException - { - assertThat( spi.lookup( ExistingServiceInterface.class, ctx ) ) - .hasSize( 2 ); - - assertThat( spi.lookup( ExistingServiceInterface.class, ctx ) ) - .containsOnly( SPImpl1.class.getName(), SPImpl2.class.getName() ); + public void shouldLoad2SpiObjects() throws IOException { + assertThat(spi.lookup(ExistingServiceInterface.class, ctx)).hasSize(2); + assertThat(spi.lookup(ExistingServiceInterface.class, ctx)) + .containsOnly(SPImpl1.class.getName(), SPImpl2.class.getName()); - assertThat( spi.load( ExistingServiceInterface.class, ctx ) ) - .hasSize( 2 ); + assertThat(spi.load(ExistingServiceInterface.class, ctx)).hasSize(2); - assertThat( spi.load( ExistingServiceInterface.class, ctx ) ) - .contains( new SPImpl1(), new SPImpl2() ); + assertThat(spi.load(ExistingServiceInterface.class, ctx)).contains(new SPImpl1(), new SPImpl2()); } } diff --git a/maven-surefire-common/src/test/java/org/apache/maven/surefire/spi/SPImpl1.java b/maven-surefire-common/src/test/java/org/apache/maven/surefire/spi/SPImpl1.java index d9e6b4d228..e80e23637d 100644 --- a/maven-surefire-common/src/test/java/org/apache/maven/surefire/spi/SPImpl1.java +++ b/maven-surefire-common/src/test/java/org/apache/maven/surefire/spi/SPImpl1.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.spi; /* @@ -23,23 +41,19 @@ * @author Tibor Digana (tibor17) * @since 2.20 */ -public class SPImpl1 implements ExistingServiceInterface -{ +public class SPImpl1 implements ExistingServiceInterface { @Override - public String whoAmI() - { + public String whoAmI() { return SPImpl1.class.getSimpleName(); } @Override - public boolean equals( Object o ) - { + public boolean equals(Object o) { return this == o || getClass() == o.getClass(); } @Override - public int hashCode() - { + public int hashCode() { return whoAmI().hashCode(); } } diff --git a/maven-surefire-common/src/test/java/org/apache/maven/surefire/spi/SPImpl2.java b/maven-surefire-common/src/test/java/org/apache/maven/surefire/spi/SPImpl2.java index 9ecccef04f..2cd2edd4eb 100644 --- a/maven-surefire-common/src/test/java/org/apache/maven/surefire/spi/SPImpl2.java +++ b/maven-surefire-common/src/test/java/org/apache/maven/surefire/spi/SPImpl2.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.spi; /* @@ -23,23 +41,19 @@ * @author Tibor Digana (tibor17) * @since 2.20 */ -public class SPImpl2 implements ExistingServiceInterface -{ +public class SPImpl2 implements ExistingServiceInterface { @Override - public String whoAmI() - { + public String whoAmI() { return SPImpl2.class.getSimpleName(); } @Override - public boolean equals( Object o ) - { + public boolean equals(Object o) { return this == o || getClass() == o.getClass(); } @Override - public int hashCode() - { + public int hashCode() { return whoAmI().hashCode(); } } diff --git a/maven-surefire-common/src/test/java/org/apache/maven/surefire/stream/EventDecoderTest.java b/maven-surefire-common/src/test/java/org/apache/maven/surefire/stream/EventDecoderTest.java index efae6eea6a..a49d7c7397 100644 --- a/maven-surefire-common/src/test/java/org/apache/maven/surefire/stream/EventDecoderTest.java +++ b/maven-surefire-common/src/test/java/org/apache/maven/surefire/stream/EventDecoderTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.stream; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,14 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.stream; + +import javax.annotation.Nonnull; + +import java.io.File; +import java.nio.ByteBuffer; +import java.nio.channels.ReadableByteChannel; +import java.util.Map; import org.apache.maven.plugin.surefire.log.api.ConsoleLogger; import org.apache.maven.surefire.api.booter.ForkedProcessEventType; @@ -53,12 +59,6 @@ import org.apache.maven.surefire.api.stream.SegmentType; import org.junit.Test; -import javax.annotation.Nonnull; -import java.io.File; -import java.nio.ByteBuffer; -import java.nio.channels.ReadableByteChannel; -import java.util.Map; - import static java.lang.Math.min; import static java.nio.charset.StandardCharsets.US_ASCII; import static java.util.Arrays.asList; @@ -101,712 +101,940 @@ /** * */ -public class EventDecoderTest -{ +public class EventDecoderTest { @Test - public void shouldMapEventTypes() throws Exception - { - Map eventTypes = invokeMethod( EventDecoder.class, "segmentsToEvents" ); - assertThat( eventTypes ) - .hasSize( ForkedProcessEventType.values().length ); + public void shouldMapEventTypes() throws Exception { + Map eventTypes = invokeMethod(EventDecoder.class, "segmentsToEvents"); + assertThat(eventTypes).hasSize(ForkedProcessEventType.values().length); } @Test - public void shouldMapRunModes() throws Exception - { - Map map = invokeMethod( EventDecoder.class, "segmentsToRunModes" ); - - assertThat( map ) - .hasSize( 2 ); - - byte[] stream = "normal-run".getBytes( US_ASCII ); - Segment segment = new Segment( stream, 0, stream.length ); - assertThat( map.get( segment ) ) - .isEqualTo( NORMAL_RUN ); - - stream = "rerun-test-after-failure".getBytes( US_ASCII ); - segment = new Segment( stream, 0, stream.length ); - assertThat( map.get( segment ) ) - .isEqualTo( RERUN_TEST_AFTER_FAILURE ); + public void shouldMapRunModes() throws Exception { + Map map = invokeMethod(EventDecoder.class, "segmentsToRunModes"); + + assertThat(map).hasSize(2); + + byte[] stream = "normal-run".getBytes(US_ASCII); + Segment segment = new Segment(stream, 0, stream.length); + assertThat(map.get(segment)).isEqualTo(NORMAL_RUN); + + stream = "rerun-test-after-failure".getBytes(US_ASCII); + segment = new Segment(stream, 0, stream.length); + assertThat(map.get(segment)).isEqualTo(RERUN_TEST_AFTER_FAILURE); } @Test - public void shouldMapEventTypeToSegmentType() - { + public void shouldMapEventTypeToSegmentType() { byte[] stream = {}; - Channel channel = new Channel( stream, 1 ); - EventDecoder decoder = new EventDecoder( channel, new MockForkNodeArguments() ); - - SegmentType[] segmentTypes = decoder.nextSegmentType( BOOTERCODE_BYE ); - assertThat( segmentTypes ) - .hasSize( 1 ) - .containsOnly( END_OF_FRAME ); - - segmentTypes = decoder.nextSegmentType( BOOTERCODE_STOP_ON_NEXT_TEST ); - assertThat( segmentTypes ) - .hasSize( 1 ) - .containsOnly( END_OF_FRAME ); - - segmentTypes = decoder.nextSegmentType( BOOTERCODE_NEXT_TEST ); - assertThat( segmentTypes ) - .hasSize( 1 ) - .containsOnly( END_OF_FRAME ); - - segmentTypes = decoder.nextSegmentType( BOOTERCODE_CONSOLE_ERROR ); - assertThat( segmentTypes ) - .hasSize( 5 ) - .isEqualTo( new SegmentType[] { STRING_ENCODING, DATA_STRING, DATA_STRING, DATA_STRING, END_OF_FRAME } ); - - segmentTypes = decoder.nextSegmentType( ForkedProcessEventType.BOOTERCODE_JVM_EXIT_ERROR ); - assertThat( segmentTypes ) - .hasSize( 5 ) - .isEqualTo( new SegmentType[] { STRING_ENCODING, DATA_STRING, DATA_STRING, DATA_STRING, END_OF_FRAME } ); - - segmentTypes = decoder.nextSegmentType( BOOTERCODE_CONSOLE_INFO ); - assertThat( segmentTypes ) - .hasSize( 3 ) - .isEqualTo( new SegmentType[] { STRING_ENCODING, DATA_STRING, END_OF_FRAME } ); - - segmentTypes = decoder.nextSegmentType( ForkedProcessEventType.BOOTERCODE_CONSOLE_DEBUG ); - assertThat( segmentTypes ) - .hasSize( 3 ) - .isEqualTo( new SegmentType[] { STRING_ENCODING, DATA_STRING, END_OF_FRAME } ); - - segmentTypes = decoder.nextSegmentType( ForkedProcessEventType.BOOTERCODE_CONSOLE_WARNING ); - assertThat( segmentTypes ) - .hasSize( 3 ) - .isEqualTo( new SegmentType[] { STRING_ENCODING, DATA_STRING, END_OF_FRAME } ); - - segmentTypes = decoder.nextSegmentType( BOOTERCODE_STDOUT ); - assertThat( segmentTypes ) - .hasSize( 5 ) - .isEqualTo( new SegmentType[] { RUN_MODE, TEST_RUN_ID, STRING_ENCODING, DATA_STRING, END_OF_FRAME } ); - - segmentTypes = decoder.nextSegmentType( ForkedProcessEventType.BOOTERCODE_STDOUT_NEW_LINE ); - assertThat( segmentTypes ) - .hasSize( 5 ) - .isEqualTo( new SegmentType[] { RUN_MODE, TEST_RUN_ID, STRING_ENCODING, DATA_STRING, END_OF_FRAME } ); - - segmentTypes = decoder.nextSegmentType( ForkedProcessEventType.BOOTERCODE_STDERR ); - assertThat( segmentTypes ) - .hasSize( 5 ) - .isEqualTo( new SegmentType[] { RUN_MODE, TEST_RUN_ID, STRING_ENCODING, DATA_STRING, END_OF_FRAME } ); - - segmentTypes = decoder.nextSegmentType( ForkedProcessEventType.BOOTERCODE_STDERR_NEW_LINE ); - assertThat( segmentTypes ) - .hasSize( 5 ) - .isEqualTo( new SegmentType[] { RUN_MODE, TEST_RUN_ID, STRING_ENCODING, DATA_STRING, END_OF_FRAME } ); - - segmentTypes = decoder.nextSegmentType( BOOTERCODE_SYSPROPS ); - assertThat( segmentTypes ) - .hasSize( 6 ) - .isEqualTo( new SegmentType[] { RUN_MODE, TEST_RUN_ID, STRING_ENCODING, DATA_STRING, DATA_STRING, - END_OF_FRAME } ); - - segmentTypes = decoder.nextSegmentType( BOOTERCODE_TESTSET_STARTING ); - assertThat( segmentTypes ) - .hasSize( 14 ) - .isEqualTo( new SegmentType[] { - RUN_MODE, TEST_RUN_ID, STRING_ENCODING, DATA_STRING, DATA_STRING, DATA_STRING, DATA_STRING, DATA_STRING, - DATA_STRING, DATA_INTEGER, DATA_STRING, DATA_STRING, DATA_STRING, END_OF_FRAME } ); - - segmentTypes = decoder.nextSegmentType( ForkedProcessEventType.BOOTERCODE_TESTSET_COMPLETED ); - assertThat( segmentTypes ) - .hasSize( 14 ) - .isEqualTo( new SegmentType[] { RUN_MODE, TEST_RUN_ID, STRING_ENCODING, DATA_STRING, DATA_STRING, - DATA_STRING, DATA_STRING, DATA_STRING, DATA_STRING, DATA_INTEGER, DATA_STRING, DATA_STRING, DATA_STRING, - END_OF_FRAME } ); - - segmentTypes = decoder.nextSegmentType( ForkedProcessEventType.BOOTERCODE_TEST_STARTING ); - assertThat( segmentTypes ) - .hasSize( 14 ) - .isEqualTo( new SegmentType[] { RUN_MODE, TEST_RUN_ID, STRING_ENCODING, DATA_STRING, DATA_STRING, - DATA_STRING, DATA_STRING, DATA_STRING, DATA_STRING, DATA_INTEGER, DATA_STRING, DATA_STRING, DATA_STRING, - END_OF_FRAME } ); - - segmentTypes = decoder.nextSegmentType( BOOTERCODE_TEST_SUCCEEDED ); - assertThat( segmentTypes ) - .hasSize( 14 ) - .isEqualTo( new SegmentType[] { RUN_MODE, TEST_RUN_ID, STRING_ENCODING, DATA_STRING, DATA_STRING, - DATA_STRING, DATA_STRING, DATA_STRING, DATA_STRING, DATA_INTEGER, DATA_STRING, DATA_STRING, DATA_STRING, - END_OF_FRAME } ); - - segmentTypes = decoder.nextSegmentType( BOOTERCODE_TEST_FAILED ); - assertThat( segmentTypes ) - .hasSize( 14 ) - .isEqualTo( new SegmentType[] { RUN_MODE, TEST_RUN_ID, STRING_ENCODING, DATA_STRING, DATA_STRING, - DATA_STRING, DATA_STRING, DATA_STRING, DATA_STRING, DATA_INTEGER, DATA_STRING, DATA_STRING, DATA_STRING, - END_OF_FRAME } ); - - segmentTypes = decoder.nextSegmentType( ForkedProcessEventType.BOOTERCODE_TEST_SKIPPED ); - assertThat( segmentTypes ) - .hasSize( 14 ) - .isEqualTo( new SegmentType[] { RUN_MODE, TEST_RUN_ID, STRING_ENCODING, DATA_STRING, DATA_STRING, - DATA_STRING, DATA_STRING, DATA_STRING, DATA_STRING, DATA_INTEGER, DATA_STRING, DATA_STRING, DATA_STRING, - END_OF_FRAME } ); - - segmentTypes = decoder.nextSegmentType( ForkedProcessEventType.BOOTERCODE_TEST_ERROR ); - assertThat( segmentTypes ) - .hasSize( 14 ) - .isEqualTo( new SegmentType[] { RUN_MODE, TEST_RUN_ID, STRING_ENCODING, DATA_STRING, DATA_STRING, - DATA_STRING, DATA_STRING, DATA_STRING, DATA_STRING, DATA_INTEGER, DATA_STRING, DATA_STRING, DATA_STRING, - END_OF_FRAME } ); - - segmentTypes = decoder.nextSegmentType( ForkedProcessEventType.BOOTERCODE_TEST_ASSUMPTIONFAILURE ); - assertThat( segmentTypes ) - .hasSize( 14 ) - .isEqualTo( new SegmentType[] { RUN_MODE, TEST_RUN_ID, STRING_ENCODING, DATA_STRING, DATA_STRING, - DATA_STRING, DATA_STRING, DATA_STRING, DATA_STRING, DATA_INTEGER, DATA_STRING, DATA_STRING, DATA_STRING, - END_OF_FRAME } ); + Channel channel = new Channel(stream, 1); + EventDecoder decoder = new EventDecoder(channel, new MockForkNodeArguments()); + + SegmentType[] segmentTypes = decoder.nextSegmentType(BOOTERCODE_BYE); + assertThat(segmentTypes).hasSize(1).containsOnly(END_OF_FRAME); + + segmentTypes = decoder.nextSegmentType(BOOTERCODE_STOP_ON_NEXT_TEST); + assertThat(segmentTypes).hasSize(1).containsOnly(END_OF_FRAME); + + segmentTypes = decoder.nextSegmentType(BOOTERCODE_NEXT_TEST); + assertThat(segmentTypes).hasSize(1).containsOnly(END_OF_FRAME); + + segmentTypes = decoder.nextSegmentType(BOOTERCODE_CONSOLE_ERROR); + assertThat(segmentTypes) + .hasSize(5) + .isEqualTo(new SegmentType[] {STRING_ENCODING, DATA_STRING, DATA_STRING, DATA_STRING, END_OF_FRAME}); + + segmentTypes = decoder.nextSegmentType(ForkedProcessEventType.BOOTERCODE_JVM_EXIT_ERROR); + assertThat(segmentTypes) + .hasSize(5) + .isEqualTo(new SegmentType[] {STRING_ENCODING, DATA_STRING, DATA_STRING, DATA_STRING, END_OF_FRAME}); + + segmentTypes = decoder.nextSegmentType(BOOTERCODE_CONSOLE_INFO); + assertThat(segmentTypes).hasSize(3).isEqualTo(new SegmentType[] {STRING_ENCODING, DATA_STRING, END_OF_FRAME}); + + segmentTypes = decoder.nextSegmentType(ForkedProcessEventType.BOOTERCODE_CONSOLE_DEBUG); + assertThat(segmentTypes).hasSize(3).isEqualTo(new SegmentType[] {STRING_ENCODING, DATA_STRING, END_OF_FRAME}); + + segmentTypes = decoder.nextSegmentType(ForkedProcessEventType.BOOTERCODE_CONSOLE_WARNING); + assertThat(segmentTypes).hasSize(3).isEqualTo(new SegmentType[] {STRING_ENCODING, DATA_STRING, END_OF_FRAME}); + + segmentTypes = decoder.nextSegmentType(BOOTERCODE_STDOUT); + assertThat(segmentTypes) + .hasSize(5) + .isEqualTo(new SegmentType[] {RUN_MODE, TEST_RUN_ID, STRING_ENCODING, DATA_STRING, END_OF_FRAME}); + + segmentTypes = decoder.nextSegmentType(ForkedProcessEventType.BOOTERCODE_STDOUT_NEW_LINE); + assertThat(segmentTypes) + .hasSize(5) + .isEqualTo(new SegmentType[] {RUN_MODE, TEST_RUN_ID, STRING_ENCODING, DATA_STRING, END_OF_FRAME}); + + segmentTypes = decoder.nextSegmentType(ForkedProcessEventType.BOOTERCODE_STDERR); + assertThat(segmentTypes) + .hasSize(5) + .isEqualTo(new SegmentType[] {RUN_MODE, TEST_RUN_ID, STRING_ENCODING, DATA_STRING, END_OF_FRAME}); + + segmentTypes = decoder.nextSegmentType(ForkedProcessEventType.BOOTERCODE_STDERR_NEW_LINE); + assertThat(segmentTypes) + .hasSize(5) + .isEqualTo(new SegmentType[] {RUN_MODE, TEST_RUN_ID, STRING_ENCODING, DATA_STRING, END_OF_FRAME}); + + segmentTypes = decoder.nextSegmentType(BOOTERCODE_SYSPROPS); + assertThat(segmentTypes).hasSize(6).isEqualTo(new SegmentType[] { + RUN_MODE, TEST_RUN_ID, STRING_ENCODING, DATA_STRING, DATA_STRING, END_OF_FRAME + }); + + segmentTypes = decoder.nextSegmentType(BOOTERCODE_TESTSET_STARTING); + assertThat(segmentTypes).hasSize(14).isEqualTo(new SegmentType[] { + RUN_MODE, + TEST_RUN_ID, + STRING_ENCODING, + DATA_STRING, + DATA_STRING, + DATA_STRING, + DATA_STRING, + DATA_STRING, + DATA_STRING, + DATA_INTEGER, + DATA_STRING, + DATA_STRING, + DATA_STRING, + END_OF_FRAME + }); + + segmentTypes = decoder.nextSegmentType(ForkedProcessEventType.BOOTERCODE_TESTSET_COMPLETED); + assertThat(segmentTypes).hasSize(14).isEqualTo(new SegmentType[] { + RUN_MODE, + TEST_RUN_ID, + STRING_ENCODING, + DATA_STRING, + DATA_STRING, + DATA_STRING, + DATA_STRING, + DATA_STRING, + DATA_STRING, + DATA_INTEGER, + DATA_STRING, + DATA_STRING, + DATA_STRING, + END_OF_FRAME + }); + + segmentTypes = decoder.nextSegmentType(ForkedProcessEventType.BOOTERCODE_TEST_STARTING); + assertThat(segmentTypes).hasSize(14).isEqualTo(new SegmentType[] { + RUN_MODE, + TEST_RUN_ID, + STRING_ENCODING, + DATA_STRING, + DATA_STRING, + DATA_STRING, + DATA_STRING, + DATA_STRING, + DATA_STRING, + DATA_INTEGER, + DATA_STRING, + DATA_STRING, + DATA_STRING, + END_OF_FRAME + }); + + segmentTypes = decoder.nextSegmentType(BOOTERCODE_TEST_SUCCEEDED); + assertThat(segmentTypes).hasSize(14).isEqualTo(new SegmentType[] { + RUN_MODE, + TEST_RUN_ID, + STRING_ENCODING, + DATA_STRING, + DATA_STRING, + DATA_STRING, + DATA_STRING, + DATA_STRING, + DATA_STRING, + DATA_INTEGER, + DATA_STRING, + DATA_STRING, + DATA_STRING, + END_OF_FRAME + }); + + segmentTypes = decoder.nextSegmentType(BOOTERCODE_TEST_FAILED); + assertThat(segmentTypes).hasSize(14).isEqualTo(new SegmentType[] { + RUN_MODE, + TEST_RUN_ID, + STRING_ENCODING, + DATA_STRING, + DATA_STRING, + DATA_STRING, + DATA_STRING, + DATA_STRING, + DATA_STRING, + DATA_INTEGER, + DATA_STRING, + DATA_STRING, + DATA_STRING, + END_OF_FRAME + }); + + segmentTypes = decoder.nextSegmentType(ForkedProcessEventType.BOOTERCODE_TEST_SKIPPED); + assertThat(segmentTypes).hasSize(14).isEqualTo(new SegmentType[] { + RUN_MODE, + TEST_RUN_ID, + STRING_ENCODING, + DATA_STRING, + DATA_STRING, + DATA_STRING, + DATA_STRING, + DATA_STRING, + DATA_STRING, + DATA_INTEGER, + DATA_STRING, + DATA_STRING, + DATA_STRING, + END_OF_FRAME + }); + + segmentTypes = decoder.nextSegmentType(ForkedProcessEventType.BOOTERCODE_TEST_ERROR); + assertThat(segmentTypes).hasSize(14).isEqualTo(new SegmentType[] { + RUN_MODE, + TEST_RUN_ID, + STRING_ENCODING, + DATA_STRING, + DATA_STRING, + DATA_STRING, + DATA_STRING, + DATA_STRING, + DATA_STRING, + DATA_INTEGER, + DATA_STRING, + DATA_STRING, + DATA_STRING, + END_OF_FRAME + }); + + segmentTypes = decoder.nextSegmentType(ForkedProcessEventType.BOOTERCODE_TEST_ASSUMPTIONFAILURE); + assertThat(segmentTypes).hasSize(14).isEqualTo(new SegmentType[] { + RUN_MODE, + TEST_RUN_ID, + STRING_ENCODING, + DATA_STRING, + DATA_STRING, + DATA_STRING, + DATA_STRING, + DATA_STRING, + DATA_STRING, + DATA_INTEGER, + DATA_STRING, + DATA_STRING, + DATA_STRING, + END_OF_FRAME + }); } @Test - public void shouldCreateEvent() throws Exception - { + public void shouldCreateEvent() throws Exception { byte[] stream = {}; - Channel channel = new Channel( stream, 1 ); - EventDecoder decoder = new EventDecoder( channel, new MockForkNodeArguments() ); + Channel channel = new Channel(stream, 1); + EventDecoder decoder = new EventDecoder(channel, new MockForkNodeArguments()); - Event event = decoder.toMessage( BOOTERCODE_BYE, decoder.new Memento() ); - assertThat( event ) - .isInstanceOf( ControlByeEvent.class ); + Event event = decoder.toMessage(BOOTERCODE_BYE, decoder.new Memento()); + assertThat(event).isInstanceOf(ControlByeEvent.class); - event = decoder.toMessage( BOOTERCODE_STOP_ON_NEXT_TEST, decoder.new Memento() ); - assertThat( event ) - .isInstanceOf( ControlStopOnNextTestEvent.class ); + event = decoder.toMessage(BOOTERCODE_STOP_ON_NEXT_TEST, decoder.new Memento()); + assertThat(event).isInstanceOf(ControlStopOnNextTestEvent.class); - event = decoder.toMessage( BOOTERCODE_NEXT_TEST, decoder.new Memento() ); - assertThat( event ) - .isInstanceOf( ControlNextTestEvent.class ); + event = decoder.toMessage(BOOTERCODE_NEXT_TEST, decoder.new Memento()); + assertThat(event).isInstanceOf(ControlNextTestEvent.class); Memento memento = decoder.new Memento(); - memento.getData().addAll( asList( "1", "2", "3" ) ); - event = decoder.toMessage( BOOTERCODE_CONSOLE_ERROR, memento ); - assertThat( event ) - .isInstanceOf( ConsoleErrorEvent.class ); + memento.getData().addAll(asList("1", "2", "3")); + event = decoder.toMessage(BOOTERCODE_CONSOLE_ERROR, memento); + assertThat(event).isInstanceOf(ConsoleErrorEvent.class); ConsoleErrorEvent consoleErrorEvent = (ConsoleErrorEvent) event; - assertThat( consoleErrorEvent.getStackTraceWriter().getThrowable().getLocalizedMessage() ) - .isEqualTo( "1" ); - assertThat( consoleErrorEvent.getStackTraceWriter().smartTrimmedStackTrace() ) - .isEqualTo( "2" ); - assertThat( consoleErrorEvent.getStackTraceWriter().writeTraceToString() ) - .isEqualTo( "3" ); + assertThat(consoleErrorEvent.getStackTraceWriter().getThrowable().getLocalizedMessage()) + .isEqualTo("1"); + assertThat(consoleErrorEvent.getStackTraceWriter().smartTrimmedStackTrace()) + .isEqualTo("2"); + assertThat(consoleErrorEvent.getStackTraceWriter().writeTraceToString()).isEqualTo("3"); memento = decoder.new Memento(); - memento.getData().addAll( asList( null, null, null ) ); - event = decoder.toMessage( BOOTERCODE_CONSOLE_ERROR, memento ); - assertThat( event ) - .isInstanceOf( ConsoleErrorEvent.class ); + memento.getData().addAll(asList(null, null, null)); + event = decoder.toMessage(BOOTERCODE_CONSOLE_ERROR, memento); + assertThat(event).isInstanceOf(ConsoleErrorEvent.class); consoleErrorEvent = (ConsoleErrorEvent) event; - assertThat( consoleErrorEvent.getStackTraceWriter() ) - .isNull(); + assertThat(consoleErrorEvent.getStackTraceWriter()).isNull(); memento = decoder.new Memento(); - memento.getData().addAll( asList( "1", "2", "3" ) ); - event = decoder.toMessage( BOOTERCODE_JVM_EXIT_ERROR, memento ); - assertThat( event ) - .isInstanceOf( JvmExitErrorEvent.class ); + memento.getData().addAll(asList("1", "2", "3")); + event = decoder.toMessage(BOOTERCODE_JVM_EXIT_ERROR, memento); + assertThat(event).isInstanceOf(JvmExitErrorEvent.class); JvmExitErrorEvent jvmExitErrorEvent = (JvmExitErrorEvent) event; - assertThat( jvmExitErrorEvent.getStackTraceWriter().getThrowable().getLocalizedMessage() ) - .isEqualTo( "1" ); - assertThat( jvmExitErrorEvent.getStackTraceWriter().smartTrimmedStackTrace() ) - .isEqualTo( "2" ); - assertThat( jvmExitErrorEvent.getStackTraceWriter().writeTraceToString() ) - .isEqualTo( "3" ); + assertThat(jvmExitErrorEvent.getStackTraceWriter().getThrowable().getLocalizedMessage()) + .isEqualTo("1"); + assertThat(jvmExitErrorEvent.getStackTraceWriter().smartTrimmedStackTrace()) + .isEqualTo("2"); + assertThat(jvmExitErrorEvent.getStackTraceWriter().writeTraceToString()).isEqualTo("3"); memento = decoder.new Memento(); - memento.getData().addAll( asList( null, null, null ) ); - event = decoder.toMessage( BOOTERCODE_JVM_EXIT_ERROR, memento ); - assertThat( event ) - .isInstanceOf( JvmExitErrorEvent.class ); + memento.getData().addAll(asList(null, null, null)); + event = decoder.toMessage(BOOTERCODE_JVM_EXIT_ERROR, memento); + assertThat(event).isInstanceOf(JvmExitErrorEvent.class); jvmExitErrorEvent = (JvmExitErrorEvent) event; - assertThat( jvmExitErrorEvent.getStackTraceWriter() ) - .isNull(); + assertThat(jvmExitErrorEvent.getStackTraceWriter()).isNull(); memento = decoder.new Memento(); - memento.getData().addAll( singletonList( "m" ) ); - event = decoder.toMessage( BOOTERCODE_CONSOLE_INFO, memento ); - assertThat( event ).isInstanceOf( ConsoleInfoEvent.class ); - assertThat( ( (ConsoleInfoEvent) event ).getMessage() ).isEqualTo( "m" ); + memento.getData().addAll(singletonList("m")); + event = decoder.toMessage(BOOTERCODE_CONSOLE_INFO, memento); + assertThat(event).isInstanceOf(ConsoleInfoEvent.class); + assertThat(((ConsoleInfoEvent) event).getMessage()).isEqualTo("m"); memento = decoder.new Memento(); - memento.getData().addAll( singletonList( "" ) ); - event = decoder.toMessage( BOOTERCODE_CONSOLE_WARNING, memento ); - assertThat( event ).isInstanceOf( ConsoleWarningEvent.class ); - assertThat( ( (ConsoleWarningEvent) event ).getMessage() ).isEmpty(); + memento.getData().addAll(singletonList("")); + event = decoder.toMessage(BOOTERCODE_CONSOLE_WARNING, memento); + assertThat(event).isInstanceOf(ConsoleWarningEvent.class); + assertThat(((ConsoleWarningEvent) event).getMessage()).isEmpty(); memento = decoder.new Memento(); - memento.getData().addAll( singletonList( null ) ); - event = decoder.toMessage( BOOTERCODE_CONSOLE_DEBUG, memento ); - assertThat( event ).isInstanceOf( ConsoleDebugEvent.class ); - assertThat( ( (ConsoleDebugEvent) event ).getMessage() ).isNull(); + memento.getData().addAll(singletonList(null)); + event = decoder.toMessage(BOOTERCODE_CONSOLE_DEBUG, memento); + assertThat(event).isInstanceOf(ConsoleDebugEvent.class); + assertThat(((ConsoleDebugEvent) event).getMessage()).isNull(); memento = decoder.new Memento(); - memento.getData().addAll( asList( NORMAL_RUN, 1L, "m" ) ); - event = decoder.toMessage( BOOTERCODE_STDOUT, memento ); - assertThat( event ).isInstanceOf( StandardStreamOutEvent.class ); - assertThat( ( (StandardStreamOutEvent) event ).getMessage() ).isEqualTo( "m" ); - assertThat( ( (StandardStreamOutEvent) event ).getRunMode() ).isEqualTo( NORMAL_RUN ); - assertThat( ( (StandardStreamOutEvent) event ).getTestRunId() ).isEqualTo( 1L ); + memento.getData().addAll(asList(NORMAL_RUN, 1L, "m")); + event = decoder.toMessage(BOOTERCODE_STDOUT, memento); + assertThat(event).isInstanceOf(StandardStreamOutEvent.class); + assertThat(((StandardStreamOutEvent) event).getMessage()).isEqualTo("m"); + assertThat(((StandardStreamOutEvent) event).getRunMode()).isEqualTo(NORMAL_RUN); + assertThat(((StandardStreamOutEvent) event).getTestRunId()).isEqualTo(1L); memento = decoder.new Memento(); - memento.getData().addAll( asList( RERUN_TEST_AFTER_FAILURE, 1L, null ) ); - event = decoder.toMessage( BOOTERCODE_STDOUT_NEW_LINE, memento ); - assertThat( event ).isInstanceOf( StandardStreamOutWithNewLineEvent.class ); - assertThat( ( (StandardStreamOutWithNewLineEvent) event ).getMessage() ).isNull(); - assertThat( ( (StandardStreamOutWithNewLineEvent) event ).getRunMode() ).isEqualTo( RERUN_TEST_AFTER_FAILURE ); - assertThat( ( (StandardStreamOutWithNewLineEvent) event ).getTestRunId() ).isEqualTo( 1L ); + memento.getData().addAll(asList(RERUN_TEST_AFTER_FAILURE, 1L, null)); + event = decoder.toMessage(BOOTERCODE_STDOUT_NEW_LINE, memento); + assertThat(event).isInstanceOf(StandardStreamOutWithNewLineEvent.class); + assertThat(((StandardStreamOutWithNewLineEvent) event).getMessage()).isNull(); + assertThat(((StandardStreamOutWithNewLineEvent) event).getRunMode()).isEqualTo(RERUN_TEST_AFTER_FAILURE); + assertThat(((StandardStreamOutWithNewLineEvent) event).getTestRunId()).isEqualTo(1L); memento = decoder.new Memento(); - memento.getData().addAll( asList( RERUN_TEST_AFTER_FAILURE, 1L, null ) ); - event = decoder.toMessage( BOOTERCODE_STDERR, memento ); - assertThat( event ).isInstanceOf( StandardStreamErrEvent.class ); - assertThat( ( (StandardStreamErrEvent) event ).getMessage() ).isNull(); - assertThat( ( (StandardStreamErrEvent) event ).getRunMode() ).isEqualTo( RERUN_TEST_AFTER_FAILURE ); - assertThat( ( (StandardStreamErrEvent) event ).getTestRunId() ).isEqualTo( 1L ); + memento.getData().addAll(asList(RERUN_TEST_AFTER_FAILURE, 1L, null)); + event = decoder.toMessage(BOOTERCODE_STDERR, memento); + assertThat(event).isInstanceOf(StandardStreamErrEvent.class); + assertThat(((StandardStreamErrEvent) event).getMessage()).isNull(); + assertThat(((StandardStreamErrEvent) event).getRunMode()).isEqualTo(RERUN_TEST_AFTER_FAILURE); + assertThat(((StandardStreamErrEvent) event).getTestRunId()).isEqualTo(1L); memento = decoder.new Memento(); - memento.getData().addAll( asList( NORMAL_RUN, 1L, "abc" ) ); - event = decoder.toMessage( BOOTERCODE_STDERR_NEW_LINE, memento ); - assertThat( event ).isInstanceOf( StandardStreamErrWithNewLineEvent.class ); - assertThat( ( (StandardStreamErrWithNewLineEvent) event ).getMessage() ).isEqualTo( "abc" ); - assertThat( ( (StandardStreamErrWithNewLineEvent) event ).getRunMode() ).isEqualTo( NORMAL_RUN ); - assertThat( ( (StandardStreamErrWithNewLineEvent) event ).getTestRunId() ).isEqualTo( 1L ); + memento.getData().addAll(asList(NORMAL_RUN, 1L, "abc")); + event = decoder.toMessage(BOOTERCODE_STDERR_NEW_LINE, memento); + assertThat(event).isInstanceOf(StandardStreamErrWithNewLineEvent.class); + assertThat(((StandardStreamErrWithNewLineEvent) event).getMessage()).isEqualTo("abc"); + assertThat(((StandardStreamErrWithNewLineEvent) event).getRunMode()).isEqualTo(NORMAL_RUN); + assertThat(((StandardStreamErrWithNewLineEvent) event).getTestRunId()).isEqualTo(1L); memento = decoder.new Memento(); - memento.getData().addAll( asList( NORMAL_RUN, 1L, "key", "value" ) ); - event = decoder.toMessage( BOOTERCODE_SYSPROPS, memento ); - assertThat( event ).isInstanceOf( SystemPropertyEvent.class ); - assertThat( ( (SystemPropertyEvent) event ).getRunMode() ).isEqualTo( NORMAL_RUN ); - assertThat( ( (SystemPropertyEvent) event ).getTestRunId() ).isEqualTo( 1L ); - assertThat( ( (SystemPropertyEvent) event ).getKey() ).isEqualTo( "key" ); - assertThat( ( (SystemPropertyEvent) event ).getValue() ).isEqualTo( "value" ); + memento.getData().addAll(asList(NORMAL_RUN, 1L, "key", "value")); + event = decoder.toMessage(BOOTERCODE_SYSPROPS, memento); + assertThat(event).isInstanceOf(SystemPropertyEvent.class); + assertThat(((SystemPropertyEvent) event).getRunMode()).isEqualTo(NORMAL_RUN); + assertThat(((SystemPropertyEvent) event).getTestRunId()).isEqualTo(1L); + assertThat(((SystemPropertyEvent) event).getKey()).isEqualTo("key"); + assertThat(((SystemPropertyEvent) event).getValue()).isEqualTo("value"); memento = decoder.new Memento(); - memento.getData().addAll( asList( NORMAL_RUN , 1L, "source", "sourceText", "name", "nameText", "group", - "message", 5, "traceMessage", "smartTrimmedStackTrace", "stackTrace" ) ); - event = decoder.toMessage( BOOTERCODE_TESTSET_STARTING, memento ); - assertThat( event ).isInstanceOf( TestsetStartingEvent.class ); - assertThat( ( (TestsetStartingEvent) event ).getReportEntry().getRunMode() ).isEqualTo( NORMAL_RUN ); - assertThat( ( (TestsetStartingEvent) event ).getReportEntry().getTestRunId() ).isEqualTo( 1L ); - assertThat( ( (TestsetStartingEvent) event ).getReportEntry().getSourceName() ).isEqualTo( "source" ); - assertThat( ( (TestsetStartingEvent) event ).getReportEntry().getSourceText() ).isEqualTo( "sourceText" ); - assertThat( ( (TestsetStartingEvent) event ).getReportEntry().getName() ).isEqualTo( "name" ); - assertThat( ( (TestsetStartingEvent) event ).getReportEntry().getNameText() ).isEqualTo( "nameText" ); - assertThat( ( (TestsetStartingEvent) event ).getReportEntry().getGroup() ).isEqualTo( "group" ); - assertThat( ( (TestsetStartingEvent) event ).getReportEntry().getMessage() ).isEqualTo( "message" ); - assertThat( ( (TestsetStartingEvent) event ).getReportEntry().getElapsed() ).isEqualTo( 5 ); - assertThat( ( (TestsetStartingEvent) event ) - .getReportEntry().getStackTraceWriter().getThrowable().getLocalizedMessage() ) - .isEqualTo( "traceMessage" ); - assertThat( ( (TestsetStartingEvent) event ).getReportEntry().getStackTraceWriter().smartTrimmedStackTrace() ) - .isEqualTo( "smartTrimmedStackTrace" ); - assertThat( ( (TestsetStartingEvent) event ).getReportEntry().getStackTraceWriter().writeTraceToString() ) - .isEqualTo( "stackTrace" ); + memento.getData() + .addAll(asList( + NORMAL_RUN, + 1L, + "source", + "sourceText", + "name", + "nameText", + "group", + "message", + 5, + "traceMessage", + "smartTrimmedStackTrace", + "stackTrace")); + event = decoder.toMessage(BOOTERCODE_TESTSET_STARTING, memento); + assertThat(event).isInstanceOf(TestsetStartingEvent.class); + assertThat(((TestsetStartingEvent) event).getReportEntry().getRunMode()).isEqualTo(NORMAL_RUN); + assertThat(((TestsetStartingEvent) event).getReportEntry().getTestRunId()) + .isEqualTo(1L); + assertThat(((TestsetStartingEvent) event).getReportEntry().getSourceName()) + .isEqualTo("source"); + assertThat(((TestsetStartingEvent) event).getReportEntry().getSourceText()) + .isEqualTo("sourceText"); + assertThat(((TestsetStartingEvent) event).getReportEntry().getName()).isEqualTo("name"); + assertThat(((TestsetStartingEvent) event).getReportEntry().getNameText()) + .isEqualTo("nameText"); + assertThat(((TestsetStartingEvent) event).getReportEntry().getGroup()).isEqualTo("group"); + assertThat(((TestsetStartingEvent) event).getReportEntry().getMessage()).isEqualTo("message"); + assertThat(((TestsetStartingEvent) event).getReportEntry().getElapsed()).isEqualTo(5); + assertThat(((TestsetStartingEvent) event) + .getReportEntry() + .getStackTraceWriter() + .getThrowable() + .getLocalizedMessage()) + .isEqualTo("traceMessage"); + assertThat(((TestsetStartingEvent) event) + .getReportEntry() + .getStackTraceWriter() + .smartTrimmedStackTrace()) + .isEqualTo("smartTrimmedStackTrace"); + assertThat(((TestsetStartingEvent) event) + .getReportEntry() + .getStackTraceWriter() + .writeTraceToString()) + .isEqualTo("stackTrace"); memento = decoder.new Memento(); - memento.getData().addAll( asList( NORMAL_RUN, 1L, "source", "sourceText", "name", "nameText", "group", null, 5, - "traceMessage", "smartTrimmedStackTrace", "stackTrace" ) ); - event = decoder.toMessage( BOOTERCODE_TESTSET_COMPLETED, memento ); - assertThat( event ).isInstanceOf( TestsetCompletedEvent.class ); - assertThat( ( (TestsetCompletedEvent) event ).getReportEntry().getRunMode() ).isEqualTo( NORMAL_RUN ); - assertThat( ( (TestsetCompletedEvent) event ).getReportEntry().getTestRunId() ).isEqualTo( 1L ); - assertThat( ( (TestsetCompletedEvent) event ).getReportEntry().getSourceName() ).isEqualTo( "source" ); - assertThat( ( (TestsetCompletedEvent) event ).getReportEntry().getSourceText() ).isEqualTo( "sourceText" ); - assertThat( ( (TestsetCompletedEvent) event ).getReportEntry().getName() ).isEqualTo( "name" ); - assertThat( ( (TestsetCompletedEvent) event ).getReportEntry().getNameText() ).isEqualTo( "nameText" ); - assertThat( ( (TestsetCompletedEvent) event ).getReportEntry().getGroup() ).isEqualTo( "group" ); - assertThat( ( (TestsetCompletedEvent) event ).getReportEntry().getMessage() ).isNull(); - assertThat( ( (TestsetCompletedEvent) event ).getReportEntry().getElapsed() ).isEqualTo( 5 ); - assertThat( ( (TestsetCompletedEvent) event ) - .getReportEntry().getStackTraceWriter().getThrowable().getLocalizedMessage() ) - .isEqualTo( "traceMessage" ); - assertThat( ( (TestsetCompletedEvent) event ).getReportEntry().getStackTraceWriter().smartTrimmedStackTrace() ) - .isEqualTo( "smartTrimmedStackTrace" ); - assertThat( ( (TestsetCompletedEvent) event ).getReportEntry().getStackTraceWriter().writeTraceToString() ) - .isEqualTo( "stackTrace" ); + memento.getData() + .addAll(asList( + NORMAL_RUN, + 1L, + "source", + "sourceText", + "name", + "nameText", + "group", + null, + 5, + "traceMessage", + "smartTrimmedStackTrace", + "stackTrace")); + event = decoder.toMessage(BOOTERCODE_TESTSET_COMPLETED, memento); + assertThat(event).isInstanceOf(TestsetCompletedEvent.class); + assertThat(((TestsetCompletedEvent) event).getReportEntry().getRunMode()) + .isEqualTo(NORMAL_RUN); + assertThat(((TestsetCompletedEvent) event).getReportEntry().getTestRunId()) + .isEqualTo(1L); + assertThat(((TestsetCompletedEvent) event).getReportEntry().getSourceName()) + .isEqualTo("source"); + assertThat(((TestsetCompletedEvent) event).getReportEntry().getSourceText()) + .isEqualTo("sourceText"); + assertThat(((TestsetCompletedEvent) event).getReportEntry().getName()).isEqualTo("name"); + assertThat(((TestsetCompletedEvent) event).getReportEntry().getNameText()) + .isEqualTo("nameText"); + assertThat(((TestsetCompletedEvent) event).getReportEntry().getGroup()).isEqualTo("group"); + assertThat(((TestsetCompletedEvent) event).getReportEntry().getMessage()) + .isNull(); + assertThat(((TestsetCompletedEvent) event).getReportEntry().getElapsed()) + .isEqualTo(5); + assertThat(((TestsetCompletedEvent) event) + .getReportEntry() + .getStackTraceWriter() + .getThrowable() + .getLocalizedMessage()) + .isEqualTo("traceMessage"); + assertThat(((TestsetCompletedEvent) event) + .getReportEntry() + .getStackTraceWriter() + .smartTrimmedStackTrace()) + .isEqualTo("smartTrimmedStackTrace"); + assertThat(((TestsetCompletedEvent) event) + .getReportEntry() + .getStackTraceWriter() + .writeTraceToString()) + .isEqualTo("stackTrace"); memento = decoder.new Memento(); - memento.getData().addAll( asList( NORMAL_RUN, 1L, "source", "sourceText", "name", "nameText", "group", - "message", 5, null, "smartTrimmedStackTrace", "stackTrace" ) ); - event = decoder.toMessage( BOOTERCODE_TEST_STARTING, memento ); - assertThat( event ).isInstanceOf( TestStartingEvent.class ); - assertThat( ( (TestStartingEvent) event ).getReportEntry().getRunMode() ).isEqualTo( NORMAL_RUN ); - assertThat( ( (TestStartingEvent) event ).getReportEntry().getTestRunId() ).isEqualTo( 1L ); - assertThat( ( (TestStartingEvent) event ).getReportEntry().getSourceName() ).isEqualTo( "source" ); - assertThat( ( (TestStartingEvent) event ).getReportEntry().getSourceText() ).isEqualTo( "sourceText" ); - assertThat( ( (TestStartingEvent) event ).getReportEntry().getName() ).isEqualTo( "name" ); - assertThat( ( (TestStartingEvent) event ).getReportEntry().getNameText() ).isEqualTo( "nameText" ); - assertThat( ( (TestStartingEvent) event ).getReportEntry().getGroup() ).isEqualTo( "group" ); - assertThat( ( (TestStartingEvent) event ).getReportEntry().getMessage() ).isEqualTo( "message" ); - assertThat( ( (TestStartingEvent) event ).getReportEntry().getElapsed() ).isEqualTo( 5 ); - assertThat( ( (TestStartingEvent) event ) - .getReportEntry().getStackTraceWriter().getThrowable().getLocalizedMessage() ) - .isNull(); - assertThat( ( (TestStartingEvent) event ).getReportEntry().getStackTraceWriter().smartTrimmedStackTrace() ) - .isEqualTo( "smartTrimmedStackTrace" ); - assertThat( ( (TestStartingEvent) event ).getReportEntry().getStackTraceWriter().writeTraceToString() ) - .isEqualTo( "stackTrace" ); + memento.getData() + .addAll(asList( + NORMAL_RUN, + 1L, + "source", + "sourceText", + "name", + "nameText", + "group", + "message", + 5, + null, + "smartTrimmedStackTrace", + "stackTrace")); + event = decoder.toMessage(BOOTERCODE_TEST_STARTING, memento); + assertThat(event).isInstanceOf(TestStartingEvent.class); + assertThat(((TestStartingEvent) event).getReportEntry().getRunMode()).isEqualTo(NORMAL_RUN); + assertThat(((TestStartingEvent) event).getReportEntry().getTestRunId()).isEqualTo(1L); + assertThat(((TestStartingEvent) event).getReportEntry().getSourceName()).isEqualTo("source"); + assertThat(((TestStartingEvent) event).getReportEntry().getSourceText()).isEqualTo("sourceText"); + assertThat(((TestStartingEvent) event).getReportEntry().getName()).isEqualTo("name"); + assertThat(((TestStartingEvent) event).getReportEntry().getNameText()).isEqualTo("nameText"); + assertThat(((TestStartingEvent) event).getReportEntry().getGroup()).isEqualTo("group"); + assertThat(((TestStartingEvent) event).getReportEntry().getMessage()).isEqualTo("message"); + assertThat(((TestStartingEvent) event).getReportEntry().getElapsed()).isEqualTo(5); + assertThat(((TestStartingEvent) event) + .getReportEntry() + .getStackTraceWriter() + .getThrowable() + .getLocalizedMessage()) + .isNull(); + assertThat(((TestStartingEvent) event) + .getReportEntry() + .getStackTraceWriter() + .smartTrimmedStackTrace()) + .isEqualTo("smartTrimmedStackTrace"); + assertThat(((TestStartingEvent) event) + .getReportEntry() + .getStackTraceWriter() + .writeTraceToString()) + .isEqualTo("stackTrace"); memento = decoder.new Memento(); - memento.getData().addAll( asList( NORMAL_RUN, 1L, "source", "sourceText", "name", "nameText", "group", - "message", 5, null, null, null ) ); - event = decoder.toMessage( BOOTERCODE_TEST_SUCCEEDED, memento ); - assertThat( event ).isInstanceOf( TestSucceededEvent.class ); - assertThat( ( (TestSucceededEvent) event ).getReportEntry().getRunMode() ).isEqualTo( NORMAL_RUN ); - assertThat( ( (TestSucceededEvent) event ).getReportEntry().getTestRunId() ).isEqualTo( 1L ); - assertThat( ( (TestSucceededEvent) event ).getReportEntry().getSourceName() ).isEqualTo( "source" ); - assertThat( ( (TestSucceededEvent) event ).getReportEntry().getSourceText() ).isEqualTo( "sourceText" ); - assertThat( ( (TestSucceededEvent) event ).getReportEntry().getName() ).isEqualTo( "name" ); - assertThat( ( (TestSucceededEvent) event ).getReportEntry().getNameText() ).isEqualTo( "nameText" ); - assertThat( ( (TestSucceededEvent) event ).getReportEntry().getGroup() ).isEqualTo( "group" ); - assertThat( ( (TestSucceededEvent) event ).getReportEntry().getMessage() ).isEqualTo( "message" ); - assertThat( ( (TestSucceededEvent) event ).getReportEntry().getElapsed() ).isEqualTo( 5 ); - assertThat( ( (TestSucceededEvent) event ).getReportEntry().getStackTraceWriter() ).isNull(); + memento.getData() + .addAll(asList( + NORMAL_RUN, + 1L, + "source", + "sourceText", + "name", + "nameText", + "group", + "message", + 5, + null, + null, + null)); + event = decoder.toMessage(BOOTERCODE_TEST_SUCCEEDED, memento); + assertThat(event).isInstanceOf(TestSucceededEvent.class); + assertThat(((TestSucceededEvent) event).getReportEntry().getRunMode()).isEqualTo(NORMAL_RUN); + assertThat(((TestSucceededEvent) event).getReportEntry().getTestRunId()).isEqualTo(1L); + assertThat(((TestSucceededEvent) event).getReportEntry().getSourceName()) + .isEqualTo("source"); + assertThat(((TestSucceededEvent) event).getReportEntry().getSourceText()) + .isEqualTo("sourceText"); + assertThat(((TestSucceededEvent) event).getReportEntry().getName()).isEqualTo("name"); + assertThat(((TestSucceededEvent) event).getReportEntry().getNameText()).isEqualTo("nameText"); + assertThat(((TestSucceededEvent) event).getReportEntry().getGroup()).isEqualTo("group"); + assertThat(((TestSucceededEvent) event).getReportEntry().getMessage()).isEqualTo("message"); + assertThat(((TestSucceededEvent) event).getReportEntry().getElapsed()).isEqualTo(5); + assertThat(((TestSucceededEvent) event).getReportEntry().getStackTraceWriter()) + .isNull(); memento = decoder.new Memento(); - memento.getData().addAll( asList( RERUN_TEST_AFTER_FAILURE, 1L, "source", null, "name", null, "group", null, 5, - "traceMessage", "smartTrimmedStackTrace", "stackTrace" ) ); - event = decoder.toMessage( BOOTERCODE_TEST_FAILED, memento ); - assertThat( event ).isInstanceOf( TestFailedEvent.class ); - assertThat( ( (TestFailedEvent) event ).getReportEntry().getRunMode() ).isEqualTo( RERUN_TEST_AFTER_FAILURE ); - assertThat( ( (TestFailedEvent) event ).getReportEntry().getTestRunId() ).isEqualTo( 1L ); - assertThat( ( (TestFailedEvent) event ).getReportEntry().getSourceName() ).isEqualTo( "source" ); - assertThat( ( (TestFailedEvent) event ).getReportEntry().getSourceText() ).isNull(); - assertThat( ( (TestFailedEvent) event ).getReportEntry().getName() ).isEqualTo( "name" ); - assertThat( ( (TestFailedEvent) event ).getReportEntry().getNameText() ).isNull(); - assertThat( ( (TestFailedEvent) event ).getReportEntry().getGroup() ).isEqualTo( "group" ); - assertThat( ( (TestFailedEvent) event ).getReportEntry().getMessage() ).isNull(); - assertThat( ( (TestFailedEvent) event ).getReportEntry().getElapsed() ).isEqualTo( 5 ); - assertThat( ( (TestFailedEvent) event ) - .getReportEntry().getStackTraceWriter().getThrowable().getLocalizedMessage() ) - .isEqualTo( "traceMessage" ); - assertThat( ( (TestFailedEvent) event ).getReportEntry().getStackTraceWriter().smartTrimmedStackTrace() ) - .isEqualTo( "smartTrimmedStackTrace" ); - assertThat( ( (TestFailedEvent) event ).getReportEntry().getStackTraceWriter().writeTraceToString() ) - .isEqualTo( "stackTrace" ); + memento.getData() + .addAll(asList( + RERUN_TEST_AFTER_FAILURE, + 1L, + "source", + null, + "name", + null, + "group", + null, + 5, + "traceMessage", + "smartTrimmedStackTrace", + "stackTrace")); + event = decoder.toMessage(BOOTERCODE_TEST_FAILED, memento); + assertThat(event).isInstanceOf(TestFailedEvent.class); + assertThat(((TestFailedEvent) event).getReportEntry().getRunMode()).isEqualTo(RERUN_TEST_AFTER_FAILURE); + assertThat(((TestFailedEvent) event).getReportEntry().getTestRunId()).isEqualTo(1L); + assertThat(((TestFailedEvent) event).getReportEntry().getSourceName()).isEqualTo("source"); + assertThat(((TestFailedEvent) event).getReportEntry().getSourceText()).isNull(); + assertThat(((TestFailedEvent) event).getReportEntry().getName()).isEqualTo("name"); + assertThat(((TestFailedEvent) event).getReportEntry().getNameText()).isNull(); + assertThat(((TestFailedEvent) event).getReportEntry().getGroup()).isEqualTo("group"); + assertThat(((TestFailedEvent) event).getReportEntry().getMessage()).isNull(); + assertThat(((TestFailedEvent) event).getReportEntry().getElapsed()).isEqualTo(5); + assertThat(((TestFailedEvent) event) + .getReportEntry() + .getStackTraceWriter() + .getThrowable() + .getLocalizedMessage()) + .isEqualTo("traceMessage"); + assertThat(((TestFailedEvent) event) + .getReportEntry() + .getStackTraceWriter() + .smartTrimmedStackTrace()) + .isEqualTo("smartTrimmedStackTrace"); + assertThat(((TestFailedEvent) event) + .getReportEntry() + .getStackTraceWriter() + .writeTraceToString()) + .isEqualTo("stackTrace"); memento = decoder.new Memento(); - memento.getData().addAll( asList( NORMAL_RUN, 1L, "source", null, "name", null, null, null, 5, null, null, - "stackTrace" ) ); - event = decoder.toMessage( BOOTERCODE_TEST_SKIPPED, memento ); - assertThat( event ).isInstanceOf( TestSkippedEvent.class ); - assertThat( ( (TestSkippedEvent) event ).getReportEntry().getRunMode() ).isEqualTo( NORMAL_RUN ); - assertThat( ( (TestSkippedEvent) event ).getReportEntry().getTestRunId() ).isEqualTo( 1L ); - assertThat( ( (TestSkippedEvent) event ).getReportEntry().getSourceName() ).isEqualTo( "source" ); - assertThat( ( (TestSkippedEvent) event ).getReportEntry().getSourceText() ).isNull(); - assertThat( ( (TestSkippedEvent) event ).getReportEntry().getName() ).isEqualTo( "name" ); - assertThat( ( (TestSkippedEvent) event ).getReportEntry().getNameText() ).isNull(); - assertThat( ( (TestSkippedEvent) event ).getReportEntry().getGroup() ).isNull(); - assertThat( ( (TestSkippedEvent) event ).getReportEntry().getMessage() ).isNull(); - assertThat( ( (TestSkippedEvent) event ).getReportEntry().getElapsed() ).isEqualTo( 5 ); - assertThat( ( (TestSkippedEvent) event ) - .getReportEntry().getStackTraceWriter().getThrowable().getLocalizedMessage() ) - .isNull(); - assertThat( ( (TestSkippedEvent) event ) - .getReportEntry().getStackTraceWriter().smartTrimmedStackTrace() ) - .isNull(); - assertThat( ( (TestSkippedEvent) event ) - .getReportEntry().getStackTraceWriter().writeTraceToString() ) - .isEqualTo( "stackTrace" ); + memento.getData() + .addAll(asList(NORMAL_RUN, 1L, "source", null, "name", null, null, null, 5, null, null, "stackTrace")); + event = decoder.toMessage(BOOTERCODE_TEST_SKIPPED, memento); + assertThat(event).isInstanceOf(TestSkippedEvent.class); + assertThat(((TestSkippedEvent) event).getReportEntry().getRunMode()).isEqualTo(NORMAL_RUN); + assertThat(((TestSkippedEvent) event).getReportEntry().getTestRunId()).isEqualTo(1L); + assertThat(((TestSkippedEvent) event).getReportEntry().getSourceName()).isEqualTo("source"); + assertThat(((TestSkippedEvent) event).getReportEntry().getSourceText()).isNull(); + assertThat(((TestSkippedEvent) event).getReportEntry().getName()).isEqualTo("name"); + assertThat(((TestSkippedEvent) event).getReportEntry().getNameText()).isNull(); + assertThat(((TestSkippedEvent) event).getReportEntry().getGroup()).isNull(); + assertThat(((TestSkippedEvent) event).getReportEntry().getMessage()).isNull(); + assertThat(((TestSkippedEvent) event).getReportEntry().getElapsed()).isEqualTo(5); + assertThat(((TestSkippedEvent) event) + .getReportEntry() + .getStackTraceWriter() + .getThrowable() + .getLocalizedMessage()) + .isNull(); + assertThat(((TestSkippedEvent) event) + .getReportEntry() + .getStackTraceWriter() + .smartTrimmedStackTrace()) + .isNull(); + assertThat(((TestSkippedEvent) event) + .getReportEntry() + .getStackTraceWriter() + .writeTraceToString()) + .isEqualTo("stackTrace"); memento = decoder.new Memento(); - memento.getData().addAll( asList( NORMAL_RUN, 1L, "source", null, "name", "nameText", null, null, 0, null, null, - "stackTrace" ) ); - event = decoder.toMessage( BOOTERCODE_TEST_ERROR, memento ); - assertThat( event ).isInstanceOf( TestErrorEvent.class ); - assertThat( ( (TestErrorEvent) event ).getReportEntry().getRunMode() ).isEqualTo( NORMAL_RUN ); - assertThat( ( (TestErrorEvent) event ).getReportEntry().getTestRunId() ).isEqualTo( 1L ); - assertThat( ( (TestErrorEvent) event ).getReportEntry().getSourceName() ).isEqualTo( "source" ); - assertThat( ( (TestErrorEvent) event ).getReportEntry().getSourceText() ).isNull(); - assertThat( ( (TestErrorEvent) event ).getReportEntry().getName() ).isEqualTo( "name" ); - assertThat( ( (TestErrorEvent) event ).getReportEntry().getNameText() ).isEqualTo( "nameText" ); - assertThat( ( (TestErrorEvent) event ).getReportEntry().getGroup() ).isNull(); - assertThat( ( (TestErrorEvent) event ).getReportEntry().getMessage() ).isNull(); - assertThat( ( (TestErrorEvent) event ).getReportEntry().getElapsed() ).isZero(); - assertThat( ( (TestErrorEvent) event ) - .getReportEntry().getStackTraceWriter().getThrowable().getLocalizedMessage() ) - .isNull(); - assertThat( ( (TestErrorEvent) event ) - .getReportEntry().getStackTraceWriter().smartTrimmedStackTrace() ) - .isNull(); - assertThat( ( (TestErrorEvent) event ) - .getReportEntry().getStackTraceWriter().writeTraceToString() ) - .isEqualTo( "stackTrace" ); + memento.getData() + .addAll(asList( + NORMAL_RUN, 1L, "source", null, "name", "nameText", null, null, 0, null, null, "stackTrace")); + event = decoder.toMessage(BOOTERCODE_TEST_ERROR, memento); + assertThat(event).isInstanceOf(TestErrorEvent.class); + assertThat(((TestErrorEvent) event).getReportEntry().getRunMode()).isEqualTo(NORMAL_RUN); + assertThat(((TestErrorEvent) event).getReportEntry().getTestRunId()).isEqualTo(1L); + assertThat(((TestErrorEvent) event).getReportEntry().getSourceName()).isEqualTo("source"); + assertThat(((TestErrorEvent) event).getReportEntry().getSourceText()).isNull(); + assertThat(((TestErrorEvent) event).getReportEntry().getName()).isEqualTo("name"); + assertThat(((TestErrorEvent) event).getReportEntry().getNameText()).isEqualTo("nameText"); + assertThat(((TestErrorEvent) event).getReportEntry().getGroup()).isNull(); + assertThat(((TestErrorEvent) event).getReportEntry().getMessage()).isNull(); + assertThat(((TestErrorEvent) event).getReportEntry().getElapsed()).isZero(); + assertThat(((TestErrorEvent) event) + .getReportEntry() + .getStackTraceWriter() + .getThrowable() + .getLocalizedMessage()) + .isNull(); + assertThat(((TestErrorEvent) event) + .getReportEntry() + .getStackTraceWriter() + .smartTrimmedStackTrace()) + .isNull(); + assertThat(((TestErrorEvent) event) + .getReportEntry() + .getStackTraceWriter() + .writeTraceToString()) + .isEqualTo("stackTrace"); memento = decoder.new Memento(); - memento.getData().addAll( asList( NORMAL_RUN, 1L, "source", null, "name", null, "group", null, 5, null, null, - "stackTrace" ) ); - event = decoder.toMessage( BOOTERCODE_TEST_ASSUMPTIONFAILURE, memento ); - assertThat( event ).isInstanceOf( TestAssumptionFailureEvent.class ); - assertThat( ( (TestAssumptionFailureEvent) event ).getReportEntry().getRunMode() ).isEqualTo( NORMAL_RUN ); - assertThat( ( (TestAssumptionFailureEvent) event ).getReportEntry().getTestRunId() ).isEqualTo( 1L ); - assertThat( ( (TestAssumptionFailureEvent) event ).getReportEntry().getSourceName() ).isEqualTo( "source" ); - assertThat( ( (TestAssumptionFailureEvent) event ).getReportEntry().getSourceText() ).isNull(); - assertThat( ( (TestAssumptionFailureEvent) event ).getReportEntry().getName() ).isEqualTo( "name" ); - assertThat( ( (TestAssumptionFailureEvent) event ).getReportEntry().getNameText() ).isNull(); - assertThat( ( (TestAssumptionFailureEvent) event ).getReportEntry().getGroup() ).isEqualTo( "group" ); - assertThat( ( (TestAssumptionFailureEvent) event ).getReportEntry().getMessage() ).isNull(); - assertThat( ( (TestAssumptionFailureEvent) event ).getReportEntry().getElapsed() ).isEqualTo( 5 ); - assertThat( ( (TestAssumptionFailureEvent) event ) - .getReportEntry().getStackTraceWriter().getThrowable().getLocalizedMessage() ) - .isNull(); - assertThat( ( (TestAssumptionFailureEvent) event ) - .getReportEntry().getStackTraceWriter().smartTrimmedStackTrace() ) - .isNull(); - assertThat( ( (TestAssumptionFailureEvent) event ) - .getReportEntry().getStackTraceWriter().writeTraceToString() ) - .isEqualTo( "stackTrace" ); + memento.getData() + .addAll(asList( + NORMAL_RUN, 1L, "source", null, "name", null, "group", null, 5, null, null, "stackTrace")); + event = decoder.toMessage(BOOTERCODE_TEST_ASSUMPTIONFAILURE, memento); + assertThat(event).isInstanceOf(TestAssumptionFailureEvent.class); + assertThat(((TestAssumptionFailureEvent) event).getReportEntry().getRunMode()) + .isEqualTo(NORMAL_RUN); + assertThat(((TestAssumptionFailureEvent) event).getReportEntry().getTestRunId()) + .isEqualTo(1L); + assertThat(((TestAssumptionFailureEvent) event).getReportEntry().getSourceName()) + .isEqualTo("source"); + assertThat(((TestAssumptionFailureEvent) event).getReportEntry().getSourceText()) + .isNull(); + assertThat(((TestAssumptionFailureEvent) event).getReportEntry().getName()) + .isEqualTo("name"); + assertThat(((TestAssumptionFailureEvent) event).getReportEntry().getNameText()) + .isNull(); + assertThat(((TestAssumptionFailureEvent) event).getReportEntry().getGroup()) + .isEqualTo("group"); + assertThat(((TestAssumptionFailureEvent) event).getReportEntry().getMessage()) + .isNull(); + assertThat(((TestAssumptionFailureEvent) event).getReportEntry().getElapsed()) + .isEqualTo(5); + assertThat(((TestAssumptionFailureEvent) event) + .getReportEntry() + .getStackTraceWriter() + .getThrowable() + .getLocalizedMessage()) + .isNull(); + assertThat(((TestAssumptionFailureEvent) event) + .getReportEntry() + .getStackTraceWriter() + .smartTrimmedStackTrace()) + .isNull(); + assertThat(((TestAssumptionFailureEvent) event) + .getReportEntry() + .getStackTraceWriter() + .writeTraceToString()) + .isEqualTo("stackTrace"); } @Test - public void shouldRecognizeEmptyStream4ReportEntry() - { - ReportEntry reportEntry = newReportEntry( NORMAL_RUN, 1L, "", "", "", "", "", "", null, "", "", "" ); - assertThat( reportEntry ).isNotNull(); - assertThat( reportEntry.getRunMode() ).isEqualTo( NORMAL_RUN ); - assertThat( reportEntry.getTestRunId() ).isEqualTo( 1L ); - assertThat( reportEntry.getStackTraceWriter() ).isNotNull(); - assertThat( reportEntry.getStackTraceWriter().smartTrimmedStackTrace() ).isEmpty(); - assertThat( reportEntry.getStackTraceWriter().writeTraceToString() ).isEmpty(); - assertThat( reportEntry.getStackTraceWriter().writeTrimmedTraceToString() ).isEmpty(); - assertThat( reportEntry.getSourceName() ).isEmpty(); - assertThat( reportEntry.getSourceText() ).isEmpty(); - assertThat( reportEntry.getName() ).isEmpty(); - assertThat( reportEntry.getNameText() ).isEmpty(); - assertThat( reportEntry.getGroup() ).isEmpty(); - assertThat( reportEntry.getNameWithGroup() ).isEmpty(); - assertThat( reportEntry.getMessage() ).isEmpty(); - assertThat( reportEntry.getElapsed() ).isNull(); + public void shouldRecognizeEmptyStream4ReportEntry() { + ReportEntry reportEntry = newReportEntry(NORMAL_RUN, 1L, "", "", "", "", "", "", null, "", "", ""); + assertThat(reportEntry).isNotNull(); + assertThat(reportEntry.getRunMode()).isEqualTo(NORMAL_RUN); + assertThat(reportEntry.getTestRunId()).isEqualTo(1L); + assertThat(reportEntry.getStackTraceWriter()).isNotNull(); + assertThat(reportEntry.getStackTraceWriter().smartTrimmedStackTrace()).isEmpty(); + assertThat(reportEntry.getStackTraceWriter().writeTraceToString()).isEmpty(); + assertThat(reportEntry.getStackTraceWriter().writeTrimmedTraceToString()) + .isEmpty(); + assertThat(reportEntry.getSourceName()).isEmpty(); + assertThat(reportEntry.getSourceText()).isEmpty(); + assertThat(reportEntry.getName()).isEmpty(); + assertThat(reportEntry.getNameText()).isEmpty(); + assertThat(reportEntry.getGroup()).isEmpty(); + assertThat(reportEntry.getNameWithGroup()).isEmpty(); + assertThat(reportEntry.getMessage()).isEmpty(); + assertThat(reportEntry.getElapsed()).isNull(); } @Test - @SuppressWarnings( "checkstyle:magicnumber" ) - public void testCreatingReportEntry() - { + @SuppressWarnings("checkstyle:magicnumber") + public void testCreatingReportEntry() { final String exceptionMessage = "msg"; final String smartStackTrace = "MyTest:86 >> Error"; final String stackTrace = "Exception: msg\ntrace line 1\ntrace line 2"; final String trimmedStackTrace = "trace line 1\ntrace line 2"; - SafeThrowable safeThrowable = new SafeThrowable( exceptionMessage ); - StackTraceWriter stackTraceWriter = mock( StackTraceWriter.class ); - when( stackTraceWriter.getThrowable() ).thenReturn( safeThrowable ); - when( stackTraceWriter.smartTrimmedStackTrace() ).thenReturn( smartStackTrace ); - when( stackTraceWriter.writeTrimmedTraceToString() ).thenReturn( trimmedStackTrace ); - when( stackTraceWriter.writeTraceToString() ).thenReturn( stackTrace ); - - ReportEntry reportEntry = mock( ReportEntry.class ); - when( reportEntry.getElapsed() ).thenReturn( 102 ); - when( reportEntry.getGroup() ).thenReturn( "this group" ); - when( reportEntry.getMessage() ).thenReturn( "skipped test" ); - when( reportEntry.getName() ).thenReturn( "my test" ); - when( reportEntry.getNameText() ).thenReturn( "my display name" ); - when( reportEntry.getNameWithGroup() ).thenReturn( "name with group" ); - when( reportEntry.getSourceName() ).thenReturn( "pkg.MyTest" ); - when( reportEntry.getSourceText() ).thenReturn( "test class display name" ); - when( reportEntry.getStackTraceWriter() ).thenReturn( stackTraceWriter ); - - ReportEntry decodedReportEntry = newReportEntry( NORMAL_RUN, 1L, reportEntry.getSourceName(), - reportEntry.getSourceText(), reportEntry.getName(), reportEntry.getNameText(), reportEntry.getGroup(), - reportEntry.getMessage(), null, null, null, null ); - - assertThat( decodedReportEntry ).isNotNull(); - assertThat( decodedReportEntry.getSourceName() ).isEqualTo( reportEntry.getSourceName() ); - assertThat( decodedReportEntry.getSourceText() ).isEqualTo( reportEntry.getSourceText() ); - assertThat( decodedReportEntry.getName() ).isEqualTo( reportEntry.getName() ); - assertThat( decodedReportEntry.getNameText() ).isEqualTo( reportEntry.getNameText() ); - assertThat( decodedReportEntry.getGroup() ).isEqualTo( reportEntry.getGroup() ); - assertThat( decodedReportEntry.getMessage() ).isEqualTo( reportEntry.getMessage() ); - assertThat( decodedReportEntry.getStackTraceWriter() ).isNull(); - - decodedReportEntry = newReportEntry( NORMAL_RUN, 1L, reportEntry.getSourceName(), - reportEntry.getSourceText(), reportEntry.getName(), reportEntry.getNameText(), reportEntry.getGroup(), - reportEntry.getMessage(), null, exceptionMessage, smartStackTrace, null ); - - assertThat( decodedReportEntry ).isNotNull(); - assertThat( decodedReportEntry.getSourceName() ).isEqualTo( reportEntry.getSourceName() ); - assertThat( decodedReportEntry.getSourceText() ).isEqualTo( reportEntry.getSourceText() ); - assertThat( decodedReportEntry.getName() ).isEqualTo( reportEntry.getName() ); - assertThat( decodedReportEntry.getNameText() ).isEqualTo( reportEntry.getNameText() ); - assertThat( decodedReportEntry.getGroup() ).isEqualTo( reportEntry.getGroup() ); - assertThat( decodedReportEntry.getMessage() ).isEqualTo( reportEntry.getMessage() ); - assertThat( decodedReportEntry.getElapsed() ).isNull(); - assertThat( decodedReportEntry.getStackTraceWriter() ).isNotNull(); - assertThat( decodedReportEntry.getStackTraceWriter().getThrowable().getMessage() ) - .isEqualTo( exceptionMessage ); - assertThat( decodedReportEntry.getStackTraceWriter().smartTrimmedStackTrace() ) - .isEqualTo( smartStackTrace ); - assertThat( decodedReportEntry.getStackTraceWriter().writeTraceToString() ) - .isNull(); - - decodedReportEntry = newReportEntry( NORMAL_RUN, 1L, reportEntry.getSourceName(), - reportEntry.getSourceText(), reportEntry.getName(), reportEntry.getNameText(), reportEntry.getGroup(), - reportEntry.getMessage(), 1003, exceptionMessage, smartStackTrace, null ); - - assertThat( decodedReportEntry ).isNotNull(); - assertThat( decodedReportEntry.getSourceName() ).isEqualTo( reportEntry.getSourceName() ); - assertThat( decodedReportEntry.getSourceText() ).isEqualTo( reportEntry.getSourceText() ); - assertThat( decodedReportEntry.getName() ).isEqualTo( reportEntry.getName() ); - assertThat( decodedReportEntry.getNameText() ).isEqualTo( reportEntry.getNameText() ); - assertThat( decodedReportEntry.getGroup() ).isEqualTo( reportEntry.getGroup() ); - assertThat( decodedReportEntry.getMessage() ).isEqualTo( reportEntry.getMessage() ); - assertThat( decodedReportEntry.getElapsed() ).isEqualTo( 1003 ); - assertThat( decodedReportEntry.getStackTraceWriter() ).isNotNull(); - assertThat( decodedReportEntry.getStackTraceWriter().getThrowable().getMessage() ) - .isEqualTo( exceptionMessage ); - assertThat( decodedReportEntry.getStackTraceWriter().smartTrimmedStackTrace() ) - .isEqualTo( smartStackTrace ); - assertThat( decodedReportEntry.getStackTraceWriter().writeTraceToString() ) - .isNull(); - - decodedReportEntry = newReportEntry( NORMAL_RUN, 1L, reportEntry.getSourceName(), - reportEntry.getSourceText(), reportEntry.getName(), reportEntry.getNameText(), reportEntry.getGroup(), - reportEntry.getMessage(), 1003, exceptionMessage, smartStackTrace, stackTrace ); - - assertThat( decodedReportEntry ).isNotNull(); - assertThat( decodedReportEntry.getSourceName() ).isEqualTo( reportEntry.getSourceName() ); - assertThat( decodedReportEntry.getSourceText() ).isEqualTo( reportEntry.getSourceText() ); - assertThat( decodedReportEntry.getName() ).isEqualTo( reportEntry.getName() ); - assertThat( decodedReportEntry.getNameText() ).isEqualTo( reportEntry.getNameText() ); - assertThat( decodedReportEntry.getGroup() ).isEqualTo( reportEntry.getGroup() ); - assertThat( decodedReportEntry.getMessage() ).isEqualTo( reportEntry.getMessage() ); - assertThat( decodedReportEntry.getElapsed() ).isEqualTo( 1003 ); - assertThat( decodedReportEntry.getStackTraceWriter() ).isNotNull(); - assertThat( decodedReportEntry.getStackTraceWriter().getThrowable().getMessage() ).isNotNull(); - assertThat( decodedReportEntry.getStackTraceWriter().getThrowable().getMessage() ) - .isEqualTo( exceptionMessage ); - assertThat( decodedReportEntry.getStackTraceWriter().smartTrimmedStackTrace() ) - .isEqualTo( smartStackTrace ); - assertThat( decodedReportEntry.getStackTraceWriter().writeTraceToString() ).isEqualTo( stackTrace ); - assertThat( decodedReportEntry.getStackTraceWriter().writeTrimmedTraceToString() ).isEqualTo( stackTrace ); - - decodedReportEntry = newReportEntry( NORMAL_RUN, 1L, reportEntry.getSourceName(), - reportEntry.getSourceText(), reportEntry.getName(), reportEntry.getNameText(), reportEntry.getGroup(), - reportEntry.getMessage(), 1003, exceptionMessage, smartStackTrace, trimmedStackTrace ); - - assertThat( decodedReportEntry ).isNotNull(); - assertThat( decodedReportEntry.getSourceName() ).isEqualTo( reportEntry.getSourceName() ); - assertThat( decodedReportEntry.getSourceText() ).isEqualTo( reportEntry.getSourceText() ); - assertThat( decodedReportEntry.getName() ).isEqualTo( reportEntry.getName() ); - assertThat( decodedReportEntry.getNameText() ).isEqualTo( reportEntry.getNameText() ); - assertThat( decodedReportEntry.getGroup() ).isEqualTo( reportEntry.getGroup() ); - assertThat( decodedReportEntry.getMessage() ).isEqualTo( reportEntry.getMessage() ); - assertThat( decodedReportEntry.getElapsed() ).isEqualTo( 1003 ); - assertThat( decodedReportEntry.getStackTraceWriter() ).isNotNull(); - assertThat( decodedReportEntry.getStackTraceWriter().getThrowable().getMessage() ).isNotNull(); - assertThat( decodedReportEntry.getStackTraceWriter().getThrowable().getMessage() ) - .isEqualTo( exceptionMessage ); - assertThat( decodedReportEntry.getStackTraceWriter().smartTrimmedStackTrace() ) - .isEqualTo( smartStackTrace ); - assertThat( decodedReportEntry.getStackTraceWriter().writeTraceToString() ).isEqualTo( trimmedStackTrace ); - assertThat( decodedReportEntry.getStackTraceWriter().writeTrimmedTraceToString() ) - .isEqualTo( trimmedStackTrace ); + SafeThrowable safeThrowable = new SafeThrowable(exceptionMessage); + StackTraceWriter stackTraceWriter = mock(StackTraceWriter.class); + when(stackTraceWriter.getThrowable()).thenReturn(safeThrowable); + when(stackTraceWriter.smartTrimmedStackTrace()).thenReturn(smartStackTrace); + when(stackTraceWriter.writeTrimmedTraceToString()).thenReturn(trimmedStackTrace); + when(stackTraceWriter.writeTraceToString()).thenReturn(stackTrace); + + ReportEntry reportEntry = mock(ReportEntry.class); + when(reportEntry.getElapsed()).thenReturn(102); + when(reportEntry.getGroup()).thenReturn("this group"); + when(reportEntry.getMessage()).thenReturn("skipped test"); + when(reportEntry.getName()).thenReturn("my test"); + when(reportEntry.getNameText()).thenReturn("my display name"); + when(reportEntry.getNameWithGroup()).thenReturn("name with group"); + when(reportEntry.getSourceName()).thenReturn("pkg.MyTest"); + when(reportEntry.getSourceText()).thenReturn("test class display name"); + when(reportEntry.getStackTraceWriter()).thenReturn(stackTraceWriter); + + ReportEntry decodedReportEntry = newReportEntry( + NORMAL_RUN, + 1L, + reportEntry.getSourceName(), + reportEntry.getSourceText(), + reportEntry.getName(), + reportEntry.getNameText(), + reportEntry.getGroup(), + reportEntry.getMessage(), + null, + null, + null, + null); + + assertThat(decodedReportEntry).isNotNull(); + assertThat(decodedReportEntry.getSourceName()).isEqualTo(reportEntry.getSourceName()); + assertThat(decodedReportEntry.getSourceText()).isEqualTo(reportEntry.getSourceText()); + assertThat(decodedReportEntry.getName()).isEqualTo(reportEntry.getName()); + assertThat(decodedReportEntry.getNameText()).isEqualTo(reportEntry.getNameText()); + assertThat(decodedReportEntry.getGroup()).isEqualTo(reportEntry.getGroup()); + assertThat(decodedReportEntry.getMessage()).isEqualTo(reportEntry.getMessage()); + assertThat(decodedReportEntry.getStackTraceWriter()).isNull(); + + decodedReportEntry = newReportEntry( + NORMAL_RUN, + 1L, + reportEntry.getSourceName(), + reportEntry.getSourceText(), + reportEntry.getName(), + reportEntry.getNameText(), + reportEntry.getGroup(), + reportEntry.getMessage(), + null, + exceptionMessage, + smartStackTrace, + null); + + assertThat(decodedReportEntry).isNotNull(); + assertThat(decodedReportEntry.getSourceName()).isEqualTo(reportEntry.getSourceName()); + assertThat(decodedReportEntry.getSourceText()).isEqualTo(reportEntry.getSourceText()); + assertThat(decodedReportEntry.getName()).isEqualTo(reportEntry.getName()); + assertThat(decodedReportEntry.getNameText()).isEqualTo(reportEntry.getNameText()); + assertThat(decodedReportEntry.getGroup()).isEqualTo(reportEntry.getGroup()); + assertThat(decodedReportEntry.getMessage()).isEqualTo(reportEntry.getMessage()); + assertThat(decodedReportEntry.getElapsed()).isNull(); + assertThat(decodedReportEntry.getStackTraceWriter()).isNotNull(); + assertThat(decodedReportEntry.getStackTraceWriter().getThrowable().getMessage()) + .isEqualTo(exceptionMessage); + assertThat(decodedReportEntry.getStackTraceWriter().smartTrimmedStackTrace()) + .isEqualTo(smartStackTrace); + assertThat(decodedReportEntry.getStackTraceWriter().writeTraceToString()) + .isNull(); + + decodedReportEntry = newReportEntry( + NORMAL_RUN, + 1L, + reportEntry.getSourceName(), + reportEntry.getSourceText(), + reportEntry.getName(), + reportEntry.getNameText(), + reportEntry.getGroup(), + reportEntry.getMessage(), + 1003, + exceptionMessage, + smartStackTrace, + null); + + assertThat(decodedReportEntry).isNotNull(); + assertThat(decodedReportEntry.getSourceName()).isEqualTo(reportEntry.getSourceName()); + assertThat(decodedReportEntry.getSourceText()).isEqualTo(reportEntry.getSourceText()); + assertThat(decodedReportEntry.getName()).isEqualTo(reportEntry.getName()); + assertThat(decodedReportEntry.getNameText()).isEqualTo(reportEntry.getNameText()); + assertThat(decodedReportEntry.getGroup()).isEqualTo(reportEntry.getGroup()); + assertThat(decodedReportEntry.getMessage()).isEqualTo(reportEntry.getMessage()); + assertThat(decodedReportEntry.getElapsed()).isEqualTo(1003); + assertThat(decodedReportEntry.getStackTraceWriter()).isNotNull(); + assertThat(decodedReportEntry.getStackTraceWriter().getThrowable().getMessage()) + .isEqualTo(exceptionMessage); + assertThat(decodedReportEntry.getStackTraceWriter().smartTrimmedStackTrace()) + .isEqualTo(smartStackTrace); + assertThat(decodedReportEntry.getStackTraceWriter().writeTraceToString()) + .isNull(); + + decodedReportEntry = newReportEntry( + NORMAL_RUN, + 1L, + reportEntry.getSourceName(), + reportEntry.getSourceText(), + reportEntry.getName(), + reportEntry.getNameText(), + reportEntry.getGroup(), + reportEntry.getMessage(), + 1003, + exceptionMessage, + smartStackTrace, + stackTrace); + + assertThat(decodedReportEntry).isNotNull(); + assertThat(decodedReportEntry.getSourceName()).isEqualTo(reportEntry.getSourceName()); + assertThat(decodedReportEntry.getSourceText()).isEqualTo(reportEntry.getSourceText()); + assertThat(decodedReportEntry.getName()).isEqualTo(reportEntry.getName()); + assertThat(decodedReportEntry.getNameText()).isEqualTo(reportEntry.getNameText()); + assertThat(decodedReportEntry.getGroup()).isEqualTo(reportEntry.getGroup()); + assertThat(decodedReportEntry.getMessage()).isEqualTo(reportEntry.getMessage()); + assertThat(decodedReportEntry.getElapsed()).isEqualTo(1003); + assertThat(decodedReportEntry.getStackTraceWriter()).isNotNull(); + assertThat(decodedReportEntry.getStackTraceWriter().getThrowable().getMessage()) + .isNotNull(); + assertThat(decodedReportEntry.getStackTraceWriter().getThrowable().getMessage()) + .isEqualTo(exceptionMessage); + assertThat(decodedReportEntry.getStackTraceWriter().smartTrimmedStackTrace()) + .isEqualTo(smartStackTrace); + assertThat(decodedReportEntry.getStackTraceWriter().writeTraceToString()) + .isEqualTo(stackTrace); + assertThat(decodedReportEntry.getStackTraceWriter().writeTrimmedTraceToString()) + .isEqualTo(stackTrace); + + decodedReportEntry = newReportEntry( + NORMAL_RUN, + 1L, + reportEntry.getSourceName(), + reportEntry.getSourceText(), + reportEntry.getName(), + reportEntry.getNameText(), + reportEntry.getGroup(), + reportEntry.getMessage(), + 1003, + exceptionMessage, + smartStackTrace, + trimmedStackTrace); + + assertThat(decodedReportEntry).isNotNull(); + assertThat(decodedReportEntry.getSourceName()).isEqualTo(reportEntry.getSourceName()); + assertThat(decodedReportEntry.getSourceText()).isEqualTo(reportEntry.getSourceText()); + assertThat(decodedReportEntry.getName()).isEqualTo(reportEntry.getName()); + assertThat(decodedReportEntry.getNameText()).isEqualTo(reportEntry.getNameText()); + assertThat(decodedReportEntry.getGroup()).isEqualTo(reportEntry.getGroup()); + assertThat(decodedReportEntry.getMessage()).isEqualTo(reportEntry.getMessage()); + assertThat(decodedReportEntry.getElapsed()).isEqualTo(1003); + assertThat(decodedReportEntry.getStackTraceWriter()).isNotNull(); + assertThat(decodedReportEntry.getStackTraceWriter().getThrowable().getMessage()) + .isNotNull(); + assertThat(decodedReportEntry.getStackTraceWriter().getThrowable().getMessage()) + .isEqualTo(exceptionMessage); + assertThat(decodedReportEntry.getStackTraceWriter().smartTrimmedStackTrace()) + .isEqualTo(smartStackTrace); + assertThat(decodedReportEntry.getStackTraceWriter().writeTraceToString()) + .isEqualTo(trimmedStackTrace); + assertThat(decodedReportEntry.getStackTraceWriter().writeTrimmedTraceToString()) + .isEqualTo(trimmedStackTrace); } - private static class Channel implements ReadableByteChannel - { + private static class Channel implements ReadableByteChannel { private final byte[] bytes; private final int chunkSize; protected int i; - Channel( byte[] bytes, int chunkSize ) - { + Channel(byte[] bytes, int chunkSize) { this.bytes = bytes; this.chunkSize = chunkSize; } @Override - public int read( ByteBuffer dst ) - { - if ( i == bytes.length ) - { + public int read(ByteBuffer dst) { + if (i == bytes.length) { return -1; - } - else if ( dst.hasRemaining() ) - { - int length = min( min( chunkSize, bytes.length - i ), dst.remaining() ) ; - dst.put( bytes, i, length ); + } else if (dst.hasRemaining()) { + int length = min(min(chunkSize, bytes.length - i), dst.remaining()); + dst.put(bytes, i, length); i += length; return length; - } - else - { + } else { return 0; } } @Override - public boolean isOpen() - { + public boolean isOpen() { return false; } @Override - public void close() - { - } + public void close() {} } - private static class MockForkNodeArguments implements ForkNodeArguments - { + private static class MockForkNodeArguments implements ForkNodeArguments { @Nonnull @Override - public String getSessionId() - { + public String getSessionId() { return null; } @Override - public int getForkChannelId() - { + public int getForkChannelId() { return 0; } @Nonnull @Override - public File dumpStreamText( @Nonnull String text ) - { + public File dumpStreamText(@Nonnull String text) { return null; } @Nonnull @Override - public File dumpStreamException( @Nonnull Throwable t ) - { + public File dumpStreamException(@Nonnull Throwable t) { return null; } @Override - public void logWarningAtEnd( @Nonnull String text ) - { - } + public void logWarningAtEnd(@Nonnull String text) {} @Nonnull @Override - public ConsoleLogger getConsoleLogger() - { + public ConsoleLogger getConsoleLogger() { return null; } @Nonnull @Override - public Object getConsoleLock() - { + public Object getConsoleLock() { return new Object(); } @Override - public File getEventStreamBinaryFile() - { + public File getEventStreamBinaryFile() { return null; } @Override - public File getCommandStreamBinaryFile() - { + public File getCommandStreamBinaryFile() { return null; } } - } diff --git a/maven-surefire-common/src/test/java/org/apache/maven/surefire/util/RelocatorTest.java b/maven-surefire-common/src/test/java/org/apache/maven/surefire/util/RelocatorTest.java index 34827775f6..a637c274df 100644 --- a/maven-surefire-common/src/test/java/org/apache/maven/surefire/util/RelocatorTest.java +++ b/maven-surefire-common/src/test/java/org/apache/maven/surefire/util/RelocatorTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.util; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,27 +16,23 @@ * specific language governing permissions and limitations * under the License. */ - -import org.apache.maven.plugin.surefire.util.Relocator; +package org.apache.maven.surefire.util; import junit.framework.TestCase; +import org.apache.maven.plugin.surefire.util.Relocator; /** * @author Kristian Rosenvold */ -public class RelocatorTest - extends TestCase -{ +public class RelocatorTest extends TestCase { - public void testFoo() - { + public void testFoo() { String cn = "org.apache.maven.surefire.report.ForkingConsoleReporter"; - assertEquals( "org.apache.maven.shadefire.surefire.report.ForkingConsoleReporter", Relocator.relocate( cn ) ); + assertEquals("org.apache.maven.shadefire.surefire.report.ForkingConsoleReporter", Relocator.relocate(cn)); } - public void testRelocation() - { + public void testRelocation() { String org1 = "org.apache.maven.surefire.fooz.Baz"; - assertEquals( "org.apache.maven.shadefire.surefire.fooz.Baz", Relocator.relocate( org1 ) ); + assertEquals("org.apache.maven.shadefire.surefire.fooz.Baz", Relocator.relocate(org1)); } } diff --git a/maven-surefire-plugin/pom.xml b/maven-surefire-plugin/pom.xml index 25c219005d..5f256d1d77 100644 --- a/maven-surefire-plugin/pom.xml +++ b/maven-surefire-plugin/pom.xml @@ -17,175 +17,175 @@ ~ specific language governing permissions and limitations ~ under the License. --> - - 4.0.0 + 4.0.0 + + + org.apache.maven.surefire + surefire + 3.0.0-M10-SNAPSHOT + - - org.apache.maven.surefire - surefire - 3.0.0-M10-SNAPSHOT - + org.apache.maven.plugins + maven-surefire-plugin + maven-plugin - org.apache.maven.plugins - maven-surefire-plugin - maven-plugin + Maven Surefire Plugin + Maven Surefire MOJO in maven-surefire-plugin. - Maven Surefire Plugin - Maven Surefire MOJO in maven-surefire-plugin. + + ${mavenVersion} + - - ${mavenVersion} - + + Surefire + Failsafe + - - Surefire - Failsafe - + + + org.apache.maven.surefire + maven-surefire-common + ${project.version} + + + org.apache.maven + maven-core + provided + + + org.apache.maven.plugin-tools + maven-plugin-annotations + provided + + - - + + + + org.apache.maven.plugins + maven-plugin-plugin + + + org.jacoco + jacoco-maven-plugin + + jacoco.agent + + + + jacoco-agent + + prepare-agent + + + + + + maven-surefire-plugin + + ${jvm.args.tests} ${jacoco.agent} + + + org.apache.maven.surefire - maven-surefire-common - ${project.version} - - - org.apache.maven - maven-core - provided - - - org.apache.maven.plugin-tools - maven-plugin-annotations - provided - - + surefire-shadefire + 3.0.0-M7 + + + + + + maven-assembly-plugin + + + build-site + + single + + package + + + src/assembly/site-source.xml + + + + + + + maven-antrun-plugin + + + generate-test-report + + run + + site + + + + + + + + + + + + + + + org.apache.maven.plugins + maven-plugin-plugin + + + - + + + ci + + + enableCiProfile + true + + + - - org.apache.maven.plugins - maven-plugin-plugin - - - org.jacoco - jacoco-maven-plugin - - - jacoco-agent - - prepare-agent - - - - - jacoco.agent - - - - maven-surefire-plugin - - ${jvm.args.tests} ${jacoco.agent} - - - - org.apache.maven.surefire - surefire-shadefire - 3.0.0-M7 - - - - - maven-assembly-plugin - - - build-site - package - - single - - - - src/assembly/site-source.xml - - - - - - - maven-antrun-plugin - - - generate-test-report - site - - run - - - - - - - - - + + maven-docck-plugin + 1.1 + + + + check + + + + - - - + + + + reporting + - - org.apache.maven.plugins - maven-plugin-plugin - + + org.apache.maven.plugins + maven-changes-plugin + + false + + + + + jira-report + + + + - - - - - ci - - - enableCiProfile - true - - - - - - maven-docck-plugin - 1.1 - - - - check - - - - - - - - - reporting - - - - org.apache.maven.plugins - maven-changes-plugin - - false - - - - - jira-report - - - - - - - - + + + diff --git a/maven-surefire-plugin/src/main/java/org/apache/maven/plugin/surefire/SurefirePlugin.java b/maven-surefire-plugin/src/main/java/org/apache/maven/plugin/surefire/SurefirePlugin.java index 20fba421fd..f9de9e6a3f 100644 --- a/maven-surefire-plugin/src/main/java/org/apache/maven/plugin/surefire/SurefirePlugin.java +++ b/maven-surefire-plugin/src/main/java/org/apache/maven/plugin/surefire/SurefirePlugin.java @@ -1,3 +1,21 @@ +/* + * 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.maven.plugin.surefire; /* @@ -23,6 +41,7 @@ import java.util.Arrays; import java.util.Collections; import java.util.List; + import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugin.surefire.booterclient.ChecksumCalculator; @@ -30,8 +49,8 @@ import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.plugins.annotations.ResolutionScope; -import org.apache.maven.surefire.extensions.ForkNodeFactory; import org.apache.maven.surefire.api.suite.RunResult; +import org.apache.maven.surefire.extensions.ForkNodeFactory; import static org.apache.maven.plugin.surefire.SurefireHelper.reportExecution; @@ -40,34 +59,34 @@ * * @author Jason van Zyl */ -@Mojo( name = "test", defaultPhase = LifecyclePhase.TEST, threadSafe = true, - requiresDependencyResolution = ResolutionScope.TEST ) -public class SurefirePlugin - extends AbstractSurefireMojo - implements SurefireReportParameters -{ +@Mojo( + name = "test", + defaultPhase = LifecyclePhase.TEST, + threadSafe = true, + requiresDependencyResolution = ResolutionScope.TEST) +public class SurefirePlugin extends AbstractSurefireMojo implements SurefireReportParameters { /** * The directory containing generated classes of the project being tested. This will be included after the test * classes in the test classpath. */ - @Parameter( defaultValue = "${project.build.outputDirectory}" ) + @Parameter(defaultValue = "${project.build.outputDirectory}") private File classesDirectory; /** * Set this to "true" to ignore a failure during testing. Its use is NOT RECOMMENDED, but quite convenient on * occasion. */ - @Parameter( property = "maven.test.failure.ignore", defaultValue = "false" ) + @Parameter(property = "maven.test.failure.ignore", defaultValue = "false") private boolean testFailureIgnore; /** * Base directory where all reports are written to. */ - @Parameter( defaultValue = "${project.build.directory}/surefire-reports" ) + @Parameter(defaultValue = "${project.build.directory}/surefire-reports") private File reportsDirectory; - @SuppressWarnings( "checkstyle:linelength" ) + @SuppressWarnings("checkstyle:linelength") /** * Specify this parameter to run individual tests by file name, overriding the parameter {@code includes} and * {@code excludes}. Each pattern you specify here will be used to create an include pattern formatted like @@ -90,26 +109,26 @@ public class SurefirePlugin * If using @Parameters(name="{index}: fib({0})={1}") and selecting the index e.g. 5 in pattern, the * non-regex method pattern would become {@code #testMethod[5:*]}. */ - @Parameter( property = "test" ) + @Parameter(property = "test") private String test; /** * Option to print summary of test suites or just print the test cases that have errors. */ - @Parameter( property = "surefire.printSummary", defaultValue = "true" ) + @Parameter(property = "surefire.printSummary", defaultValue = "true") private boolean printSummary; /** * Selects the formatting for the test report to be generated. Can be set as "brief" or "plain". * Only applies to the output format of the output files (target/surefire-reports/testName.txt) */ - @Parameter( property = "surefire.reportFormat", defaultValue = "brief" ) + @Parameter(property = "surefire.reportFormat", defaultValue = "brief") private String reportFormat; /** * Option to generate a file test report or just output the test report to the console. */ - @Parameter( property = "surefire.useFile", defaultValue = "true" ) + @Parameter(property = "surefire.useFile", defaultValue = "true") private boolean useFile; /** @@ -118,7 +137,7 @@ public class SurefirePlugin * * @since 2.12 */ - @Parameter( property = "surefire.failIfNoSpecifiedTests", defaultValue = "true" ) + @Parameter(property = "surefire.failIfNoSpecifiedTests", defaultValue = "true") private boolean failIfNoSpecifiedTests; /** @@ -129,7 +148,7 @@ public class SurefirePlugin * * @since 2.4 */ - @Parameter( property = "maven.surefire.debug" ) + @Parameter(property = "maven.surefire.debug") private String debugForkedProcess; /** @@ -138,7 +157,7 @@ public class SurefirePlugin * * @since 2.4 */ - @Parameter( property = "surefire.timeout" ) + @Parameter(property = "surefire.timeout") private int forkedProcessTimeoutInSeconds; /** @@ -151,7 +170,7 @@ public class SurefirePlugin * * @since 2.20 */ - @Parameter( property = "surefire.exitTimeout", defaultValue = "30" ) + @Parameter(property = "surefire.exitTimeout", defaultValue = "30") private int forkedProcessExitTimeoutInSeconds; /** @@ -164,7 +183,7 @@ public class SurefirePlugin * * @since 2.16 */ - @Parameter( property = "surefire.parallel.timeout" ) + @Parameter(property = "surefire.parallel.timeout") private double parallelTestsTimeoutInSeconds; /** @@ -178,10 +197,10 @@ public class SurefirePlugin * * @since 2.16 */ - @Parameter( property = "surefire.parallel.forcedTimeout" ) + @Parameter(property = "surefire.parallel.forcedTimeout") private double parallelTestsTimeoutForcedInSeconds; - @SuppressWarnings( "checkstyle:linelength" ) + @SuppressWarnings("checkstyle:linelength") /** * A list of {@literal } elements specifying the tests (by pattern) that should be included in testing. * When not specified and when the {@code test} parameter is not specified, the default includes will be @@ -208,7 +227,7 @@ public class SurefirePlugin * to the POM property {@code ${project.build.testOutputDirectory}}, typically * {@literal src/test/java} unless overridden. */ - @Parameter( property = "surefire.includes" ) + @Parameter(property = "surefire.includes") // TODO use regex for fully qualified class names in 3.0 and change the filtering abilities private List includes; @@ -236,7 +255,7 @@ public class SurefirePlugin * to the POM property ${project.build.testOutputDirectory}, typically * {@literal src/test/java} unless overridden. */ - @Parameter( property = "surefire.excludes" ) + @Parameter(property = "surefire.excludes") // TODO use regex for fully qualified class names in 3.0 and change the filtering abilities private List excludes; @@ -247,7 +266,7 @@ public class SurefirePlugin * * @since 2.3 */ - @Parameter( property = "surefire.useSystemClassLoader", defaultValue = "true" ) + @Parameter(property = "surefire.useSystemClassLoader", defaultValue = "true") private boolean useSystemClassLoader; /** @@ -261,7 +280,7 @@ public class SurefirePlugin * * @since 2.4.3 */ - @Parameter( property = "surefire.useManifestOnlyJar", defaultValue = "true" ) + @Parameter(property = "surefire.useManifestOnlyJar", defaultValue = "true") private boolean useManifestOnlyJar; /** @@ -271,7 +290,7 @@ public class SurefirePlugin * * @since 3.0.0-M1 */ - @Parameter( property = "surefire.encoding", defaultValue = "${project.reporting.outputEncoding}" ) + @Parameter(property = "surefire.encoding", defaultValue = "${project.reporting.outputEncoding}") private String encoding; /** @@ -280,7 +299,7 @@ public class SurefirePlugin * they fail. If a failing test passes in any of those reruns, it will be marked as pass and reported as a "flake". * However, all the failing attempts will be recorded. */ - @Parameter( property = "surefire.rerunFailingTestsCount", defaultValue = "0" ) + @Parameter(property = "surefire.rerunFailingTestsCount", defaultValue = "0") private int rerunFailingTestsCount; /** @@ -289,7 +308,7 @@ public class SurefirePlugin * * @since 3.0.0-M6 */ - @Parameter( property = "surefire.failOnFlakeCount", defaultValue = "0" ) + @Parameter(property = "surefire.failOnFlakeCount", defaultValue = "0") private int failOnFlakeCount; /** @@ -301,7 +320,7 @@ public class SurefirePlugin * * @since 2.2 */ - @Parameter( property = "surefire.suiteXmlFiles" ) + @Parameter(property = "surefire.suiteXmlFiles") private File[] suiteXmlFiles; /** @@ -328,7 +347,7 @@ public class SurefirePlugin * * @since 2.7 */ - @Parameter( property = "surefire.runOrder", defaultValue = "filesystem" ) + @Parameter(property = "surefire.runOrder", defaultValue = "filesystem") private String runOrder; /** @@ -344,7 +363,7 @@ public class SurefirePlugin * * @since 3.0.0-M6 */ - @Parameter( property = "surefire.runOrder.random.seed" ) + @Parameter(property = "surefire.runOrder.random.seed") private Long runOrderRandomSeed; /** @@ -363,7 +382,7 @@ public class SurefirePlugin * * @since 2.13 */ - @Parameter( property = "surefire.includesFile" ) + @Parameter(property = "surefire.includesFile") private File includesFile; /** @@ -382,7 +401,7 @@ public class SurefirePlugin * * @since 2.13 */ - @Parameter( property = "surefire.excludesFile" ) + @Parameter(property = "surefire.excludesFile") private File excludesFile; /** @@ -396,7 +415,7 @@ public class SurefirePlugin * * @since 2.19 */ - @Parameter( property = "surefire.skipAfterFailureCount", defaultValue = "0" ) + @Parameter(property = "surefire.skipAfterFailureCount", defaultValue = "0") private int skipAfterFailureCount; /** @@ -416,7 +435,7 @@ public class SurefirePlugin * * @since 2.19 */ - @Parameter( property = "surefire.shutdown", defaultValue = "exit" ) + @Parameter(property = "surefire.shutdown", defaultValue = "exit") private String shutdown; /** @@ -427,7 +446,7 @@ public class SurefirePlugin * * @since 3.0.0-M2 */ - @Parameter( property = "surefire.useModulePath", defaultValue = "true" ) + @Parameter(property = "surefire.useModulePath", defaultValue = "true") private boolean useModulePath; /** @@ -442,7 +461,7 @@ public class SurefirePlugin * * @since 3.0.0-M5 */ - @Parameter( property = "surefire.forkNode" ) + @Parameter(property = "surefire.forkNode") private ForkNodeFactory forkNode; /** @@ -458,7 +477,7 @@ public class SurefirePlugin * * @since 3.0.0-M4 */ - @Parameter( property = "surefire.excludedEnvironmentVariables" ) + @Parameter(property = "surefire.excludedEnvironmentVariables") private String[] excludedEnvironmentVariables; /** @@ -499,10 +518,10 @@ public class SurefirePlugin * * @since 3.0.0-M4 */ - @Parameter( property = "surefire.enableProcessChecker" ) + @Parameter(property = "surefire.enableProcessChecker") private String enableProcessChecker; - @Parameter( property = "surefire.systemPropertiesFile" ) + @Parameter(property = "surefire.systemPropertiesFile") private File systemPropertiesFile; /** @@ -510,7 +529,7 @@ public class SurefirePlugin * * @since 3.0.0-M6 */ - @Parameter( property = "surefire.includeJUnit5Engines" ) + @Parameter(property = "surefire.includeJUnit5Engines") private String[] includeJUnit5Engines; /** @@ -518,498 +537,413 @@ public class SurefirePlugin * * @since 3.0.0-M6 */ - @Parameter( property = "surefire.excludeJUnit5Engines" ) + @Parameter(property = "surefire.excludeJUnit5Engines") private String[] excludeJUnit5Engines; @Override - protected int getRerunFailingTestsCount() - { + protected int getRerunFailingTestsCount() { return rerunFailingTestsCount; } @Override - public int getFailOnFlakeCount() - { + public int getFailOnFlakeCount() { return failOnFlakeCount; } @Override - public void setFailOnFlakeCount( int failOnFlakeCount ) - { + public void setFailOnFlakeCount(int failOnFlakeCount) { this.failOnFlakeCount = failOnFlakeCount; } @Override - protected void handleSummary( RunResult summary, Exception firstForkException ) - throws MojoExecutionException, MojoFailureException - { - reportExecution( this, summary, getConsoleLogger(), firstForkException ); + protected void handleSummary(RunResult summary, Exception firstForkException) + throws MojoExecutionException, MojoFailureException { + reportExecution(this, summary, getConsoleLogger(), firstForkException); } @Override - protected boolean isSkipExecution() - { + protected boolean isSkipExecution() { return isSkip() || isSkipTests() || isSkipExec(); } @Override - protected String getPluginName() - { + protected String getPluginName() { return "surefire"; } @Override - protected String[] getDefaultIncludes() - { - return new String[]{ "**/Test*.java", "**/*Test.java", "**/*Tests.java", "**/*TestCase.java" }; + protected String[] getDefaultIncludes() { + return new String[] {"**/Test*.java", "**/*Test.java", "**/*Tests.java", "**/*TestCase.java"}; } @Override - protected String getReportSchemaLocation() - { + protected String getReportSchemaLocation() { return "https://maven.apache.org/surefire/maven-surefire-plugin/xsd/surefire-test-report-3.0.xsd"; } - - public File getSystemPropertiesFile() - { + public File getSystemPropertiesFile() { return systemPropertiesFile; } - - public void setSystemPropertiesFile( File systemPropertiesFile ) - { + public void setSystemPropertiesFile(File systemPropertiesFile) { this.systemPropertiesFile = systemPropertiesFile; } - // now for the implementation of the field accessors @Override - public boolean isSkipTests() - { + public boolean isSkipTests() { return skipTests; } @Override - public void setSkipTests( boolean skipTests ) - { + public void setSkipTests(boolean skipTests) { this.skipTests = skipTests; } @Override @Deprecated - public boolean isSkipExec() - { + public boolean isSkipExec() { return skipExec; } @Override @Deprecated - public void setSkipExec( boolean skipExec ) - { + public void setSkipExec(boolean skipExec) { this.skipExec = skipExec; } @Override - public boolean isSkip() - { + public boolean isSkip() { return skip; } @Override - public void setSkip( boolean skip ) - { + public void setSkip(boolean skip) { this.skip = skip; } @Override - public boolean isTestFailureIgnore() - { + public boolean isTestFailureIgnore() { return testFailureIgnore; } @Override - public void setTestFailureIgnore( boolean testFailureIgnore ) - { + public void setTestFailureIgnore(boolean testFailureIgnore) { this.testFailureIgnore = testFailureIgnore; } @Override - public File getBasedir() - { + public File getBasedir() { return basedir; } @Override - public void setBasedir( File basedir ) - { + public void setBasedir(File basedir) { this.basedir = basedir; } @Override - public File getTestClassesDirectory() - { + public File getTestClassesDirectory() { return testClassesDirectory; } @Override - public void setTestClassesDirectory( File testClassesDirectory ) - { + public void setTestClassesDirectory(File testClassesDirectory) { this.testClassesDirectory = testClassesDirectory; } @Override - public File getMainBuildPath() - { + public File getMainBuildPath() { return classesDirectory; } @Override - public void setMainBuildPath( File mainBuildPath ) - { + public void setMainBuildPath(File mainBuildPath) { classesDirectory = mainBuildPath; } @Override - public File getReportsDirectory() - { + public File getReportsDirectory() { return reportsDirectory; } @Override - public void setReportsDirectory( File reportsDirectory ) - { + public void setReportsDirectory(File reportsDirectory) { this.reportsDirectory = reportsDirectory; } @Override - public String getTest() - { + public String getTest() { return test; } @Override - public boolean isUseSystemClassLoader() - { + public boolean isUseSystemClassLoader() { return useSystemClassLoader; } @Override - public void setUseSystemClassLoader( boolean useSystemClassLoader ) - { + public void setUseSystemClassLoader(boolean useSystemClassLoader) { this.useSystemClassLoader = useSystemClassLoader; } @Override - public boolean isUseManifestOnlyJar() - { + public boolean isUseManifestOnlyJar() { return useManifestOnlyJar; } @Override - public void setUseManifestOnlyJar( boolean useManifestOnlyJar ) - { + public void setUseManifestOnlyJar(boolean useManifestOnlyJar) { this.useManifestOnlyJar = useManifestOnlyJar; } @Override - public String getEncoding() - { + public String getEncoding() { return encoding; } @Override - public void setEncoding( String encoding ) - { + public void setEncoding(String encoding) { this.encoding = encoding; } @Override - public boolean getFailIfNoSpecifiedTests() - { + public boolean getFailIfNoSpecifiedTests() { return failIfNoSpecifiedTests; } @Override - public void setFailIfNoSpecifiedTests( boolean failIfNoSpecifiedTests ) - { + public void setFailIfNoSpecifiedTests(boolean failIfNoSpecifiedTests) { this.failIfNoSpecifiedTests = failIfNoSpecifiedTests; } @Override - public int getSkipAfterFailureCount() - { + public int getSkipAfterFailureCount() { return skipAfterFailureCount; } @Override - public String getShutdown() - { + public String getShutdown() { return shutdown; } @Override - public boolean isPrintSummary() - { + public boolean isPrintSummary() { return printSummary; } @Override - public void setPrintSummary( boolean printSummary ) - { + public void setPrintSummary(boolean printSummary) { this.printSummary = printSummary; } @Override - public String getReportFormat() - { + public String getReportFormat() { return reportFormat; } @Override - public void setReportFormat( String reportFormat ) - { + public void setReportFormat(String reportFormat) { this.reportFormat = reportFormat; } @Override - public boolean isUseFile() - { + public boolean isUseFile() { return useFile; } @Override - public void setUseFile( boolean useFile ) - { + public void setUseFile(boolean useFile) { this.useFile = useFile; } @Override - public String getDebugForkedProcess() - { + public String getDebugForkedProcess() { return debugForkedProcess; } @Override - public void setDebugForkedProcess( String debugForkedProcess ) - { + public void setDebugForkedProcess(String debugForkedProcess) { this.debugForkedProcess = debugForkedProcess; } @Override - public int getForkedProcessTimeoutInSeconds() - { + public int getForkedProcessTimeoutInSeconds() { return forkedProcessTimeoutInSeconds; } @Override - public void setForkedProcessTimeoutInSeconds( int forkedProcessTimeoutInSeconds ) - { + public void setForkedProcessTimeoutInSeconds(int forkedProcessTimeoutInSeconds) { this.forkedProcessTimeoutInSeconds = forkedProcessTimeoutInSeconds; } @Override - public int getForkedProcessExitTimeoutInSeconds() - { + public int getForkedProcessExitTimeoutInSeconds() { return forkedProcessExitTimeoutInSeconds; } @Override - public void setForkedProcessExitTimeoutInSeconds( int forkedProcessExitTimeoutInSeconds ) - { + public void setForkedProcessExitTimeoutInSeconds(int forkedProcessExitTimeoutInSeconds) { this.forkedProcessExitTimeoutInSeconds = forkedProcessExitTimeoutInSeconds; } @Override - public double getParallelTestsTimeoutInSeconds() - { + public double getParallelTestsTimeoutInSeconds() { return parallelTestsTimeoutInSeconds; } @Override - public void setParallelTestsTimeoutInSeconds( double parallelTestsTimeoutInSeconds ) - { + public void setParallelTestsTimeoutInSeconds(double parallelTestsTimeoutInSeconds) { this.parallelTestsTimeoutInSeconds = parallelTestsTimeoutInSeconds; } @Override - public double getParallelTestsTimeoutForcedInSeconds() - { + public double getParallelTestsTimeoutForcedInSeconds() { return parallelTestsTimeoutForcedInSeconds; } @Override - public void setParallelTestsTimeoutForcedInSeconds( double parallelTestsTimeoutForcedInSeconds ) - { + public void setParallelTestsTimeoutForcedInSeconds(double parallelTestsTimeoutForcedInSeconds) { this.parallelTestsTimeoutForcedInSeconds = parallelTestsTimeoutForcedInSeconds; } @Override - public void setTest( String test ) - { + public void setTest(String test) { this.test = test; } @Override - public List getIncludes() - { + public List getIncludes() { return includes; } @Override - public void setIncludes( List includes ) - { + public void setIncludes(List includes) { this.includes = includes; } @Override - public List getExcludes() - { + public List getExcludes() { return excludes; } @Override - public void setExcludes( List excludes ) - { + public void setExcludes(List excludes) { this.excludes = excludes; } @Override - public File[] getSuiteXmlFiles() - { + public File[] getSuiteXmlFiles() { return suiteXmlFiles.clone(); } @Override - @SuppressWarnings( "UnusedDeclaration" ) - public void setSuiteXmlFiles( File[] suiteXmlFiles ) - { + @SuppressWarnings("UnusedDeclaration") + public void setSuiteXmlFiles(File[] suiteXmlFiles) { this.suiteXmlFiles = suiteXmlFiles.clone(); } @Override - public String getRunOrder() - { + public String getRunOrder() { return runOrder; } @Override - @SuppressWarnings( "UnusedDeclaration" ) - public void setRunOrder( String runOrder ) - { + @SuppressWarnings("UnusedDeclaration") + public void setRunOrder(String runOrder) { this.runOrder = runOrder; } @Override - public Long getRunOrderRandomSeed() - { + public Long getRunOrderRandomSeed() { return runOrderRandomSeed; } @Override - public void setRunOrderRandomSeed( Long runOrderRandomSeed ) - { + public void setRunOrderRandomSeed(Long runOrderRandomSeed) { this.runOrderRandomSeed = runOrderRandomSeed; } @Override - public File getIncludesFile() - { + public File getIncludesFile() { return includesFile; } @Override - public File getExcludesFile() - { + public File getExcludesFile() { return excludesFile; } @Override - protected boolean useModulePath() - { + protected boolean useModulePath() { return useModulePath; } @Override - protected void setUseModulePath( boolean useModulePath ) - { + protected void setUseModulePath(boolean useModulePath) { this.useModulePath = useModulePath; } @Override - protected final List suiteXmlFiles() - { - return hasSuiteXmlFiles() ? Arrays.asList( suiteXmlFiles ) : Collections.emptyList(); + protected final List suiteXmlFiles() { + return hasSuiteXmlFiles() ? Arrays.asList(suiteXmlFiles) : Collections.emptyList(); } @Override - protected final boolean hasSuiteXmlFiles() - { + protected final boolean hasSuiteXmlFiles() { return suiteXmlFiles != null && suiteXmlFiles.length != 0; } @Override - protected final String[] getExcludedEnvironmentVariables() - { + protected final String[] getExcludedEnvironmentVariables() { return excludedEnvironmentVariables == null ? new String[0] : excludedEnvironmentVariables; } - void setExcludedEnvironmentVariables( String[] excludedEnvironmentVariables ) - { + void setExcludedEnvironmentVariables(String[] excludedEnvironmentVariables) { this.excludedEnvironmentVariables = excludedEnvironmentVariables; } @Override - protected final String getEnableProcessChecker() - { + protected final String getEnableProcessChecker() { return enableProcessChecker; } @Override - protected final ForkNodeFactory getForkNode() - { + protected final ForkNodeFactory getForkNode() { return forkNode; } @Override - protected void warnIfIllegalFailOnFlakeCount() throws MojoFailureException - { - if ( failOnFlakeCount < 0 ) - { - throw new MojoFailureException( "Parameter \"failOnFlakeCount\" should not be negative." ); + protected void warnIfIllegalFailOnFlakeCount() throws MojoFailureException { + if (failOnFlakeCount < 0) { + throw new MojoFailureException("Parameter \"failOnFlakeCount\" should not be negative."); } - if ( failOnFlakeCount > 0 && rerunFailingTestsCount < 1 ) - { - throw new MojoFailureException( "\"failOnFlakeCount\" requires rerunFailingTestsCount to be at least 1." ); + if (failOnFlakeCount > 0 && rerunFailingTestsCount < 1) { + throw new MojoFailureException("\"failOnFlakeCount\" requires rerunFailingTestsCount to be at least 1."); } } @Override - protected void addPluginSpecificChecksumItems( ChecksumCalculator checksum ) - { - checksum.add( skipAfterFailureCount ); + protected void addPluginSpecificChecksumItems(ChecksumCalculator checksum) { + checksum.add(skipAfterFailureCount); } - public String[] getIncludeJUnit5Engines() - { + public String[] getIncludeJUnit5Engines() { return includeJUnit5Engines; } - @SuppressWarnings( "UnusedDeclaration" ) - public void setIncludeJUnit5Engines( String[] includeJUnit5Engines ) - { + @SuppressWarnings("UnusedDeclaration") + public void setIncludeJUnit5Engines(String[] includeJUnit5Engines) { this.includeJUnit5Engines = includeJUnit5Engines; } - public String[] getExcludeJUnit5Engines() - { + public String[] getExcludeJUnit5Engines() { return excludeJUnit5Engines; } - @SuppressWarnings( "UnusedDeclaration" ) - public void setExcludeJUnit5Engines( String[] excludeJUnit5Engines ) - { + @SuppressWarnings("UnusedDeclaration") + public void setExcludeJUnit5Engines(String[] excludeJUnit5Engines) { this.excludeJUnit5Engines = excludeJUnit5Engines; } } diff --git a/maven-surefire-plugin/src/test/java/org/apache/maven/plugin/surefire/SurefirePluginTest.java b/maven-surefire-plugin/src/test/java/org/apache/maven/plugin/surefire/SurefirePluginTest.java index 5015bc0144..d2c3ffe38e 100644 --- a/maven-surefire-plugin/src/test/java/org/apache/maven/plugin/surefire/SurefirePluginTest.java +++ b/maven-surefire-plugin/src/test/java/org/apache/maven/plugin/surefire/SurefirePluginTest.java @@ -1,3 +1,21 @@ +/* + * 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.maven.plugin.surefire; /* @@ -19,131 +37,108 @@ * under the License. */ +import java.io.File; + import junit.framework.TestCase; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.surefire.api.suite.RunResult; import org.junit.Rule; import org.junit.rules.ExpectedException; -import java.io.File; - import static org.assertj.core.api.Assertions.assertThat; /** * */ -public class SurefirePluginTest extends TestCase -{ +public class SurefirePluginTest extends TestCase { @Rule public final ExpectedException e = ExpectedException.none(); - public void testDefaultIncludes() - { - assertThat( new SurefirePlugin().getDefaultIncludes() ) - .containsOnly( "**/Test*.java", "**/*Test.java", "**/*Tests.java", "**/*TestCase.java" ); + public void testDefaultIncludes() { + assertThat(new SurefirePlugin().getDefaultIncludes()) + .containsOnly("**/Test*.java", "**/*Test.java", "**/*Tests.java", "**/*TestCase.java"); } - public void testReportSchemaLocation() - { - assertThat( new SurefirePlugin().getReportSchemaLocation() ) - .isEqualTo( "https://maven.apache.org/surefire/maven-surefire-plugin/xsd/surefire-test-report-3.0.xsd" ); + public void testReportSchemaLocation() { + assertThat(new SurefirePlugin().getReportSchemaLocation()) + .isEqualTo("https://maven.apache.org/surefire/maven-surefire-plugin/xsd/surefire-test-report-3.0.xsd"); } - public void testFailIfNoTests() throws Exception - { - RunResult runResult = new RunResult( 0, 0, 0, 0 ); - try - { + public void testFailIfNoTests() throws Exception { + RunResult runResult = new RunResult(0, 0, 0, 0); + try { SurefirePlugin plugin = new SurefirePlugin(); - plugin.setFailIfNoTests( true ); - plugin.handleSummary( runResult, null ); - } - catch ( MojoFailureException e ) - { - assertThat( e.getLocalizedMessage() ) - .isEqualTo( "No tests were executed! (Set -DfailIfNoTests=false to ignore this error.)" ); + plugin.setFailIfNoTests(true); + plugin.handleSummary(runResult, null); + } catch (MojoFailureException e) { + assertThat(e.getLocalizedMessage()) + .isEqualTo("No tests were executed! (Set -DfailIfNoTests=false to ignore this error.)"); return; } - fail( "Expected MojoFailureException with message " - + "'No tests were executed! (Set -DfailIfNoTests=false to ignore this error.)'" ); + fail("Expected MojoFailureException with message " + + "'No tests were executed! (Set -DfailIfNoTests=false to ignore this error.)'"); } - public void testTestFailure() throws Exception - { - RunResult runResult = new RunResult( 1, 0, 1, 0 ); - try - { + public void testTestFailure() throws Exception { + RunResult runResult = new RunResult(1, 0, 1, 0); + try { SurefirePlugin plugin = new SurefirePlugin(); - plugin.handleSummary( runResult, null ); - } - catch ( MojoFailureException e ) - { - assertThat( e.getLocalizedMessage() ) - .isEqualTo( "There are test failures.\n\nPlease refer to null " + plugin.handleSummary(runResult, null); + } catch (MojoFailureException e) { + assertThat(e.getLocalizedMessage()) + .isEqualTo("There are test failures.\n\nPlease refer to null " + "for the individual test results.\nPlease refer to dump files (if any exist) " - + "[date].dump, [date]-jvmRun[N].dump and [date].dumpstream." ); + + "[date].dump, [date]-jvmRun[N].dump and [date].dumpstream."); return; } - fail( "Expected MojoFailureException with message " + fail("Expected MojoFailureException with message " + "'There are test failures.\n\nPlease refer to null " + "for the individual test results.\nPlease refer to dump files (if any exist) " - + "[date].dump, [date]-jvmRun[N].dump and [date].dumpstream.'" ); + + "[date].dump, [date]-jvmRun[N].dump and [date].dumpstream.'"); } - public void testPluginName() - { - assertThat( new SurefirePlugin().getPluginName() ) - .isEqualTo( "surefire" ); + public void testPluginName() { + assertThat(new SurefirePlugin().getPluginName()).isEqualTo("surefire"); } - public void testShouldGetNullEnv() - { + public void testShouldGetNullEnv() { SurefirePlugin plugin = new SurefirePlugin(); - assertThat( plugin.getExcludedEnvironmentVariables() ) - .hasSize( 0 ); + assertThat(plugin.getExcludedEnvironmentVariables()).hasSize(0); } - public void testShouldGetEnv() - { + public void testShouldGetEnv() { SurefirePlugin plugin = new SurefirePlugin(); - plugin.setExcludedEnvironmentVariables( new String[] { "ABC", "KLM" } ); - assertThat( plugin.getExcludedEnvironmentVariables() ) - .hasSize( 2 ) - .contains( "ABC", "KLM" ); + plugin.setExcludedEnvironmentVariables(new String[] {"ABC", "KLM"}); + assertThat(plugin.getExcludedEnvironmentVariables()).hasSize(2).contains("ABC", "KLM"); } - public void testShouldGetPropertyFile() - { + public void testShouldGetPropertyFile() { SurefirePlugin plugin = new SurefirePlugin(); - plugin.setSystemPropertiesFile( new File( "testShouldGetPropertyFile" ) ); - assertThat( plugin.getSystemPropertiesFile() ) - .isEqualTo( new File( "testShouldGetPropertyFile" ) ); + plugin.setSystemPropertiesFile(new File("testShouldGetPropertyFile")); + assertThat(plugin.getSystemPropertiesFile()).isEqualTo(new File("testShouldGetPropertyFile")); } - public void testNegativeFailOnFlakeCount() - { + public void testNegativeFailOnFlakeCount() { SurefirePlugin plugin = new SurefirePlugin(); - plugin.setFailOnFlakeCount( -1 ); - e.expect( MojoFailureException.class ); - e.expectMessage( "Parameter \"failOnFlakeCount\" should not be negative." ); + plugin.setFailOnFlakeCount(-1); + e.expect(MojoFailureException.class); + e.expectMessage("Parameter \"failOnFlakeCount\" should not be negative."); } - public void testFailOnFlakeCountWithoutRerun() - { + public void testFailOnFlakeCountWithoutRerun() { SurefirePlugin plugin = new SurefirePlugin(); - plugin.setFailOnFlakeCount( 1 ); - e.expect( MojoFailureException.class ); - e.expectMessage( "\"failOnFlakeCount\" requires rerunFailingTestsCount to be at least 1." ); + plugin.setFailOnFlakeCount(1); + e.expect(MojoFailureException.class); + e.expectMessage("\"failOnFlakeCount\" requires rerunFailingTestsCount to be at least 1."); } - public void testShouldHaveJUnit5EnginesFilter() - { + public void testShouldHaveJUnit5EnginesFilter() { SurefirePlugin plugin = new SurefirePlugin(); - plugin.setIncludeJUnit5Engines( new String[] { "e1", "e2" } ); - assertThat( plugin.getIncludeJUnit5Engines() ).isEqualTo( new String[] { "e1", "e2" } ); + plugin.setIncludeJUnit5Engines(new String[] {"e1", "e2"}); + assertThat(plugin.getIncludeJUnit5Engines()).isEqualTo(new String[] {"e1", "e2"}); - plugin.setExcludeJUnit5Engines( new String[] { "e1", "e2" } ); - assertThat( plugin.getExcludeJUnit5Engines() ).isEqualTo( new String[] { "e1", "e2" } ); + plugin.setExcludeJUnit5Engines(new String[] {"e1", "e2"}); + assertThat(plugin.getExcludeJUnit5Engines()).isEqualTo(new String[] {"e1", "e2"}); } } diff --git a/maven-surefire-report-plugin/pom.xml b/maven-surefire-report-plugin/pom.xml index 72910a62b6..48577238ff 100644 --- a/maven-surefire-report-plugin/pom.xml +++ b/maven-surefire-report-plugin/pom.xml @@ -17,236 +17,236 @@ ~ specific language governing permissions and limitations ~ under the License. --> - - 4.0.0 + 4.0.0 + + + org.apache.maven.surefire + surefire + 3.0.0-M10-SNAPSHOT + - - org.apache.maven.surefire - surefire - 3.0.0-M10-SNAPSHOT - + org.apache.maven.plugins + maven-surefire-report-plugin + maven-plugin - org.apache.maven.plugins - maven-surefire-report-plugin - maven-plugin + Maven Surefire Report Plugin + Maven Surefire Report MOJO in maven-surefire-report-plugin. - Maven Surefire Report Plugin - Maven Surefire Report MOJO in maven-surefire-report-plugin. + + + jruiz + Johnny Ruiz III + jruiz@exist.com + + - - - jruiz - Johnny Ruiz III - jruiz@exist.com - - + + ${mavenVersion} + - - ${mavenVersion} - + + 1.11.1 + 1.0.0.v20140518 + - - 1.11.1 - 1.0.0.v20140518 - + + + org.apache.maven.surefire + surefire-report-parser + ${project.version} + + + org.apache.maven + maven-core + provided + + + org.apache.maven + maven-model + provided + + + org.apache.maven + maven-plugin-api + provided + + + org.apache.maven.plugin-tools + maven-plugin-annotations + provided + + + org.apache.maven.doxia + doxia-sink-api + ${doxiaVersion} + + + org.apache.maven.doxia + doxia-core + ${doxiaVersion} + + + org.apache.maven.reporting + maven-reporting-api + + + org.apache.maven.reporting + maven-reporting-impl + + + org.fusesource.jansi + jansi + provided + + + commons-io + commons-io + test + + + org.apache.maven.plugin-testing + maven-plugin-testing-harness + test + + + org.apache.maven + maven-compat + test + + + org.xmlunit + xmlunit-core + test + + + org.eclipse.aether + aether-impl + ${aetherVersion} + test + + + org.eclipse.aether + aether-connector-basic + ${aetherVersion} + test + + + org.eclipse.aether + aether-transport-wagon + ${aetherVersion} + test + + + org.apache.maven.wagon + wagon-http-lightweight + 3.5.1 + test + + + org.slf4j + slf4j-simple + 1.7.36 + test + + - - + + + + org.apache.maven.plugins + maven-plugin-plugin + + + org.jacoco + jacoco-maven-plugin + + jacoco.agent + + + + jacoco-agent + + prepare-agent + + + + + + maven-surefire-plugin + + ${jvm.args.tests} ${jacoco.agent} + + **/JUnit4SuiteTest.java + + + org.fusesource.jansi:jansi + + + + org.apache.maven.surefire - surefire-report-parser - ${project.version} - - - org.apache.maven - maven-core - provided - - - org.apache.maven - maven-model - provided - - - org.apache.maven - maven-plugin-api - provided - - - org.apache.maven.plugin-tools - maven-plugin-annotations - provided - - - org.apache.maven.doxia - doxia-sink-api - ${doxiaVersion} - - - org.apache.maven.doxia - doxia-core - ${doxiaVersion} - - - org.apache.maven.reporting - maven-reporting-api - - - org.apache.maven.reporting - maven-reporting-impl - - - org.fusesource.jansi - jansi - provided - - - commons-io - commons-io - test - - - org.apache.maven.plugin-testing - maven-plugin-testing-harness - test - - - org.apache.maven - maven-compat - test - - - org.xmlunit - xmlunit-core - test - - - org.eclipse.aether - aether-impl - ${aetherVersion} - test - - - org.eclipse.aether - aether-connector-basic - ${aetherVersion} - test - - - org.eclipse.aether - aether-transport-wagon - ${aetherVersion} - test - - - org.apache.maven.wagon - wagon-http-lightweight - 3.5.1 - test - - - org.slf4j - slf4j-simple - 1.7.36 - test - - + surefire-shadefire + 3.0.0-M7 + + + + + + + + + + + maven-plugin-plugin + + + - + + + ci + + + enableCiProfile + true + + + - - org.apache.maven.plugins - maven-plugin-plugin - - - org.jacoco - jacoco-maven-plugin - - - jacoco-agent - - prepare-agent - - - - - jacoco.agent - - - - maven-surefire-plugin - - ${jvm.args.tests} ${jacoco.agent} - - **/JUnit4SuiteTest.java - - - org.fusesource.jansi:jansi - - - - - org.apache.maven.surefire - surefire-shadefire - 3.0.0-M7 - - - + + maven-docck-plugin + 1.1 + + + + check + + + + - - - + + + + reporting + - - maven-plugin-plugin - + + maven-changes-plugin + + false + + + + + jira-report + + + + - - - - - ci - - - enableCiProfile - true - - - - - - maven-docck-plugin - 1.1 - - - - check - - - - - - - - - reporting - - - - maven-changes-plugin - - false - - - - - jira-report - - - - - - - - + + + diff --git a/maven-surefire-report-plugin/src/main/java/org/apache/maven/plugins/surefire/report/AbstractSurefireReportMojo.java b/maven-surefire-report-plugin/src/main/java/org/apache/maven/plugins/surefire/report/AbstractSurefireReportMojo.java index ae69f181a2..05e5858aa8 100644 --- a/maven-surefire-report-plugin/src/main/java/org/apache/maven/plugins/surefire/report/AbstractSurefireReportMojo.java +++ b/maven-surefire-report-plugin/src/main/java/org/apache/maven/plugins/surefire/report/AbstractSurefireReportMojo.java @@ -1,3 +1,21 @@ +/* + * 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.maven.plugins.surefire.report; /* @@ -24,6 +42,7 @@ import java.util.Iterator; import java.util.List; import java.util.Locale; + import org.apache.maven.model.ReportPlugin; import org.apache.maven.plugin.surefire.log.api.ConsoleLogger; import org.apache.maven.plugins.annotations.Parameter; @@ -41,14 +60,12 @@ * * @author Stephen Connolly */ -public abstract class AbstractSurefireReportMojo - extends AbstractMavenReport -{ +public abstract class AbstractSurefireReportMojo extends AbstractMavenReport { /** * If set to false, only failures are shown. */ - @Parameter( defaultValue = "true", required = true, property = "showSuccess" ) + @Parameter(defaultValue = "true", required = true, property = "showSuccess") private boolean showSuccess; /** @@ -68,25 +85,25 @@ public abstract class AbstractSurefireReportMojo /** * The projects in the reactor for aggregation report. */ - @Parameter( defaultValue = "${reactorProjects}", readonly = true ) + @Parameter(defaultValue = "${reactorProjects}", readonly = true) private List reactorProjects; /** * Location of the Xrefs to link. */ - @Parameter( defaultValue = "${project.reporting.outputDirectory}/xref-test" ) + @Parameter(defaultValue = "${project.reporting.outputDirectory}/xref-test") private File xrefLocation; /** * Whether to link the XRef if found. */ - @Parameter( defaultValue = "true", property = "linkXRef" ) + @Parameter(defaultValue = "true", property = "linkXRef") private boolean linkXRef; /** * Whether to build an aggregated report at the root, or build individual reports. */ - @Parameter( defaultValue = "false", property = "aggregate" ) + @Parameter(defaultValue = "false", property = "aggregate") private boolean aggregate; private List resolvedReportsDirectories; @@ -97,8 +114,7 @@ public abstract class AbstractSurefireReportMojo * @return {@code true} if and only if the report should be generated. * @since 2.11 */ - protected boolean isSkipped() - { + protected boolean isSkipped() { return false; } @@ -108,16 +124,15 @@ protected boolean isSkipped() * @return {@code true} if and only if the report should be generated when there are no result files at all. * @since 2.11 */ - protected boolean isGeneratedWhenNoResults() - { + protected boolean isGeneratedWhenNoResults() { return false; } - public abstract void setTitle( String title ); + public abstract void setTitle(String title); public abstract String getTitle(); - public abstract void setDescription( String description ); + public abstract void setDescription(String description); public abstract String getDescription(); @@ -125,124 +140,94 @@ protected boolean isGeneratedWhenNoResults() * {@inheritDoc} */ @Override - public void executeReport( Locale locale ) - throws MavenReportException - { - if ( !hasReportDirectories() ) - { + public void executeReport(Locale locale) throws MavenReportException { + if (!hasReportDirectories()) { return; } - new SurefireReportGenerator( getReportsDirectories(), locale, showSuccess, determineXrefLocation(), - getConsoleLogger() ) - .doGenerateReport( getBundle( locale ), getSink() ); + new SurefireReportGenerator( + getReportsDirectories(), locale, showSuccess, determineXrefLocation(), getConsoleLogger()) + .doGenerateReport(getBundle(locale), getSink()); } @Override - public boolean canGenerateReport() - { + public boolean canGenerateReport() { return hasReportDirectories() && super.canGenerateReport(); } - private boolean hasReportDirectories() - { - if ( isSkipped() ) - { + private boolean hasReportDirectories() { + if (isSkipped()) { return false; } final List reportsDirectories = getReportsDirectories(); - if ( reportsDirectories == null ) - { + if (reportsDirectories == null) { return false; } - if ( !isGeneratedWhenNoResults() ) - { + if (!isGeneratedWhenNoResults()) { boolean atLeastOneDirectoryExists = false; - for ( Iterator i = reportsDirectories.iterator(); i.hasNext() && !atLeastOneDirectoryExists; ) - { - atLeastOneDirectoryExists = hasReportFiles( i.next() ); + for (Iterator i = reportsDirectories.iterator(); i.hasNext() && !atLeastOneDirectoryExists; ) { + atLeastOneDirectoryExists = hasReportFiles(i.next()); } - if ( !atLeastOneDirectoryExists ) - { + if (!atLeastOneDirectoryExists) { return false; } } return true; } - private List getReportsDirectories() - { - if ( resolvedReportsDirectories != null ) - { + private List getReportsDirectories() { + if (resolvedReportsDirectories != null) { return resolvedReportsDirectories; } resolvedReportsDirectories = new ArrayList<>(); - if ( this.reportsDirectories != null ) - { - addAll( resolvedReportsDirectories, this.reportsDirectories ); + if (this.reportsDirectories != null) { + addAll(resolvedReportsDirectories, this.reportsDirectories); } //noinspection deprecation - if ( reportsDirectory != null ) - { + if (reportsDirectory != null) { //noinspection deprecation - resolvedReportsDirectories.add( reportsDirectory ); + resolvedReportsDirectories.add(reportsDirectory); } - if ( aggregate ) - { - if ( !project.isExecutionRoot() ) - { + if (aggregate) { + if (!project.isExecutionRoot()) { return null; } - if ( this.reportsDirectories == null ) - { - if ( reactorProjects.size() > 1 ) - { - for ( MavenProject mavenProject : getProjectsWithoutRoot() ) - { - resolvedReportsDirectories.add( getSurefireReportsDirectory( mavenProject ) ); + if (this.reportsDirectories == null) { + if (reactorProjects.size() > 1) { + for (MavenProject mavenProject : getProjectsWithoutRoot()) { + resolvedReportsDirectories.add(getSurefireReportsDirectory(mavenProject)); } + } else { + resolvedReportsDirectories.add(getSurefireReportsDirectory(project)); } - else - { - resolvedReportsDirectories.add( getSurefireReportsDirectory( project ) ); - } - } - else - { + } else { // Multiple report directories are configured. // Let's see if those directories exist in each sub-module to fix SUREFIRE-570 String parentBaseDir = getProject().getBasedir().getAbsolutePath(); - for ( MavenProject subProject : getProjectsWithoutRoot() ) - { + for (MavenProject subProject : getProjectsWithoutRoot()) { String moduleBaseDir = subProject.getBasedir().getAbsolutePath(); - for ( File reportsDirectory1 : this.reportsDirectories ) - { + for (File reportsDirectory1 : this.reportsDirectories) { String reportDir = reportsDirectory1.getPath(); - if ( reportDir.startsWith( parentBaseDir ) ) - { - reportDir = reportDir.substring( parentBaseDir.length() ); + if (reportDir.startsWith(parentBaseDir)) { + reportDir = reportDir.substring(parentBaseDir.length()); } - File reportsDirectory = new File( moduleBaseDir, reportDir ); - if ( reportsDirectory.exists() && reportsDirectory.isDirectory() ) - { - getConsoleLogger().debug( "Adding report dir : " + moduleBaseDir + reportDir ); - resolvedReportsDirectories.add( reportsDirectory ); + File reportsDirectory = new File(moduleBaseDir, reportDir); + if (reportsDirectory.exists() && reportsDirectory.isDirectory()) { + getConsoleLogger().debug("Adding report dir : " + moduleBaseDir + reportDir); + resolvedReportsDirectories.add(reportsDirectory); } } } } - } - else - { - if ( resolvedReportsDirectories.isEmpty() ) - { + } else { + if (resolvedReportsDirectories.isEmpty()) { - resolvedReportsDirectories.add( getSurefireReportsDirectory( project ) ); + resolvedReportsDirectories.add(getSurefireReportsDirectory(project)); } } return resolvedReportsDirectories; @@ -254,57 +239,44 @@ private List getReportsDirectories() * @param subProject the project to query. * @return the default surefire reports directory for the specified project. */ - protected abstract File getSurefireReportsDirectory( MavenProject subProject ); + protected abstract File getSurefireReportsDirectory(MavenProject subProject); - private List getProjectsWithoutRoot() - { + private List getProjectsWithoutRoot() { List result = new ArrayList<>(); - for ( MavenProject subProject : reactorProjects ) - { - if ( !project.equals( subProject ) ) - { - result.add( subProject ); + for (MavenProject subProject : reactorProjects) { + if (!project.equals(subProject)) { + result.add(subProject); } } return result; - } - private String determineXrefLocation() - { + private String determineXrefLocation() { String location = null; - if ( linkXRef ) - { - String relativePath = PathTool.getRelativePath( getOutputDirectory(), xrefLocation.getAbsolutePath() ); - if ( isEmpty( relativePath ) ) - { + if (linkXRef) { + String relativePath = PathTool.getRelativePath(getOutputDirectory(), xrefLocation.getAbsolutePath()); + if (isEmpty(relativePath)) { relativePath = "."; } relativePath = relativePath + "/" + xrefLocation.getName(); - if ( xrefLocation.exists() ) - { + if (xrefLocation.exists()) { // XRef was already generated by manual execution of a lifecycle binding location = relativePath; - } - else - { + } else { // Not yet generated - check if the report is on its way - for ( Object o : project.getReportPlugins() ) - { + for (Object o : project.getReportPlugins()) { ReportPlugin report = (ReportPlugin) o; String artifactId = report.getArtifactId(); - if ( "maven-jxr-plugin".equals( artifactId ) || "jxr-maven-plugin".equals( artifactId ) ) - { + if ("maven-jxr-plugin".equals(artifactId) || "jxr-maven-plugin".equals(artifactId)) { location = relativePath; } } } - if ( location == null ) - { - getConsoleLogger().warning( "Unable to locate Test Source XRef to link to - DISABLED" ); + if (location == null) { + getConsoleLogger().warning("Unable to locate Test Source XRef to link to - DISABLED"); } } return location; @@ -314,18 +286,16 @@ private String determineXrefLocation() * {@inheritDoc} */ @Override - public String getName( Locale locale ) - { - return getBundle( locale ).getReportName(); + public String getName(Locale locale) { + return getBundle(locale).getReportName(); } /** * {@inheritDoc} */ @Override - public String getDescription( Locale locale ) - { - return getBundle( locale ).getReportDescription(); + public String getDescription(Locale locale) { + return getBundle(locale).getReportDescription(); } /** @@ -334,21 +304,18 @@ public String getDescription( Locale locale ) @Override public abstract String getOutputName(); - protected abstract LocalizedProperties getBundle( Locale locale, ClassLoader resourceBundleClassLoader ); + protected abstract LocalizedProperties getBundle(Locale locale, ClassLoader resourceBundleClassLoader); - protected final ConsoleLogger getConsoleLogger() - { - return new PluginConsoleLogger( getLog() ); + protected final ConsoleLogger getConsoleLogger() { + return new PluginConsoleLogger(getLog()); } - final LocalizedProperties getBundle( Locale locale ) - { - return getBundle( locale, getClass().getClassLoader() ); + final LocalizedProperties getBundle(Locale locale) { + return getBundle(locale, getClass().getClassLoader()); } @Override - protected MavenProject getProject() - { + protected MavenProject getProject() { return project; } } diff --git a/maven-surefire-report-plugin/src/main/java/org/apache/maven/plugins/surefire/report/FailsafeReportMojo.java b/maven-surefire-report-plugin/src/main/java/org/apache/maven/plugins/surefire/report/FailsafeReportMojo.java index ea9786a4f9..3d8b733f89 100644 --- a/maven-surefire-report-plugin/src/main/java/org/apache/maven/plugins/surefire/report/FailsafeReportMojo.java +++ b/maven-surefire-report-plugin/src/main/java/org/apache/maven/plugins/surefire/report/FailsafeReportMojo.java @@ -1,3 +1,21 @@ +/* + * 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.maven.plugins.surefire.report; /* @@ -19,14 +37,14 @@ * under the License. */ -import org.apache.maven.plugins.annotations.Mojo; -import org.apache.maven.plugins.annotations.Parameter; -import org.apache.maven.project.MavenProject; - import java.io.File; import java.util.Locale; import java.util.ResourceBundle; +import org.apache.maven.plugins.annotations.Mojo; +import org.apache.maven.plugins.annotations.Parameter; +import org.apache.maven.project.MavenProject; + import static org.apache.maven.shared.utils.StringUtils.isEmpty; /** @@ -38,16 +56,14 @@ * @author Stephen Connolly * @since 2.10 */ -@Mojo( name = "failsafe-report-only" ) -@SuppressWarnings( "unused" ) -public class FailsafeReportMojo - extends AbstractSurefireReportMojo -{ +@Mojo(name = "failsafe-report-only") +@SuppressWarnings("unused") +public class FailsafeReportMojo extends AbstractSurefireReportMojo { /** * The filename to use for the report. */ - @Parameter( defaultValue = "failsafe-report", property = "outputName", required = true ) + @Parameter(defaultValue = "failsafe-report", property = "outputName", required = true) private String outputName; /** @@ -55,105 +71,95 @@ public class FailsafeReportMojo * Defaults to {@code false} to preserve legacy behaviour pre 2.10. * @since 2.11 */ - @Parameter( defaultValue = "false", property = "alwaysGenerateFailsafeReport" ) + @Parameter(defaultValue = "false", property = "alwaysGenerateFailsafeReport") private boolean alwaysGenerateFailsafeReport; /** * If set to true the failsafe report generation will be skipped. * @since 2.11 */ - @Parameter( defaultValue = "false", property = "skipFailsafeReport" ) + @Parameter(defaultValue = "false", property = "skipFailsafeReport") private boolean skipFailsafeReport; /** * A custom title of the report for the menu and the project reports page. * @since 2.21.0 */ - @Parameter( defaultValue = "", property = "failsafe.report.title" ) + @Parameter(defaultValue = "", property = "failsafe.report.title") private String title; /** * A custom description for the project reports page. * @since 2.21.0 */ - @Parameter( defaultValue = "", property = "failsafe.report.description" ) + @Parameter(defaultValue = "", property = "failsafe.report.description") private String description; @Override - protected File getSurefireReportsDirectory( MavenProject subProject ) - { + protected File getSurefireReportsDirectory(MavenProject subProject) { String buildDir = subProject.getBuild().getDirectory(); - return new File( buildDir + "/failsafe-reports" ); + return new File(buildDir + "/failsafe-reports"); } @Override - public String getOutputName() - { + public String getOutputName() { return outputName; } @Override - protected LocalizedProperties getBundle( Locale locale, ClassLoader resourceBundleClassLoader ) - { - ResourceBundle bundle = ResourceBundle.getBundle( "surefire-report", locale, resourceBundleClassLoader ); - return new LocalizedProperties( bundle ) - { + protected LocalizedProperties getBundle(Locale locale, ClassLoader resourceBundleClassLoader) { + ResourceBundle bundle = ResourceBundle.getBundle("surefire-report", locale, resourceBundleClassLoader); + return new LocalizedProperties(bundle) { @Override - public String getReportName() - { - return isEmpty( FailsafeReportMojo.this.getTitle() ) - ? toLocalizedValue( "report.failsafe.name" ) : FailsafeReportMojo.this.getTitle(); + public String getReportName() { + return isEmpty(FailsafeReportMojo.this.getTitle()) + ? toLocalizedValue("report.failsafe.name") + : FailsafeReportMojo.this.getTitle(); } @Override - public String getReportDescription() - { - return isEmpty( FailsafeReportMojo.this.getDescription() ) - ? toLocalizedValue( "report.failsafe.description" ) : FailsafeReportMojo.this.getDescription(); + public String getReportDescription() { + return isEmpty(FailsafeReportMojo.this.getDescription()) + ? toLocalizedValue("report.failsafe.description") + : FailsafeReportMojo.this.getDescription(); } @Override - public String getReportHeader() - { - return isEmpty( FailsafeReportMojo.this.getTitle() ) - ? toLocalizedValue( "report.failsafe.header" ) : FailsafeReportMojo.this.getTitle(); + public String getReportHeader() { + return isEmpty(FailsafeReportMojo.this.getTitle()) + ? toLocalizedValue("report.failsafe.header") + : FailsafeReportMojo.this.getTitle(); } }; } @Override - protected boolean isSkipped() - { + protected boolean isSkipped() { return skipFailsafeReport; } @Override - protected boolean isGeneratedWhenNoResults() - { + protected boolean isGeneratedWhenNoResults() { return alwaysGenerateFailsafeReport; } @Override - public void setTitle( String title ) - { + public void setTitle(String title) { this.title = title; } @Override - public String getTitle() - { + public String getTitle() { return title; } @Override - public void setDescription( String description ) - { + public void setDescription(String description) { this.description = description; } @Override - public String getDescription() - { + public String getDescription() { return description; } } diff --git a/maven-surefire-report-plugin/src/main/java/org/apache/maven/plugins/surefire/report/LocalizedProperties.java b/maven-surefire-report-plugin/src/main/java/org/apache/maven/plugins/surefire/report/LocalizedProperties.java index d73dc5e9da..5ad2186ee7 100644 --- a/maven-surefire-report-plugin/src/main/java/org/apache/maven/plugins/surefire/report/LocalizedProperties.java +++ b/maven-surefire-report-plugin/src/main/java/org/apache/maven/plugins/surefire/report/LocalizedProperties.java @@ -1,3 +1,21 @@ +/* + * 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.maven.plugins.surefire.report; /* @@ -26,91 +44,76 @@ * * @author Tibor Digana (tibor17) */ -public abstract class LocalizedProperties -{ +public abstract class LocalizedProperties { private final ResourceBundle bundle; - protected LocalizedProperties( ResourceBundle bundle ) - { + protected LocalizedProperties(ResourceBundle bundle) { this.bundle = bundle; } public abstract String getReportName(); + public abstract String getReportDescription(); + public abstract String getReportHeader(); - protected final String toLocalizedValue( String key ) - { - return bundle.getString( key ); + protected final String toLocalizedValue(String key) { + return bundle.getString(key); } - public String getReportLabelSummary() - { - return toLocalizedValue( "report.surefire.label.summary" ); + public String getReportLabelSummary() { + return toLocalizedValue("report.surefire.label.summary"); } - public String getReportLabelTests() - { - return toLocalizedValue( "report.surefire.label.tests" ); + public String getReportLabelTests() { + return toLocalizedValue("report.surefire.label.tests"); } - public String getReportLabelErrors() - { - return toLocalizedValue( "report.surefire.label.errors" ); + public String getReportLabelErrors() { + return toLocalizedValue("report.surefire.label.errors"); } - public String getReportLabelFailures() - { - return toLocalizedValue( "report.surefire.label.failures" ); + public String getReportLabelFailures() { + return toLocalizedValue("report.surefire.label.failures"); } - public String getReportLabelSkipped() - { - return toLocalizedValue( "report.surefire.label.skipped" ); + public String getReportLabelSkipped() { + return toLocalizedValue("report.surefire.label.skipped"); } - public String getReportLabelSuccessRate() - { - return toLocalizedValue( "report.surefire.label.successrate" ); + public String getReportLabelSuccessRate() { + return toLocalizedValue("report.surefire.label.successrate"); } - public String getReportLabelTime() - { - return toLocalizedValue( "report.surefire.label.time" ); + public String getReportLabelTime() { + return toLocalizedValue("report.surefire.label.time"); } - public String getReportLabelPackageList() - { - return toLocalizedValue( "report.surefire.label.packagelist" ); + public String getReportLabelPackageList() { + return toLocalizedValue("report.surefire.label.packagelist"); } - public String getReportLabelPackage() - { - return toLocalizedValue( "report.surefire.label.package" ); + public String getReportLabelPackage() { + return toLocalizedValue("report.surefire.label.package"); } - public String getReportLabelClass() - { - return toLocalizedValue( "report.surefire.label.class" ); + public String getReportLabelClass() { + return toLocalizedValue("report.surefire.label.class"); } - public String getReportLabelTestCases() - { - return toLocalizedValue( "report.surefire.label.testcases" ); + public String getReportLabelTestCases() { + return toLocalizedValue("report.surefire.label.testcases"); } - public String getReportLabelFailureDetails() - { - return toLocalizedValue( "report.surefire.label.failuredetails" ); + public String getReportLabelFailureDetails() { + return toLocalizedValue("report.surefire.label.failuredetails"); } - public String getReportTextNode1() - { - return toLocalizedValue( "report.surefire.text.note1" ); + public String getReportTextNode1() { + return toLocalizedValue("report.surefire.text.note1"); } - public String getReportTextNode2() - { - return toLocalizedValue( "report.surefire.text.note2" ); + public String getReportTextNode2() { + return toLocalizedValue("report.surefire.text.note2"); } } diff --git a/maven-surefire-report-plugin/src/main/java/org/apache/maven/plugins/surefire/report/PluginConsoleLogger.java b/maven-surefire-report-plugin/src/main/java/org/apache/maven/plugins/surefire/report/PluginConsoleLogger.java index 5070364a2d..1a62b424de 100644 --- a/maven-surefire-report-plugin/src/main/java/org/apache/maven/plugins/surefire/report/PluginConsoleLogger.java +++ b/maven-surefire-report-plugin/src/main/java/org/apache/maven/plugins/surefire/report/PluginConsoleLogger.java @@ -1,3 +1,21 @@ +/* + * 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.maven.plugins.surefire.report; /* @@ -33,93 +51,76 @@ * @since 2.20 * @see ConsoleLogger */ -final class PluginConsoleLogger - implements ConsoleLogger -{ +final class PluginConsoleLogger implements ConsoleLogger { private final Log mojoLogger; - PluginConsoleLogger( Log mojoLogger ) - { + PluginConsoleLogger(Log mojoLogger) { this.mojoLogger = mojoLogger; } @Override - public boolean isDebugEnabled() - { + public boolean isDebugEnabled() { return mojoLogger.isDebugEnabled(); } @Override - public void debug( String message ) - { - mojoLogger.debug( createAnsiBuilder( message ).a( message ).toString() ); + public void debug(String message) { + mojoLogger.debug(createAnsiBuilder(message).a(message).toString()); } - public void debug( CharSequence content, Throwable error ) - { - mojoLogger.debug( content, error ); + public void debug(CharSequence content, Throwable error) { + mojoLogger.debug(content, error); } @Override - public boolean isInfoEnabled() - { + public boolean isInfoEnabled() { return mojoLogger.isInfoEnabled(); } @Override - public void info( String message ) - { - mojoLogger.info( createAnsiBuilder( message ).a( message ).toString() ); + public void info(String message) { + mojoLogger.info(createAnsiBuilder(message).a(message).toString()); } @Override - public boolean isWarnEnabled() - { + public boolean isWarnEnabled() { return mojoLogger.isWarnEnabled(); } @Override - public void warning( String message ) - { - mojoLogger.warn( createAnsiBuilder( message ).warning( message ).toString() ); + public void warning(String message) { + mojoLogger.warn(createAnsiBuilder(message).warning(message).toString()); } - public void warn( CharSequence content, Throwable error ) - { - mojoLogger.warn( content, error ); + public void warn(CharSequence content, Throwable error) { + mojoLogger.warn(content, error); } @Override - public boolean isErrorEnabled() - { + public boolean isErrorEnabled() { return mojoLogger.isErrorEnabled(); } @Override - public void error( String message ) - { - mojoLogger.error( createAnsiBuilder( message ).failure( message ).toString() ); + public void error(String message) { + mojoLogger.error(createAnsiBuilder(message).failure(message).toString()); } @Override - public void error( String message, Throwable t ) - { - mojoLogger.error( message, t ); + public void error(String message, Throwable t) { + mojoLogger.error(message, t); } @Override - public void error( Throwable t ) - { - mojoLogger.error( t ); + public void error(Throwable t) { + mojoLogger.error(t); } - private static MessageBuilder createAnsiBuilder( CharSequence message ) - { - return buffer( bufferSize( message ) ); + private static MessageBuilder createAnsiBuilder(CharSequence message) { + return buffer(bufferSize(message)); } - private static int bufferSize( CharSequence message ) - { - return 32 - numberOfLeadingZeros( message.length() ); + private static int bufferSize(CharSequence message) { + return 32 - numberOfLeadingZeros(message.length()); } } diff --git a/maven-surefire-report-plugin/src/main/java/org/apache/maven/plugins/surefire/report/SurefireReportGenerator.java b/maven-surefire-report-plugin/src/main/java/org/apache/maven/plugins/surefire/report/SurefireReportGenerator.java index 4cfcce0386..edd10ede74 100644 --- a/maven-surefire-report-plugin/src/main/java/org/apache/maven/plugins/surefire/report/SurefireReportGenerator.java +++ b/maven-surefire-report-plugin/src/main/java/org/apache/maven/plugins/surefire/report/SurefireReportGenerator.java @@ -1,3 +1,21 @@ +/* + * 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.maven.plugins.surefire.report; /* @@ -24,6 +42,7 @@ import java.util.List; import java.util.Locale; import java.util.Map; + import org.apache.maven.doxia.markup.HtmlMarkup; import org.apache.maven.doxia.sink.Sink; import org.apache.maven.doxia.sink.impl.SinkEventAttributeSet; @@ -42,34 +61,34 @@ /** * This generator creates HTML Report from Surefire and Failsafe XML Report. */ -public final class SurefireReportGenerator -{ +public final class SurefireReportGenerator { private static final int LEFT = JUSTIFY_LEFT; - private static final Object[] TAG_TYPE_START = { HtmlMarkup.TAG_TYPE_START }; - private static final Object[] TAG_TYPE_END = { HtmlMarkup.TAG_TYPE_END }; + private static final Object[] TAG_TYPE_START = {HtmlMarkup.TAG_TYPE_START}; + private static final Object[] TAG_TYPE_END = {HtmlMarkup.TAG_TYPE_END}; private final SurefireReportParser report; private final boolean showSuccess; private final String xrefLocation; private List testSuites; - public SurefireReportGenerator( List reportsDirectories, Locale locale, boolean showSuccess, - String xrefLocation, ConsoleLogger consoleLogger ) - { - report = new SurefireReportParser( reportsDirectories, locale, consoleLogger ); + public SurefireReportGenerator( + List reportsDirectories, + Locale locale, + boolean showSuccess, + String xrefLocation, + ConsoleLogger consoleLogger) { + report = new SurefireReportParser(reportsDirectories, locale, consoleLogger); this.showSuccess = showSuccess; this.xrefLocation = xrefLocation; } - public void doGenerateReport( LocalizedProperties bundle, Sink sink ) - throws MavenReportException - { + public void doGenerateReport(LocalizedProperties bundle, Sink sink) throws MavenReportException { testSuites = report.parseXMLReportFiles(); sink.head(); sink.title(); - sink.text( bundle.getReportHeader() ); + sink.text(bundle.getReportHeader()); sink.title_(); sink.head_(); @@ -77,34 +96,31 @@ public void doGenerateReport( LocalizedProperties bundle, Sink sink ) sink.body(); SinkEventAttributeSet atts = new SinkEventAttributeSet(); - atts.addAttribute( TYPE, "application/javascript" ); - sink.unknown( "script", new Object[]{ HtmlMarkup.TAG_TYPE_START }, atts ); - sink.unknown( "cdata", new Object[]{ HtmlMarkup.CDATA_TYPE, javascriptToggleDisplayCode() }, null ); - sink.unknown( "script", new Object[]{ HtmlMarkup.TAG_TYPE_END }, null ); + atts.addAttribute(TYPE, "application/javascript"); + sink.unknown("script", new Object[] {HtmlMarkup.TAG_TYPE_START}, atts); + sink.unknown("cdata", new Object[] {HtmlMarkup.CDATA_TYPE, javascriptToggleDisplayCode()}, null); + sink.unknown("script", new Object[] {HtmlMarkup.TAG_TYPE_END}, null); sink.section1(); sink.sectionTitle1(); - sink.text( bundle.getReportHeader() ); + sink.text(bundle.getReportHeader()); sink.sectionTitle1_(); sink.section1_(); - constructSummarySection( bundle, sink ); + constructSummarySection(bundle, sink); - Map> suitePackages = report.getSuitesGroupByPackage( testSuites ); - if ( !suitePackages.isEmpty() ) - { - constructPackagesSection( bundle, sink, suitePackages ); + Map> suitePackages = report.getSuitesGroupByPackage(testSuites); + if (!suitePackages.isEmpty()) { + constructPackagesSection(bundle, sink, suitePackages); } - if ( !testSuites.isEmpty() ) - { - constructTestCasesSection( bundle, sink ); + if (!testSuites.isEmpty()) { + constructTestCasesSection(bundle, sink); } - List failureList = report.getFailureDetails( testSuites ); - if ( !failureList.isEmpty() ) - { - constructFailureDetails( sink, bundle, failureList ); + List failureList = report.getFailureDetails(testSuites); + if (!failureList.isEmpty()) { + constructFailureDetails(sink, bundle, failureList); } sink.body_(); @@ -114,53 +130,52 @@ public void doGenerateReport( LocalizedProperties bundle, Sink sink ) sink.close(); } - private void constructSummarySection( LocalizedProperties bundle, Sink sink ) - { - Map summary = report.getSummary( testSuites ); + private void constructSummarySection(LocalizedProperties bundle, Sink sink) { + Map summary = report.getSummary(testSuites); sink.section1(); - sinkAnchor( sink, "Summary" ); + sinkAnchor(sink, "Summary"); sink.sectionTitle1(); - sink.text( bundle.getReportLabelSummary() ); + sink.text(bundle.getReportLabelSummary()); sink.sectionTitle1_(); - constructHotLinks( sink, bundle ); + constructHotLinks(sink, bundle); - sinkLineBreak( sink ); + sinkLineBreak(sink); sink.table(); - sink.tableRows( new int[]{ LEFT, LEFT, LEFT, LEFT, LEFT, LEFT }, false ); + sink.tableRows(new int[] {LEFT, LEFT, LEFT, LEFT, LEFT, LEFT}, false); sink.tableRow(); - sinkHeader( sink, bundle.getReportLabelTests() ); + sinkHeader(sink, bundle.getReportLabelTests()); - sinkHeader( sink, bundle.getReportLabelErrors() ); + sinkHeader(sink, bundle.getReportLabelErrors()); - sinkHeader( sink, bundle.getReportLabelFailures() ); + sinkHeader(sink, bundle.getReportLabelFailures()); - sinkHeader( sink, bundle.getReportLabelSkipped() ); + sinkHeader(sink, bundle.getReportLabelSkipped()); - sinkHeader( sink, bundle.getReportLabelSuccessRate() ); + sinkHeader(sink, bundle.getReportLabelSuccessRate()); - sinkHeader( sink, bundle.getReportLabelTime() ); + sinkHeader(sink, bundle.getReportLabelTime()); sink.tableRow_(); sink.tableRow(); - sinkCell( sink, summary.get( "totalTests" ) ); + sinkCell(sink, summary.get("totalTests")); - sinkCell( sink, summary.get( "totalErrors" ) ); + sinkCell(sink, summary.get("totalErrors")); - sinkCell( sink, summary.get( "totalFailures" ) ); + sinkCell(sink, summary.get("totalFailures")); - sinkCell( sink, summary.get( "totalSkipped" ) ); + sinkCell(sink, summary.get("totalSkipped")); - sinkCell( sink, summary.get( "totalPercentage" ) + "%" ); + sinkCell(sink, summary.get("totalPercentage") + "%"); - sinkCell( sink, summary.get( "totalElapsedTime" ) ); + sinkCell(sink, summary.get("totalElapsedTime")); sink.tableRow_(); @@ -171,74 +186,72 @@ private void constructSummarySection( LocalizedProperties bundle, Sink sink ) sink.lineBreak(); sink.paragraph(); - sink.text( bundle.getReportTextNode1() ); + sink.text(bundle.getReportTextNode1()); sink.paragraph_(); - sinkLineBreak( sink ); + sinkLineBreak(sink); sink.section1_(); } - private void constructPackagesSection( LocalizedProperties bundle, Sink sink, - Map> suitePackages ) - { + private void constructPackagesSection( + LocalizedProperties bundle, Sink sink, Map> suitePackages) { NumberFormat numberFormat = report.getNumberFormat(); sink.section1(); - sinkAnchor( sink, "Package_List" ); + sinkAnchor(sink, "Package_List"); sink.sectionTitle1(); - sink.text( bundle.getReportLabelPackageList() ); + sink.text(bundle.getReportLabelPackageList()); sink.sectionTitle1_(); - constructHotLinks( sink, bundle ); + constructHotLinks(sink, bundle); - sinkLineBreak( sink ); + sinkLineBreak(sink); sink.table(); - sink.tableRows( new int[]{ LEFT, LEFT, LEFT, LEFT, LEFT, LEFT, LEFT }, false ); + sink.tableRows(new int[] {LEFT, LEFT, LEFT, LEFT, LEFT, LEFT, LEFT}, false); sink.tableRow(); - sinkHeader( sink, bundle.getReportLabelPackage() ); + sinkHeader(sink, bundle.getReportLabelPackage()); - sinkHeader( sink, bundle.getReportLabelTests() ); + sinkHeader(sink, bundle.getReportLabelTests()); - sinkHeader( sink, bundle.getReportLabelErrors() ); + sinkHeader(sink, bundle.getReportLabelErrors()); - sinkHeader( sink, bundle.getReportLabelFailures() ); + sinkHeader(sink, bundle.getReportLabelFailures()); - sinkHeader( sink, bundle.getReportLabelSkipped() ); + sinkHeader(sink, bundle.getReportLabelSkipped()); - sinkHeader( sink, bundle.getReportLabelSuccessRate() ); + sinkHeader(sink, bundle.getReportLabelSuccessRate()); - sinkHeader( sink, bundle.getReportLabelTime() ); + sinkHeader(sink, bundle.getReportLabelTime()); sink.tableRow_(); - for ( Map.Entry> entry : suitePackages.entrySet() ) - { + for (Map.Entry> entry : suitePackages.entrySet()) { sink.tableRow(); String packageName = entry.getKey(); List testSuiteList = entry.getValue(); - Map packageSummary = report.getSummary( testSuiteList ); + Map packageSummary = report.getSummary(testSuiteList); - sinkCellLink( sink, packageName, "#" + packageName ); + sinkCellLink(sink, packageName, "#" + packageName); - sinkCell( sink, packageSummary.get( "totalTests" ) ); + sinkCell(sink, packageSummary.get("totalTests")); - sinkCell( sink, packageSummary.get( "totalErrors" ) ); + sinkCell(sink, packageSummary.get("totalErrors")); - sinkCell( sink, packageSummary.get( "totalFailures" ) ); + sinkCell(sink, packageSummary.get("totalFailures")); - sinkCell( sink, packageSummary.get( "totalSkipped" ) ); + sinkCell(sink, packageSummary.get("totalSkipped")); - sinkCell( sink, packageSummary.get( "totalPercentage" ) + "%" ); + sinkCell(sink, packageSummary.get("totalPercentage") + "%"); - sinkCell( sink, packageSummary.get( "totalElapsedTime" ) ); + sinkCell(sink, packageSummary.get("totalElapsedTime")); sink.tableRow_(); } @@ -250,64 +263,58 @@ private void constructPackagesSection( LocalizedProperties bundle, Sink sink, sink.lineBreak(); sink.paragraph(); - sink.text( bundle.getReportTextNode2() ); + sink.text(bundle.getReportTextNode2()); sink.paragraph_(); - for ( Map.Entry> entry : suitePackages.entrySet() ) - { + for (Map.Entry> entry : suitePackages.entrySet()) { String packageName = entry.getKey(); List testSuiteList = entry.getValue(); sink.section2(); - sinkAnchor( sink, packageName ); + sinkAnchor(sink, packageName); sink.sectionTitle2(); - sink.text( packageName ); + sink.text(packageName); sink.sectionTitle2_(); boolean showTable = false; - for ( ReportTestSuite suite : testSuiteList ) - { - if ( showSuccess || suite.getNumberOfErrors() != 0 || suite.getNumberOfFailures() != 0 ) - { + for (ReportTestSuite suite : testSuiteList) { + if (showSuccess || suite.getNumberOfErrors() != 0 || suite.getNumberOfFailures() != 0) { showTable = true; break; } } - if ( showTable ) - { + if (showTable) { sink.table(); - sink.tableRows( new int[]{ LEFT, LEFT, LEFT, LEFT, LEFT, LEFT, LEFT, LEFT }, false ); + sink.tableRows(new int[] {LEFT, LEFT, LEFT, LEFT, LEFT, LEFT, LEFT, LEFT}, false); sink.tableRow(); - sinkHeader( sink, "" ); + sinkHeader(sink, ""); - sinkHeader( sink, bundle.getReportLabelClass() ); + sinkHeader(sink, bundle.getReportLabelClass()); - sinkHeader( sink, bundle.getReportLabelTests() ); + sinkHeader(sink, bundle.getReportLabelTests()); - sinkHeader( sink, bundle.getReportLabelErrors() ); + sinkHeader(sink, bundle.getReportLabelErrors()); - sinkHeader( sink, bundle.getReportLabelFailures() ); + sinkHeader(sink, bundle.getReportLabelFailures()); - sinkHeader( sink, bundle.getReportLabelSkipped() ); + sinkHeader(sink, bundle.getReportLabelSkipped()); - sinkHeader( sink, bundle.getReportLabelSuccessRate() ); + sinkHeader(sink, bundle.getReportLabelSuccessRate()); - sinkHeader( sink, bundle.getReportLabelTime() ); + sinkHeader(sink, bundle.getReportLabelTime()); sink.tableRow_(); - for ( ReportTestSuite suite : testSuiteList ) - { - if ( showSuccess || suite.getNumberOfErrors() != 0 || suite.getNumberOfFailures() != 0 ) - { - constructTestSuiteSection( sink, numberFormat, suite ); + for (ReportTestSuite suite : testSuiteList) { + if (showSuccess || suite.getNumberOfErrors() != 0 || suite.getNumberOfFailures() != 0) { + constructTestSuiteSection(sink, numberFormat, suite); } } @@ -319,106 +326,91 @@ private void constructPackagesSection( LocalizedProperties bundle, Sink sink, sink.section2_(); } - sinkLineBreak( sink ); + sinkLineBreak(sink); sink.section1_(); } - private void constructTestSuiteSection( Sink sink, NumberFormat numberFormat, ReportTestSuite suite ) - { + private void constructTestSuiteSection(Sink sink, NumberFormat numberFormat, ReportTestSuite suite) { sink.tableRow(); sink.tableCell(); - sink.link( "#" + suite.getPackageName() + '.' + suite.getName() ); + sink.link("#" + suite.getPackageName() + '.' + suite.getName()); - if ( suite.getNumberOfErrors() > 0 ) - { - sinkIcon( "error", sink ); - } - else if ( suite.getNumberOfFailures() > 0 ) - { - sinkIcon( "junit.framework", sink ); - } - else if ( suite.getNumberOfSkipped() > 0 ) - { - sinkIcon( "skipped", sink ); - } - else - { - sinkIcon( "success", sink ); + if (suite.getNumberOfErrors() > 0) { + sinkIcon("error", sink); + } else if (suite.getNumberOfFailures() > 0) { + sinkIcon("junit.framework", sink); + } else if (suite.getNumberOfSkipped() > 0) { + sinkIcon("skipped", sink); + } else { + sinkIcon("success", sink); } sink.link_(); sink.tableCell_(); - sinkCellLink( sink, suite.getName(), "#" + suite.getPackageName() + '.' + suite.getName() ); + sinkCellLink(sink, suite.getName(), "#" + suite.getPackageName() + '.' + suite.getName()); - sinkCell( sink, Integer.toString( suite.getNumberOfTests() ) ); + sinkCell(sink, Integer.toString(suite.getNumberOfTests())); - sinkCell( sink, Integer.toString( suite.getNumberOfErrors() ) ); + sinkCell(sink, Integer.toString(suite.getNumberOfErrors())); - sinkCell( sink, Integer.toString( suite.getNumberOfFailures() ) ); + sinkCell(sink, Integer.toString(suite.getNumberOfFailures())); - sinkCell( sink, Integer.toString( suite.getNumberOfSkipped() ) ); + sinkCell(sink, Integer.toString(suite.getNumberOfSkipped())); - String percentage = report.computePercentage( suite.getNumberOfTests(), suite.getNumberOfErrors(), - suite.getNumberOfFailures(), suite.getNumberOfSkipped() ); - sinkCell( sink, percentage + "%" ); + String percentage = report.computePercentage( + suite.getNumberOfTests(), suite.getNumberOfErrors(), + suite.getNumberOfFailures(), suite.getNumberOfSkipped()); + sinkCell(sink, percentage + "%"); - sinkCell( sink, numberFormat.format( suite.getTimeElapsed() ) ); + sinkCell(sink, numberFormat.format(suite.getTimeElapsed())); sink.tableRow_(); } - private void constructTestCasesSection( LocalizedProperties bundle, Sink sink ) - { + private void constructTestCasesSection(LocalizedProperties bundle, Sink sink) { NumberFormat numberFormat = report.getNumberFormat(); sink.section1(); - sinkAnchor( sink, "Test_Cases" ); + sinkAnchor(sink, "Test_Cases"); sink.sectionTitle1(); - sink.text( bundle.getReportLabelTestCases() ); + sink.text(bundle.getReportLabelTestCases()); sink.sectionTitle1_(); - constructHotLinks( sink, bundle ); + constructHotLinks(sink, bundle); - for ( ReportTestSuite suite : testSuites ) - { + for (ReportTestSuite suite : testSuites) { List testCases = suite.getTestCases(); - if ( !testCases.isEmpty() ) - { + if (!testCases.isEmpty()) { sink.section2(); - sinkAnchor( sink, suite.getPackageName() + '.' + suite.getName() ); + sinkAnchor(sink, suite.getPackageName() + '.' + suite.getName()); sink.sectionTitle2(); - sink.text( suite.getName() ); + sink.text(suite.getName()); sink.sectionTitle2_(); boolean showTable = false; - for ( ReportTestCase testCase : testCases ) - { - if ( !testCase.isSuccessful() || showSuccess ) - { + for (ReportTestCase testCase : testCases) { + if (!testCase.isSuccessful() || showSuccess) { showTable = true; break; } } - if ( showTable ) - { + if (showTable) { sink.table(); - sink.tableRows( new int[]{ LEFT, LEFT, LEFT }, false ); + sink.tableRows(new int[] {LEFT, LEFT, LEFT}, false); - for ( ReportTestCase testCase : testCases ) - { - if ( !testCase.isSuccessful() || showSuccess ) - { - constructTestCaseSection( sink, numberFormat, testCase ); + for (ReportTestCase testCase : testCases) { + if (!testCase.isSuccessful() || showSuccess) { + constructTestCaseSection(sink, numberFormat, testCase); } } @@ -431,145 +423,133 @@ private void constructTestCasesSection( LocalizedProperties bundle, Sink sink ) } } - sinkLineBreak( sink ); + sinkLineBreak(sink); sink.section1_(); } - private static void constructTestCaseSection( Sink sink, NumberFormat numberFormat, ReportTestCase testCase ) - { + private static void constructTestCaseSection(Sink sink, NumberFormat numberFormat, ReportTestCase testCase) { sink.tableRow(); sink.tableCell(); - if ( testCase.getFailureType() != null ) - { - sink.link( "#" + toHtmlId( testCase.getFullName() ) ); + if (testCase.getFailureType() != null) { + sink.link("#" + toHtmlId(testCase.getFullName())); - sinkIcon( testCase.getFailureType(), sink ); + sinkIcon(testCase.getFailureType(), sink); sink.link_(); - } - else - { - sinkIcon( "success", sink ); + } else { + sinkIcon("success", sink); } sink.tableCell_(); - if ( !testCase.isSuccessful() ) - { + if (!testCase.isSuccessful()) { sink.tableCell(); - sinkAnchor( sink, "TC_" + toHtmlId( testCase.getFullName() ) ); + sinkAnchor(sink, "TC_" + toHtmlId(testCase.getFullName())); - sinkLink( sink, testCase.getName(), "#" + toHtmlId( testCase.getFullName() ) ); + sinkLink(sink, testCase.getName(), "#" + toHtmlId(testCase.getFullName())); SinkEventAttributeSet atts = new SinkEventAttributeSet(); - atts.addAttribute( CLASS, "detailToggle" ); - atts.addAttribute( STYLE, "display:inline" ); - sink.unknown( "div", TAG_TYPE_START, atts ); + atts.addAttribute(CLASS, "detailToggle"); + atts.addAttribute(STYLE, "display:inline"); + sink.unknown("div", TAG_TYPE_START, atts); - sinkLink( sink, "javascript:toggleDisplay('" + toHtmlId( testCase.getFullName() ) + "');" ); + sinkLink(sink, "javascript:toggleDisplay('" + toHtmlId(testCase.getFullName()) + "');"); atts = new SinkEventAttributeSet(); - atts.addAttribute( STYLE, "display:inline;" ); - atts.addAttribute( ID, toHtmlId( testCase.getFullName() ) + "-off" ); - sink.unknown( "span", TAG_TYPE_START, atts ); - sink.text( " + " ); - sink.unknown( "span", TAG_TYPE_END, null ); + atts.addAttribute(STYLE, "display:inline;"); + atts.addAttribute(ID, toHtmlId(testCase.getFullName()) + "-off"); + sink.unknown("span", TAG_TYPE_START, atts); + sink.text(" + "); + sink.unknown("span", TAG_TYPE_END, null); atts = new SinkEventAttributeSet(); - atts.addAttribute( STYLE, "display:none;" ); - atts.addAttribute( ID, toHtmlId( testCase.getFullName() ) + "-on" ); - sink.unknown( "span", TAG_TYPE_START, atts ); - sink.text( " - " ); - sink.unknown( "span", TAG_TYPE_END, null ); + atts.addAttribute(STYLE, "display:none;"); + atts.addAttribute(ID, toHtmlId(testCase.getFullName()) + "-on"); + sink.unknown("span", TAG_TYPE_START, atts); + sink.text(" - "); + sink.unknown("span", TAG_TYPE_END, null); - sink.text( "[ Detail ]" ); - sinkLink_( sink ); + sink.text("[ Detail ]"); + sinkLink_(sink); - sink.unknown( "div", TAG_TYPE_END, null ); + sink.unknown("div", TAG_TYPE_END, null); sink.tableCell_(); - } - else - { - sinkCellAnchor( sink, testCase.getName(), "TC_" + toHtmlId( testCase.getFullName() ) ); + } else { + sinkCellAnchor(sink, testCase.getName(), "TC_" + toHtmlId(testCase.getFullName())); } - sinkCell( sink, numberFormat.format( testCase.getTime() ) ); + sinkCell(sink, numberFormat.format(testCase.getTime())); sink.tableRow_(); - if ( !testCase.isSuccessful() ) - { + if (!testCase.isSuccessful()) { sink.tableRow(); - sinkCell( sink, "" ); - sinkCell( sink, testCase.getFailureMessage() ); - sinkCell( sink, "" ); + sinkCell(sink, ""); + sinkCell(sink, testCase.getFailureMessage()); + sinkCell(sink, ""); sink.tableRow_(); String detail = testCase.getFailureDetail(); - if ( detail != null ) - { + if (detail != null) { sink.tableRow(); - sinkCell( sink, "" ); + sinkCell(sink, ""); sink.tableCell(); SinkEventAttributeSet atts = new SinkEventAttributeSet(); - atts.addAttribute( ID, toHtmlId( testCase.getFullName() ) + toHtmlIdFailure( testCase ) ); - atts.addAttribute( STYLE, "display:none;" ); - sink.unknown( "div", TAG_TYPE_START, atts ); + atts.addAttribute(ID, toHtmlId(testCase.getFullName()) + toHtmlIdFailure(testCase)); + atts.addAttribute(STYLE, "display:none;"); + sink.unknown("div", TAG_TYPE_START, atts); - sink.verbatim( null ); - sink.text( detail ); + sink.verbatim(null); + sink.text(detail); sink.verbatim_(); - sink.unknown( "div", TAG_TYPE_END, null ); + sink.unknown("div", TAG_TYPE_END, null); sink.tableCell_(); - sinkCell( sink, "" ); + sinkCell(sink, ""); sink.tableRow_(); } } } - private static String toHtmlId( String id ) - { - return DoxiaUtils.isValidId( id ) ? id : DoxiaUtils.encodeId( id, true ); + private static String toHtmlId(String id) { + return DoxiaUtils.isValidId(id) ? id : DoxiaUtils.encodeId(id, true); } - private void constructFailureDetails( Sink sink, LocalizedProperties bundle, List failures ) - { + private void constructFailureDetails(Sink sink, LocalizedProperties bundle, List failures) { sink.section1(); - sinkAnchor( sink, "Failure_Details" ); + sinkAnchor(sink, "Failure_Details"); sink.sectionTitle1(); - sink.text( bundle.getReportLabelFailureDetails() ); + sink.text(bundle.getReportLabelFailureDetails()); sink.sectionTitle1_(); - constructHotLinks( sink, bundle ); + constructHotLinks(sink, bundle); - sinkLineBreak( sink ); + sinkLineBreak(sink); sink.table(); - sink.tableRows( new int[]{ LEFT, LEFT }, false ); + sink.tableRows(new int[] {LEFT, LEFT}, false); - for ( ReportTestCase tCase : failures ) - { + for (ReportTestCase tCase : failures) { sink.tableRow(); sink.tableCell(); String type = tCase.getFailureType(); - sinkIcon( type, sink ); + sinkIcon(type, sink); sink.tableCell_(); - sinkCellAnchor( sink, tCase.getName(), toHtmlId( tCase.getFullName() ) ); + sinkCellAnchor(sink, tCase.getName(), toHtmlId(tCase.getFullName())); sink.tableRow_(); @@ -577,38 +557,35 @@ private void constructFailureDetails( Sink sink, LocalizedProperties bundle, Lis sink.tableRow(); - sinkCell( sink, "" ); + sinkCell(sink, ""); - sinkCell( sink, message == null ? type : type + ": " + message ); + sinkCell(sink, message == null ? type : type + ": " + message); sink.tableRow_(); String detail = tCase.getFailureDetail(); - if ( detail != null ) - { + if (detail != null) { sink.tableRow(); - sinkCell( sink, "" ); + sinkCell(sink, ""); sink.tableCell(); SinkEventAttributeSet atts = new SinkEventAttributeSet(); - atts.addAttribute( ID, tCase.getName() + toHtmlIdFailure( tCase ) ); - sink.unknown( "div", TAG_TYPE_START, atts ); + atts.addAttribute(ID, tCase.getName() + toHtmlIdFailure(tCase)); + sink.unknown("div", TAG_TYPE_START, atts); String fullClassName = tCase.getFullClassName(); String errorLineNumber = tCase.getFailureErrorLine(); - if ( xrefLocation != null ) - { - String path = fullClassName.replace( '.', '/' ); - sink.link( xrefLocation + "/" + path + ".html#L" + errorLineNumber ); + if (xrefLocation != null) { + String path = fullClassName.replace('.', '/'); + sink.link(xrefLocation + "/" + path + ".html#L" + errorLineNumber); } - sink.text( fullClassName + ":" + errorLineNumber ); + sink.text(fullClassName + ":" + errorLineNumber); - if ( xrefLocation != null ) - { + if (xrefLocation != null) { sink.link_(); } - sink.unknown( "div", TAG_TYPE_END, null ); + sink.unknown("div", TAG_TYPE_END, null); sink.tableCell_(); @@ -620,118 +597,99 @@ private void constructFailureDetails( Sink sink, LocalizedProperties bundle, Lis sink.table_(); - sinkLineBreak( sink ); + sinkLineBreak(sink); sink.section1_(); } - private void constructHotLinks( Sink sink, LocalizedProperties bundle ) - { - if ( !testSuites.isEmpty() ) - { + private void constructHotLinks(Sink sink, LocalizedProperties bundle) { + if (!testSuites.isEmpty()) { sink.paragraph(); - sink.text( "[" ); - sinkLink( sink, bundle.getReportLabelSummary(), "#Summary" ); - sink.text( "]" ); + sink.text("["); + sinkLink(sink, bundle.getReportLabelSummary(), "#Summary"); + sink.text("]"); - sink.text( " [" ); - sinkLink( sink, bundle.getReportLabelPackageList(), "#Package_List" ); - sink.text( "]" ); + sink.text(" ["); + sinkLink(sink, bundle.getReportLabelPackageList(), "#Package_List"); + sink.text("]"); - sink.text( " [" ); - sinkLink( sink, bundle.getReportLabelTestCases(), "#Test_Cases" ); - sink.text( "]" ); + sink.text(" ["); + sinkLink(sink, bundle.getReportLabelTestCases(), "#Test_Cases"); + sink.text("]"); sink.paragraph_(); } } - private static String toHtmlIdFailure( ReportTestCase tCase ) - { + private static String toHtmlIdFailure(ReportTestCase tCase) { return tCase.hasError() ? "-error" : "-failure"; } - private static void sinkLineBreak( Sink sink ) - { + private static void sinkLineBreak(Sink sink) { sink.lineBreak(); } - private static void sinkIcon( String type, Sink sink ) - { - if ( type.startsWith( "junit.framework" ) || "skipped".equals( type ) ) - { - sink.figureGraphics( "images/icon_warning_sml.gif" ); - } - else if ( type.startsWith( "success" ) ) - { - sink.figureGraphics( "images/icon_success_sml.gif" ); - } - else - { - sink.figureGraphics( "images/icon_error_sml.gif" ); + private static void sinkIcon(String type, Sink sink) { + if (type.startsWith("junit.framework") || "skipped".equals(type)) { + sink.figureGraphics("images/icon_warning_sml.gif"); + } else if (type.startsWith("success")) { + sink.figureGraphics("images/icon_success_sml.gif"); + } else { + sink.figureGraphics("images/icon_error_sml.gif"); } } - private static void sinkHeader( Sink sink, String header ) - { + private static void sinkHeader(Sink sink, String header) { sink.tableHeaderCell(); - sink.text( header ); + sink.text(header); sink.tableHeaderCell_(); } - private static void sinkCell( Sink sink, String text ) - { + private static void sinkCell(Sink sink, String text) { sink.tableCell(); - sink.text( text ); + sink.text(text); sink.tableCell_(); } - private static void sinkLink( Sink sink, String text, String link ) - { - sink.link( link ); - sink.text( text ); + private static void sinkLink(Sink sink, String text, String link) { + sink.link(link); + sink.text(text); sink.link_(); } - private static void sinkCellLink( Sink sink, String text, String link ) - { + private static void sinkCellLink(Sink sink, String text, String link) { sink.tableCell(); - sinkLink( sink, text, link ); + sinkLink(sink, text, link); sink.tableCell_(); } - private static void sinkCellAnchor( Sink sink, String text, String anchor ) - { + private static void sinkCellAnchor(Sink sink, String text, String anchor) { sink.tableCell(); - sinkAnchor( sink, anchor ); - sink.text( text ); + sinkAnchor(sink, anchor); + sink.text(text); sink.tableCell_(); } - private static void sinkAnchor( Sink sink, String anchor ) - { + private static void sinkAnchor(Sink sink, String anchor) { // Dollar '$' for nested classes is not valid character in sink.anchor() and therefore it is ignored // https://issues.apache.org/jira/browse/SUREFIRE-1443 - sink.unknown( A.toString(), TAG_TYPE_START, new SinkEventAttributeSet( ID, anchor ) ); - sink.unknown( A.toString(), TAG_TYPE_END, null ); + sink.unknown(A.toString(), TAG_TYPE_START, new SinkEventAttributeSet(ID, anchor)); + sink.unknown(A.toString(), TAG_TYPE_END, null); } - private static void sinkLink( Sink sink, String href ) - { + private static void sinkLink(Sink sink, String href) { // The "'" argument in this JavaScript function would be escaped to "'" // sink.link( "javascript:toggleDisplay('" + toHtmlId( testCase.getFullName() ) + "');" ); - sink.unknown( A.toString(), TAG_TYPE_START, new SinkEventAttributeSet( HREF, href ) ); + sink.unknown(A.toString(), TAG_TYPE_START, new SinkEventAttributeSet(HREF, href)); } - @SuppressWarnings( "checkstyle:methodname" ) - private static void sinkLink_( Sink sink ) - { - sink.unknown( A.toString(), TAG_TYPE_END, null ); + @SuppressWarnings("checkstyle:methodname") + private static void sinkLink_(Sink sink) { + sink.unknown(A.toString(), TAG_TYPE_END, null); } - private static String javascriptToggleDisplayCode() - { + private static String javascriptToggleDisplayCode() { // the javascript code is emitted within a commented CDATA section // so we have to start with a newline and comment the CDATA closing in the end diff --git a/maven-surefire-report-plugin/src/main/java/org/apache/maven/plugins/surefire/report/SurefireReportMojo.java b/maven-surefire-report-plugin/src/main/java/org/apache/maven/plugins/surefire/report/SurefireReportMojo.java index 1a852dbfb7..cbebf2c76a 100644 --- a/maven-surefire-report-plugin/src/main/java/org/apache/maven/plugins/surefire/report/SurefireReportMojo.java +++ b/maven-surefire-report-plugin/src/main/java/org/apache/maven/plugins/surefire/report/SurefireReportMojo.java @@ -1,3 +1,21 @@ +/* + * 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.maven.plugins.surefire.report; /* @@ -19,16 +37,16 @@ * under the License. */ +import java.io.File; +import java.util.Locale; +import java.util.ResourceBundle; + import org.apache.maven.plugins.annotations.Execute; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.project.MavenProject; -import java.io.File; -import java.util.Locale; -import java.util.ResourceBundle; - import static org.apache.maven.shared.utils.StringUtils.isEmpty; /** @@ -36,17 +54,15 @@ * * @author Johnny R. Ruiz III */ -@Mojo( name = "report", inheritByDefault = false ) -@Execute( lifecycle = "surefire", phase = LifecyclePhase.TEST ) -@SuppressWarnings( "unused" ) -public class SurefireReportMojo - extends AbstractSurefireReportMojo -{ +@Mojo(name = "report", inheritByDefault = false) +@Execute(lifecycle = "surefire", phase = LifecyclePhase.TEST) +@SuppressWarnings("unused") +public class SurefireReportMojo extends AbstractSurefireReportMojo { /** * The filename to use for the report. */ - @Parameter( defaultValue = "surefire-report", property = "outputName", required = true ) + @Parameter(defaultValue = "surefire-report", property = "outputName", required = true) private String outputName; /** @@ -54,105 +70,95 @@ public class SurefireReportMojo * Defaults to {@code true} to preserve legacy behaviour pre 2.10. * @since 2.11 */ - @Parameter( defaultValue = "true", property = "alwaysGenerateSurefireReport" ) + @Parameter(defaultValue = "true", property = "alwaysGenerateSurefireReport") private boolean alwaysGenerateSurefireReport; /** * If set to true the surefire report generation will be skipped. * @since 2.11 */ - @Parameter( defaultValue = "false", property = "skipSurefireReport" ) + @Parameter(defaultValue = "false", property = "skipSurefireReport") private boolean skipSurefireReport; /** * A custom title of the report for the menu and the project reports page. * @since 2.21.0 */ - @Parameter( defaultValue = "", property = "surefire.report.title" ) + @Parameter(defaultValue = "", property = "surefire.report.title") private String title; /** * A custom description for the project reports page. * @since 2.21.0 */ - @Parameter( defaultValue = "", property = "surefire.report.description" ) + @Parameter(defaultValue = "", property = "surefire.report.description") private String description; @Override - protected File getSurefireReportsDirectory( MavenProject subProject ) - { + protected File getSurefireReportsDirectory(MavenProject subProject) { String buildDir = subProject.getBuild().getDirectory(); - return new File( buildDir + "/surefire-reports" ); + return new File(buildDir + "/surefire-reports"); } @Override - public String getOutputName() - { + public String getOutputName() { return outputName; } @Override - protected LocalizedProperties getBundle( Locale locale, ClassLoader resourceBundleClassLoader ) - { - ResourceBundle bundle = ResourceBundle.getBundle( "surefire-report", locale, resourceBundleClassLoader ); - return new LocalizedProperties( bundle ) - { + protected LocalizedProperties getBundle(Locale locale, ClassLoader resourceBundleClassLoader) { + ResourceBundle bundle = ResourceBundle.getBundle("surefire-report", locale, resourceBundleClassLoader); + return new LocalizedProperties(bundle) { @Override - public String getReportName() - { - return isEmpty( SurefireReportMojo.this.getTitle() ) - ? toLocalizedValue( "report.surefire.name" ) : SurefireReportMojo.this.getTitle(); + public String getReportName() { + return isEmpty(SurefireReportMojo.this.getTitle()) + ? toLocalizedValue("report.surefire.name") + : SurefireReportMojo.this.getTitle(); } @Override - public String getReportDescription() - { - return isEmpty( SurefireReportMojo.this.getDescription() ) - ? toLocalizedValue( "report.surefire.description" ) : SurefireReportMojo.this.getDescription(); + public String getReportDescription() { + return isEmpty(SurefireReportMojo.this.getDescription()) + ? toLocalizedValue("report.surefire.description") + : SurefireReportMojo.this.getDescription(); } @Override - public String getReportHeader() - { - return isEmpty( SurefireReportMojo.this.getTitle() ) - ? toLocalizedValue( "report.surefire.header" ) : SurefireReportMojo.this.getTitle(); + public String getReportHeader() { + return isEmpty(SurefireReportMojo.this.getTitle()) + ? toLocalizedValue("report.surefire.header") + : SurefireReportMojo.this.getTitle(); } }; } @Override - protected boolean isSkipped() - { + protected boolean isSkipped() { return skipSurefireReport; } @Override - protected boolean isGeneratedWhenNoResults() - { + protected boolean isGeneratedWhenNoResults() { return alwaysGenerateSurefireReport; } @Override - public void setTitle( String title ) - { + public void setTitle(String title) { this.title = title; } @Override - public String getTitle() - { + public String getTitle() { return title; } @Override - public void setDescription( String description ) - { + public void setDescription(String description) { this.description = description; } @Override - public String getDescription() - { + public String getDescription() { return description; } } diff --git a/maven-surefire-report-plugin/src/main/java/org/apache/maven/plugins/surefire/report/SurefireReportOnlyMojo.java b/maven-surefire-report-plugin/src/main/java/org/apache/maven/plugins/surefire/report/SurefireReportOnlyMojo.java index 4a2f2bd2d6..de105c8a08 100644 --- a/maven-surefire-report-plugin/src/main/java/org/apache/maven/plugins/surefire/report/SurefireReportOnlyMojo.java +++ b/maven-surefire-report-plugin/src/main/java/org/apache/maven/plugins/surefire/report/SurefireReportOnlyMojo.java @@ -1,3 +1,21 @@ +/* + * 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.maven.plugins.surefire.report; /* @@ -32,11 +50,7 @@ * @author Barrie Treloar * @since 2.3 */ -@Mojo( name = "report-only" ) -@Execute( phase = LifecyclePhase.NONE ) -@SuppressWarnings( "unused" ) -public class SurefireReportOnlyMojo - extends SurefireReportMojo -{ - -} +@Mojo(name = "report-only") +@Execute(phase = LifecyclePhase.NONE) +@SuppressWarnings("unused") +public class SurefireReportOnlyMojo extends SurefireReportMojo {} diff --git a/maven-surefire-report-plugin/src/test/java/org/apache/maven/plugins/surefire/report/JUnit4SuiteTest.java b/maven-surefire-report-plugin/src/test/java/org/apache/maven/plugins/surefire/report/JUnit4SuiteTest.java index 13b03e7854..ffbce432d5 100644 --- a/maven-surefire-report-plugin/src/test/java/org/apache/maven/plugins/surefire/report/JUnit4SuiteTest.java +++ b/maven-surefire-report-plugin/src/test/java/org/apache/maven/plugins/surefire/report/JUnit4SuiteTest.java @@ -1,3 +1,21 @@ +/* + * 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.maven.plugins.surefire.report; /* @@ -30,14 +48,12 @@ * @author Tibor Digana (tibor17) * @since 3.0.0-M4 */ -public class JUnit4SuiteTest extends TestCase -{ - public static Test suite() - { +public class JUnit4SuiteTest extends TestCase { + public static Test suite() { TestSuite suite = new TestSuite(); - suite.addTest( new JUnit4TestAdapter( Surefire597Test.class ) ); - suite.addTest( new JUnit4TestAdapter( SurefireSchemaValidationTest.class ) ); - suite.addTestSuite( SurefireReportMojoTest.class ); + suite.addTest(new JUnit4TestAdapter(Surefire597Test.class)); + suite.addTest(new JUnit4TestAdapter(SurefireSchemaValidationTest.class)); + suite.addTestSuite(SurefireReportMojoTest.class); return suite; } } diff --git a/maven-surefire-report-plugin/src/test/java/org/apache/maven/plugins/surefire/report/Surefire597Test.java b/maven-surefire-report-plugin/src/test/java/org/apache/maven/plugins/surefire/report/Surefire597Test.java index d7758cb021..46669b79a8 100644 --- a/maven-surefire-report-plugin/src/test/java/org/apache/maven/plugins/surefire/report/Surefire597Test.java +++ b/maven-surefire-report-plugin/src/test/java/org/apache/maven/plugins/surefire/report/Surefire597Test.java @@ -1,3 +1,21 @@ +/* + * 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.maven.plugins.surefire.report; /* @@ -19,107 +37,106 @@ * under the License. */ +import java.io.File; +import java.io.StringWriter; + import junit.framework.TestCase; import org.apache.maven.doxia.module.xhtml5.Xhtml5Sink; import org.apache.maven.doxia.sink.Sink; import org.apache.maven.plugin.surefire.log.api.ConsoleLogger; import org.apache.maven.plugin.surefire.log.api.NullConsoleLogger; -import java.io.File; -import java.io.StringWriter; - import static java.util.Collections.singletonList; import static java.util.Locale.ENGLISH; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.CoreMatchers.containsString; import static org.apache.maven.plugins.surefire.report.Utils.toSystemNewLine; +import static org.hamcrest.CoreMatchers.containsString; +import static org.hamcrest.MatcherAssert.assertThat; /** * Prevent fom NPE if failure type and message is null however detail presents. */ -public class Surefire597Test - extends TestCase -{ - @SuppressWarnings( "checkstyle:linelength" ) - public void testCorruptedTestCaseFailureWithMissingErrorTypeAndMessage() - throws Exception - { - File basedir = new File( "." ).getCanonicalFile(); - File report = new File( basedir, "target/test-classes/surefire-597" ); +public class Surefire597Test extends TestCase { + @SuppressWarnings("checkstyle:linelength") + public void testCorruptedTestCaseFailureWithMissingErrorTypeAndMessage() throws Exception { + File basedir = new File(".").getCanonicalFile(); + File report = new File(basedir, "target/test-classes/surefire-597"); ConsoleLogger log = new NullConsoleLogger(); - SurefireReportGenerator gen = new SurefireReportGenerator( singletonList( report ), ENGLISH, true, null, log ); + SurefireReportGenerator gen = new SurefireReportGenerator(singletonList(report), ENGLISH, true, null, log); StringWriter writer = new StringWriter(); - Sink sink = new Xhtml5Sink( writer ) - { }; - gen.doGenerateReport( new SurefireReportMojo().getBundle( ENGLISH ), sink ); + Sink sink = new Xhtml5Sink(writer) {}; + gen.doGenerateReport(new SurefireReportMojo().getBundle(ENGLISH), sink); String xml = writer.toString(); - assertThat( xml, containsString( toSystemNewLine( - "\n" - + "\n" - + "\n" - + "\n" - + "\n" - + "\n" - + "\n" - + "\n" - + "\n" - + "\n" - + "\n" - + "\n" - + "\n" - + "\n" - + "" - + "" - + "
TestsErrorsFailuresSkippedSuccess RateTime
11000%0
" ) ) ); - assertThat( xml, containsString( toSystemNewLine( - "\n" - + "\n" - + "\n" - + "\n" - + "\n" - + "\n" - + "\n" - + "\n" - + "\n" - + "\n" - + "\n" - + "\n" - + "\n" - + "\n" - + "\n" - + "\n" - + "
PackageTestsErrorsFailuresSkippedSuccess RateTime
surefire11000%0
" ) ) ); - assertThat( xml, containsString( toSystemNewLine( - "\n" - + "\n" - + "\n" - + "\n" - + "\n" - + "\n" - + "\n" - + "\n" - + "\n" - + "\n" - + "\n" - + "\n" - + "\n" - + "\n" - + "\n" - + "\n" - + "\n" - + "\n" - + "
ClassTestsErrorsFailuresSkippedSuccess RateTime
\"\"MyTest11000%0
" ) ) ); - assertThat( xml, containsString( toSystemNewLine( - "\n" - + "\n" - + "\n" - + "\n" - + "\n" - + "\n" - + "\n" - + "\n" - + "\n" - + "
\"\"test
java.lang.RuntimeException: java.lang.IndexOutOfBoundsException: msg
\n" - + "
surefire.MyTest:13
" ) ) ); + assertThat( + xml, + containsString(toSystemNewLine("\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "" + + "" + + "
TestsErrorsFailuresSkippedSuccess RateTime
11000%0
"))); + assertThat( + xml, + containsString(toSystemNewLine("\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "
PackageTestsErrorsFailuresSkippedSuccess RateTime
surefire11000%0
"))); + assertThat( + xml, + containsString(toSystemNewLine("\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "
ClassTestsErrorsFailuresSkippedSuccess RateTime
\"\"MyTest11000%0
"))); + assertThat( + xml, + containsString(toSystemNewLine("\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "
\"\"test
java.lang.RuntimeException: java.lang.IndexOutOfBoundsException: msg
\n" + + "
surefire.MyTest:13
"))); } } diff --git a/maven-surefire-report-plugin/src/test/java/org/apache/maven/plugins/surefire/report/SurefireReportMojoTest.java b/maven-surefire-report-plugin/src/test/java/org/apache/maven/plugins/surefire/report/SurefireReportMojoTest.java index 0e1f1818fb..748ea4eabe 100644 --- a/maven-surefire-report-plugin/src/test/java/org/apache/maven/plugins/surefire/report/SurefireReportMojoTest.java +++ b/maven-surefire-report-plugin/src/test/java/org/apache/maven/plugins/surefire/report/SurefireReportMojoTest.java @@ -1,3 +1,21 @@ +/* + * 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.maven.plugins.surefire.report; /* @@ -44,577 +62,579 @@ import org.eclipse.aether.internal.impl.SimpleLocalRepositoryManagerFactory; import org.eclipse.aether.repository.LocalRepository; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.CoreMatchers.containsString; import static org.apache.maven.plugins.surefire.report.Utils.toSystemNewLine; +import static org.hamcrest.CoreMatchers.containsString; +import static org.hamcrest.MatcherAssert.assertThat; /** * @author Allan Ramirez */ -@SuppressWarnings( "checkstyle:linelength" ) -public class SurefireReportMojoTest - extends AbstractMojoTestCase -{ +@SuppressWarnings("checkstyle:linelength") +public class SurefireReportMojoTest extends AbstractMojoTestCase { private ArtifactStubFactory artifactStubFactory; private Renderer renderer; @Override - protected void setUp() - throws Exception - { + protected void setUp() throws Exception { super.setUp(); - renderer = (Renderer) lookup( Renderer.ROLE ); + renderer = (Renderer) lookup(Renderer.ROLE); - artifactStubFactory = new DependencyArtifactStubFactory( getTestFile( "target" ), true, false ); + artifactStubFactory = new DependencyArtifactStubFactory(getTestFile("target"), true, false); artifactStubFactory.getWorkingDir().mkdirs(); } - protected SurefireReportMojo createReportMojo( File pluginXmlFile ) - throws Exception - { - SurefireReportMojo mojo = (SurefireReportMojo) lookupMojo( "report", pluginXmlFile ); - assertNotNull( "Mojo found.", mojo ); + protected SurefireReportMojo createReportMojo(File pluginXmlFile) throws Exception { + SurefireReportMojo mojo = (SurefireReportMojo) lookupMojo("report", pluginXmlFile); + assertNotNull("Mojo found.", mojo); - LegacySupport legacySupport = lookup( LegacySupport.class ); - legacySupport.setSession( newMavenSession( new MavenProjectStub() ) ); + LegacySupport legacySupport = lookup(LegacySupport.class); + legacySupport.setSession(newMavenSession(new MavenProjectStub())); DefaultRepositorySystemSession repoSession = - (DefaultRepositorySystemSession) legacySupport.getRepositorySession(); - repoSession.setLocalRepositoryManager( new SimpleLocalRepositoryManagerFactory().newInstance( repoSession, new LocalRepository( artifactStubFactory.getWorkingDir() ) ) ); + (DefaultRepositorySystemSession) legacySupport.getRepositorySession(); + repoSession.setLocalRepositoryManager(new SimpleLocalRepositoryManagerFactory() + .newInstance(repoSession, new LocalRepository(artifactStubFactory.getWorkingDir()))); - //setVariableValueToObject( mojo, "session", legacySupport.getSession() ); - setVariableValueToObject( mojo, "remoteRepositories", mojo.getProject().getRemoteArtifactRepositories() ); + // setVariableValueToObject( mojo, "session", legacySupport.getSession() ); + setVariableValueToObject(mojo, "remoteRepositories", mojo.getProject().getRemoteArtifactRepositories()); return mojo; } - public void testBasicSurefireReport() - throws Exception - { - File testPom = new File( getUnitBaseDir(), "basic-surefire-report-test/plugin-config.xml" ); - SurefireReportMojo mojo = createReportMojo( testPom ); - File outputDir = (File) getVariableValueFromObject( mojo, "outputDirectory" ); - boolean showSuccess = (Boolean) getVariableValueFromObject( mojo, "showSuccess" ); - File reportsDir = (File) getVariableValueFromObject( mojo, "reportsDirectory" ); - String outputName = (String) getVariableValueFromObject( mojo, "outputName" ); - File xrefLocation = (File) getVariableValueFromObject( mojo, "xrefLocation" ); - boolean linkXRef = (Boolean) getVariableValueFromObject( mojo, "linkXRef" ); - - assertEquals( new File( getBasedir() + "/target/site/unit/basic-surefire-report-test" ), outputDir ); - assertTrue( showSuccess ); - assertEquals( new File( - getBasedir() + "/src/test/resources/unit/basic-surefire-report-test/surefire-reports" ).getAbsolutePath(), - reportsDir.getAbsolutePath() ); - assertEquals( "surefire-report", outputName ); + public void testBasicSurefireReport() throws Exception { + File testPom = new File(getUnitBaseDir(), "basic-surefire-report-test/plugin-config.xml"); + SurefireReportMojo mojo = createReportMojo(testPom); + File outputDir = (File) getVariableValueFromObject(mojo, "outputDirectory"); + boolean showSuccess = (Boolean) getVariableValueFromObject(mojo, "showSuccess"); + File reportsDir = (File) getVariableValueFromObject(mojo, "reportsDirectory"); + String outputName = (String) getVariableValueFromObject(mojo, "outputName"); + File xrefLocation = (File) getVariableValueFromObject(mojo, "xrefLocation"); + boolean linkXRef = (Boolean) getVariableValueFromObject(mojo, "linkXRef"); + + assertEquals(new File(getBasedir() + "/target/site/unit/basic-surefire-report-test"), outputDir); + assertTrue(showSuccess); assertEquals( - new File( getBasedir() + "/target/site/unit/basic-surefire-report-test/xref-test" ).getAbsolutePath(), - xrefLocation.getAbsolutePath() ); - assertTrue( linkXRef ); + new File(getBasedir() + "/src/test/resources/unit/basic-surefire-report-test/surefire-reports") + .getAbsolutePath(), + reportsDir.getAbsolutePath()); + assertEquals("surefire-report", outputName); + assertEquals( + new File(getBasedir() + "/target/site/unit/basic-surefire-report-test/xref-test").getAbsolutePath(), + xrefLocation.getAbsolutePath()); + assertTrue(linkXRef); mojo.execute(); - File report = new File( getBasedir(), "target/site/unit/basic-surefire-report-test/surefire-report.html" ); - renderer( mojo, report ); - assertTrue( report.exists() ); - String htmlContent = FileUtils.fileRead( report ); + File report = new File(getBasedir(), "target/site/unit/basic-surefire-report-test/surefire-report.html"); + renderer(mojo, report); + assertTrue(report.exists()); + String htmlContent = FileUtils.fileRead(report); - int idx = htmlContent.indexOf( "images/icon_success_sml.gif" ); - assertTrue( idx >= 0 ); + int idx = htmlContent.indexOf("images/icon_success_sml.gif"); + assertTrue(idx >= 0); } - private File getUnitBaseDir() - throws UnsupportedEncodingException - { - URL resource = getClass().getResource( "/unit" ); + private File getUnitBaseDir() throws UnsupportedEncodingException { + URL resource = getClass().getResource("/unit"); // URLDecoder.decode necessary for JDK 1.5+, where spaces are escaped to %20 - return new File( URLDecoder.decode( resource.getPath(), "UTF-8" ) ).getAbsoluteFile(); + return new File(URLDecoder.decode(resource.getPath(), "UTF-8")).getAbsoluteFile(); } - public void testBasicSurefireReportIfShowSuccessIsFalse() - throws Exception - { - File testPom = new File( getUnitBaseDir(), "basic-surefire-report-success-false/plugin-config.xml" ); - SurefireReportMojo mojo = createReportMojo( testPom ); - boolean showSuccess = (Boolean) getVariableValueFromObject( mojo, "showSuccess" ); - assertFalse( showSuccess ); + public void testBasicSurefireReportIfShowSuccessIsFalse() throws Exception { + File testPom = new File(getUnitBaseDir(), "basic-surefire-report-success-false/plugin-config.xml"); + SurefireReportMojo mojo = createReportMojo(testPom); + boolean showSuccess = (Boolean) getVariableValueFromObject(mojo, "showSuccess"); + assertFalse(showSuccess); mojo.execute(); File report = - new File( getBasedir(), "target/site/unit/basic-surefire-report-success-false/surefire-report.html" ); - renderer( mojo, report ); - assertTrue( report.exists() ); - String htmlContent = FileUtils.fileRead( report ); + new File(getBasedir(), "target/site/unit/basic-surefire-report-success-false/surefire-report.html"); + renderer(mojo, report); + assertTrue(report.exists()); + String htmlContent = FileUtils.fileRead(report); - int idx = htmlContent.indexOf( "images/icon_success_sml.gif" ); - assertTrue( idx < 0 ); + int idx = htmlContent.indexOf("images/icon_success_sml.gif"); + assertTrue(idx < 0); } - public void testBasicSurefireReportIfLinkXrefIsFalse() - throws Exception - { - File testPom = new File( getUnitBaseDir(), "basic-surefire-report-linkxref-false/plugin-config.xml" ); - SurefireReportMojo mojo = createReportMojo( testPom ); - boolean linkXRef = (Boolean) getVariableValueFromObject( mojo, "linkXRef" ); - assertFalse( linkXRef ); + public void testBasicSurefireReportIfLinkXrefIsFalse() throws Exception { + File testPom = new File(getUnitBaseDir(), "basic-surefire-report-linkxref-false/plugin-config.xml"); + SurefireReportMojo mojo = createReportMojo(testPom); + boolean linkXRef = (Boolean) getVariableValueFromObject(mojo, "linkXRef"); + assertFalse(linkXRef); mojo.execute(); File report = - new File( getBasedir(), "target/site/unit/basic-surefire-report-success-false/surefire-report.html" ); - renderer( mojo, report ); - assertTrue( report.exists() ); - String htmlContent = FileUtils.fileRead( report ); + new File(getBasedir(), "target/site/unit/basic-surefire-report-success-false/surefire-report.html"); + renderer(mojo, report); + assertTrue(report.exists()); + String htmlContent = FileUtils.fileRead(report); - int idx = htmlContent.indexOf( "./xref-test/com/shape/CircleTest.html#L44" ); - assertTrue( idx == -1 ); + int idx = htmlContent.indexOf("./xref-test/com/shape/CircleTest.html#L44"); + assertTrue(idx == -1); } - public void testBasicSurefireReportIfReportingIsNull() - throws Exception - { - File testPom = new File( getUnitBaseDir(), "basic-surefire-report-reporting-null/plugin-config.xml" ); - SurefireReportMojo mojo = createReportMojo( testPom ); + public void testBasicSurefireReportIfReportingIsNull() throws Exception { + File testPom = new File(getUnitBaseDir(), "basic-surefire-report-reporting-null/plugin-config.xml"); + SurefireReportMojo mojo = createReportMojo(testPom); mojo.execute(); File report = - new File( getBasedir(), "target/site/unit/basic-surefire-report-reporting-null/surefire-report.html" ); - renderer( mojo, report ); - assertTrue( report.exists() ); - String htmlContent = FileUtils.fileRead( report ); + new File(getBasedir(), "target/site/unit/basic-surefire-report-reporting-null/surefire-report.html"); + renderer(mojo, report); + assertTrue(report.exists()); + String htmlContent = FileUtils.fileRead(report); - int idx = htmlContent.indexOf( "./xref-test/com/shape/CircleTest.html#L44" ); - assertTrue( idx < 0 ); + int idx = htmlContent.indexOf("./xref-test/com/shape/CircleTest.html#L44"); + assertTrue(idx < 0); } - @SuppressWarnings( "checkstyle:methodname" ) - public void testBasicSurefireReport_AnchorTestCases() - throws Exception - { - File testPom = new File( getUnitBaseDir(), "basic-surefire-report-anchor-test-cases/plugin-config.xml" ); - SurefireReportMojo mojo = createReportMojo( testPom ); + @SuppressWarnings("checkstyle:methodname") + public void testBasicSurefireReport_AnchorTestCases() throws Exception { + File testPom = new File(getUnitBaseDir(), "basic-surefire-report-anchor-test-cases/plugin-config.xml"); + SurefireReportMojo mojo = createReportMojo(testPom); mojo.execute(); - File report = new File( getBasedir(), - "target/site/unit/basic-surefire-report-anchor-test-cases/surefire-report.html" ); - renderer( mojo, report ); - assertTrue( report.exists() ); - String htmlContent = FileUtils.fileRead( report ); - - int idx = htmlContent.indexOf( "testX" ); - assertTrue( idx > 0 ); - - idx = htmlContent.indexOf( "" - + "testRadius" ); - assertTrue( idx > 0 ); + File report = + new File(getBasedir(), "target/site/unit/basic-surefire-report-anchor-test-cases/surefire-report.html"); + renderer(mojo, report); + assertTrue(report.exists()); + String htmlContent = FileUtils.fileRead(report); + + int idx = htmlContent.indexOf("testX"); + assertTrue(idx > 0); + + idx = htmlContent.indexOf("" + + "testRadius"); + assertTrue(idx > 0); } - public void testSurefireReportSingleError() - throws Exception - { - File testPom = new File( getUnitBaseDir(), "surefire-report-single-error/plugin-config.xml" ); - SurefireReportMojo mojo = createReportMojo( testPom ); + public void testSurefireReportSingleError() throws Exception { + File testPom = new File(getUnitBaseDir(), "surefire-report-single-error/plugin-config.xml"); + SurefireReportMojo mojo = createReportMojo(testPom); mojo.execute(); - File report = new File( getBasedir(), "target/site/unit/surefire-report-single-error/surefire-report.html" ); - renderer( mojo, report ); - assertTrue( report.exists() ); - String htmlContent = FileUtils.fileRead( report ); - - assertThat( htmlContent, - containsString( toSystemNewLine( "\n" - + "1\n" - + "1\n" - + "0\n" - + "0\n" - + "0%\n" - + "0" ) ) ); - - assertThat( htmlContent, - containsString( toSystemNewLine( "\n" - + "surefire\n" - + "1\n" - + "1\n" - + "0\n" - + "0\n" - + "0%\n" - + "0" ) ) ); - assertThat( htmlContent, - containsString( toSystemNewLine( "\n" - + "" - + "" - + "\"\"" - + "" - + "\n" - + "MyTest\n" - + "1\n" - + "1\n" - + "0\n" - + "0\n" - + "0%\n" - + "0" ) ) ); - - assertThat( htmlContent, containsString( ">surefire.MyTest:13" ) ); - - assertThat( htmlContent, containsString( "./xref-test/surefire/MyTest.html#L13" ) ); - - assertThat( htmlContent, containsString( toSystemNewLine( "
"
-        + "java.lang.RuntimeException: java.lang.IndexOutOfBoundsException\n"
-        + "\tat surefire.MyTest.rethrownDelegate(MyTest.java:24)\n"
-        + "\tat surefire.MyTest.newRethrownDelegate(MyTest.java:17)\n"
-        + "\tat surefire.MyTest.test(MyTest.java:13)\n"
-        + "\tat sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\n"
-        + "\tat sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)\n"
-        + "\tat sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)\n"
-        + "\tat java.lang.reflect.Method.invoke(Method.java:606)\n"
-        + "\tat org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)\n"
-        + "\tat org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)\n"
-        + "\tat org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)\n"
-        + "\tat org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)\n"
-        + "\tat org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)\n"
-        + "\tat org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)\n"
-        + "\tat org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)\n"
-        + "\tat org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)\n"
-        + "\tat org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)\n"
-        + "\tat org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)\n"
-        + "\tat org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)\n"
-        + "\tat org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)\n"
-        + "\tat org.junit.runners.ParentRunner.run(ParentRunner.java:363)\n"
-        + "\tat org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:272)\n"
-        + "\tat org.apache.maven.surefire.junit4.JUnit4Provider.executeWithRerun(JUnit4Provider.java:167)\n"
-        + "\tat org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:147)\n"
-        + "\tat org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:130)\n"
-        + "\tat org.apache.maven.surefire.booter.ForkedBooter.invokeProviderInSameClassLoader(ForkedBooter.java:211)\n"
-        + "\tat org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:163)\n"
-        + "\tat org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:105)\n"
-        + "\tCaused by: java.lang.IndexOutOfBoundsException\n"
-        + "\tat surefire.MyTest.failure(MyTest.java:33)\n" + "\tat surefire.MyTest.access$100(MyTest.java:9)\n"
-        + "\tat surefire.MyTest$Nested.run(MyTest.java:38)\n"
-        + "\tat surefire.MyTest.delegate(MyTest.java:29)\n"
-        + "\tat surefire.MyTest.rethrownDelegate(MyTest.java:22)" + "
" ) ) ); + File report = new File(getBasedir(), "target/site/unit/surefire-report-single-error/surefire-report.html"); + renderer(mojo, report); + assertTrue(report.exists()); + String htmlContent = FileUtils.fileRead(report); + + assertThat( + htmlContent, + containsString(toSystemNewLine("\n" + + "1\n" + + "1\n" + + "0\n" + + "0\n" + + "0%\n" + + "0"))); + + assertThat( + htmlContent, + containsString(toSystemNewLine("\n" + + "surefire\n" + + "1\n" + + "1\n" + + "0\n" + + "0\n" + + "0%\n" + + "0"))); + assertThat( + htmlContent, + containsString(toSystemNewLine("\n" + + "" + + "" + + "\"\"" + + "" + + "\n" + + "MyTest\n" + + "1\n" + + "1\n" + + "0\n" + + "0\n" + + "0%\n" + + "0"))); + + assertThat(htmlContent, containsString(">surefire.MyTest:13")); + + assertThat(htmlContent, containsString("./xref-test/surefire/MyTest.html#L13")); + + assertThat( + htmlContent, + containsString(toSystemNewLine("
"
+                        + "java.lang.RuntimeException: java.lang.IndexOutOfBoundsException\n"
+                        + "\tat surefire.MyTest.rethrownDelegate(MyTest.java:24)\n"
+                        + "\tat surefire.MyTest.newRethrownDelegate(MyTest.java:17)\n"
+                        + "\tat surefire.MyTest.test(MyTest.java:13)\n"
+                        + "\tat sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\n"
+                        + "\tat sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)\n"
+                        + "\tat sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)\n"
+                        + "\tat java.lang.reflect.Method.invoke(Method.java:606)\n"
+                        + "\tat org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)\n"
+                        + "\tat org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)\n"
+                        + "\tat org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)\n"
+                        + "\tat org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)\n"
+                        + "\tat org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)\n"
+                        + "\tat org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)\n"
+                        + "\tat org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)\n"
+                        + "\tat org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)\n"
+                        + "\tat org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)\n"
+                        + "\tat org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)\n"
+                        + "\tat org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)\n"
+                        + "\tat org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)\n"
+                        + "\tat org.junit.runners.ParentRunner.run(ParentRunner.java:363)\n"
+                        + "\tat org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:272)\n"
+                        + "\tat org.apache.maven.surefire.junit4.JUnit4Provider.executeWithRerun(JUnit4Provider.java:167)\n"
+                        + "\tat org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:147)\n"
+                        + "\tat org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:130)\n"
+                        + "\tat org.apache.maven.surefire.booter.ForkedBooter.invokeProviderInSameClassLoader(ForkedBooter.java:211)\n"
+                        + "\tat org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:163)\n"
+                        + "\tat org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:105)\n"
+                        + "\tCaused by: java.lang.IndexOutOfBoundsException\n"
+                        + "\tat surefire.MyTest.failure(MyTest.java:33)\n"
+                        + "\tat surefire.MyTest.access$100(MyTest.java:9)\n"
+                        + "\tat surefire.MyTest$Nested.run(MyTest.java:38)\n"
+                        + "\tat surefire.MyTest.delegate(MyTest.java:29)\n"
+                        + "\tat surefire.MyTest.rethrownDelegate(MyTest.java:22)" + "
"))); } - public void testSurefireReportNestedClassTrimStackTrace() - throws Exception - { - File testPom = new File( getUnitBaseDir(), "surefire-report-nestedClass-trimStackTrace/plugin-config.xml" ); - SurefireReportMojo mojo = createReportMojo( testPom ); + public void testSurefireReportNestedClassTrimStackTrace() throws Exception { + File testPom = new File(getUnitBaseDir(), "surefire-report-nestedClass-trimStackTrace/plugin-config.xml"); + SurefireReportMojo mojo = createReportMojo(testPom); mojo.execute(); - File report = new File( getBasedir(), "target/site/unit/surefire-report-nestedClass-trimStackTrace/surefire-report.html" ); - renderer( mojo, report ); - assertTrue( report.exists() ); - String htmlContent = FileUtils.fileRead( report ); - - assertThat( htmlContent, - containsString( toSystemNewLine( "\n" - + "1\n" - + "1\n" - + "0\n" - + "0\n" - + "0%\n" - + "0" ) ) ); - - assertThat( htmlContent, - containsString( toSystemNewLine( "\n" - + "surefire\n" - + "1\n" - + "1\n" - + "0\n" - + "0\n" - + "0%\n" - + "0" ) ) ); - assertThat( htmlContent, - containsString( toSystemNewLine( "\n" - + "" - + "" - + "\"\"" - + "" - + "\n" - + "MyTest\n" - + "1\n" - + "1\n" - + "0\n" - + "0\n" - + "0%\n" - + "0" ) ) ); - assertThat( htmlContent, - containsString( ">surefire.MyTest:13" ) ); - - assertThat( htmlContent, containsString( "./xref-test/surefire/MyTest.html#L13" ) ); - - assertThat( htmlContent, containsString( toSystemNewLine( "
"
-        + "java.lang.RuntimeException: java.lang.IndexOutOfBoundsException\n"
-        + "\tat surefire.MyTest.rethrownDelegate(MyTest.java:24)\n"
-        + "\tat surefire.MyTest.newRethrownDelegate(MyTest.java:17)\n"
-        + "\tat surefire.MyTest.test(MyTest.java:13)\n"
-        + "\tCaused by: java.lang.IndexOutOfBoundsException\n"
-        + "\tat surefire.MyTest.failure(MyTest.java:33)\n"
-        + "\tat surefire.MyTest.access$100(MyTest.java:9)\n"
-        + "\tat surefire.MyTest$Nested.run(MyTest.java:38)\n"
-        + "\tat surefire.MyTest.delegate(MyTest.java:29)\n"
-        + "\tat surefire.MyTest.rethrownDelegate(MyTest.java:22)"
-        + "
" ) ) ); + File report = new File( + getBasedir(), "target/site/unit/surefire-report-nestedClass-trimStackTrace/surefire-report.html"); + renderer(mojo, report); + assertTrue(report.exists()); + String htmlContent = FileUtils.fileRead(report); + + assertThat( + htmlContent, + containsString(toSystemNewLine("\n" + + "1\n" + + "1\n" + + "0\n" + + "0\n" + + "0%\n" + + "0"))); + + assertThat( + htmlContent, + containsString(toSystemNewLine("\n" + + "surefire\n" + + "1\n" + + "1\n" + + "0\n" + + "0\n" + + "0%\n" + + "0"))); + assertThat( + htmlContent, + containsString(toSystemNewLine("\n" + + "" + + "" + + "\"\"" + + "" + + "\n" + + "MyTest\n" + + "1\n" + + "1\n" + + "0\n" + + "0\n" + + "0%\n" + + "0"))); + assertThat(htmlContent, containsString(">surefire.MyTest:13")); + + assertThat(htmlContent, containsString("./xref-test/surefire/MyTest.html#L13")); + + assertThat( + htmlContent, + containsString(toSystemNewLine("
"
+                        + "java.lang.RuntimeException: java.lang.IndexOutOfBoundsException\n"
+                        + "\tat surefire.MyTest.rethrownDelegate(MyTest.java:24)\n"
+                        + "\tat surefire.MyTest.newRethrownDelegate(MyTest.java:17)\n"
+                        + "\tat surefire.MyTest.test(MyTest.java:13)\n"
+                        + "\tCaused by: java.lang.IndexOutOfBoundsException\n"
+                        + "\tat surefire.MyTest.failure(MyTest.java:33)\n"
+                        + "\tat surefire.MyTest.access$100(MyTest.java:9)\n"
+                        + "\tat surefire.MyTest$Nested.run(MyTest.java:38)\n"
+                        + "\tat surefire.MyTest.delegate(MyTest.java:29)\n"
+                        + "\tat surefire.MyTest.rethrownDelegate(MyTest.java:22)"
+                        + "
"))); } - public void testSurefireReportNestedClass() - throws Exception - { - File testPom = new File( getUnitBaseDir(), "surefire-report-nestedClass/plugin-config.xml" ); - SurefireReportMojo mojo = createReportMojo( testPom ); + public void testSurefireReportNestedClass() throws Exception { + File testPom = new File(getUnitBaseDir(), "surefire-report-nestedClass/plugin-config.xml"); + SurefireReportMojo mojo = createReportMojo(testPom); mojo.execute(); - File report = new File( getBasedir(), "target/site/unit/surefire-report-nestedClass/surefire-report.html" ); - renderer( mojo, report ); - assertTrue( report.exists() ); - String htmlContent = FileUtils.fileRead( report ); - - assertThat( htmlContent, - containsString( toSystemNewLine( "\n" - + "1\n" - + "1\n" - + "0\n" - + "0\n" - + "0%\n" - + "0" ) ) ); - - assertThat( htmlContent, - containsString( toSystemNewLine( "\n" - + "surefire\n" - + "1\n" - + "1\n" - + "0\n" - + "0\n" - + "0%\n" - + "0" ) ) ); - assertThat( htmlContent, - containsString( toSystemNewLine( "\n" - + "" - + "" - + "\"\"" - + "" - + "\n" - + "MyTest\n" - + "1\n" - + "1\n" - + "0\n" - + "0\n" - + "0%\n" - + "0" ) ) ); - assertThat( htmlContent, - containsString( ">surefire.MyTest:13" ) ); - - assertThat( htmlContent, containsString( "./xref-test/surefire/MyTest.html#L13" ) ); - - assertThat( htmlContent, containsString( toSystemNewLine( "
"
-        + "java.lang.RuntimeException: java.lang.IndexOutOfBoundsException\n"
-        + "\tat surefire.MyTest.rethrownDelegate(MyTest.java:24)\n"
-        + "\tat surefire.MyTest.newRethrownDelegate(MyTest.java:17)\n"
-        + "\tat surefire.MyTest.test(MyTest.java:13)\n"
-        + "\tat sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\n"
-        + "\tat sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)\n"
-        + "\tat sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)\n"
-        + "\tat java.lang.reflect.Method.invoke(Method.java:606)\n"
-        + "\tat org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)\n"
-        + "\tat org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)\n"
-        + "\tat org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)\n"
-        + "\tat org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)\n"
-        + "\tat org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)\n"
-        + "\tat org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)\n"
-        + "\tat org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)\n"
-        + "\tat org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)\n"
-        + "\tat org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)\n"
-        + "\tat org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)\n"
-        + "\tat org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)\n"
-        + "\tat org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)\n"
-        + "\tat org.junit.runners.ParentRunner.run(ParentRunner.java:363)\n"
-        + "\tat org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:272)\n"
-        + "\tat org.apache.maven.surefire.junit4.JUnit4Provider.executeWithRerun(JUnit4Provider.java:167)\n"
-        + "\tat org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:147)\n"
-        + "\tat org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:130)\n"
-        + "\tat org.apache.maven.surefire.booter.ForkedBooter.invokeProviderInSameClassLoader(ForkedBooter.java:211)\n"
-        + "\tat org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:163)\n"
-        + "\tat org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:105)\n"
-        + "\tCaused by: java.lang.IndexOutOfBoundsException\n"
-        + "\tat surefire.MyTest.failure(MyTest.java:33)\n"
-        + "\tat surefire.MyTest.access$100(MyTest.java:9)\n"
-        + "\tat surefire.MyTest$Nested.run(MyTest.java:38)\n"
-        + "\tat surefire.MyTest.delegate(MyTest.java:29)\n"
-        + "\tat surefire.MyTest.rethrownDelegate(MyTest.java:22)"
-        + "
" ) ) ); + File report = new File(getBasedir(), "target/site/unit/surefire-report-nestedClass/surefire-report.html"); + renderer(mojo, report); + assertTrue(report.exists()); + String htmlContent = FileUtils.fileRead(report); + + assertThat( + htmlContent, + containsString(toSystemNewLine("\n" + + "1\n" + + "1\n" + + "0\n" + + "0\n" + + "0%\n" + + "0"))); + + assertThat( + htmlContent, + containsString(toSystemNewLine("\n" + + "surefire\n" + + "1\n" + + "1\n" + + "0\n" + + "0\n" + + "0%\n" + + "0"))); + assertThat( + htmlContent, + containsString(toSystemNewLine("\n" + + "" + + "" + + "\"\"" + + "" + + "\n" + + "MyTest\n" + + "1\n" + + "1\n" + + "0\n" + + "0\n" + + "0%\n" + + "0"))); + assertThat(htmlContent, containsString(">surefire.MyTest:13")); + + assertThat(htmlContent, containsString("./xref-test/surefire/MyTest.html#L13")); + + assertThat( + htmlContent, + containsString(toSystemNewLine("
"
+                        + "java.lang.RuntimeException: java.lang.IndexOutOfBoundsException\n"
+                        + "\tat surefire.MyTest.rethrownDelegate(MyTest.java:24)\n"
+                        + "\tat surefire.MyTest.newRethrownDelegate(MyTest.java:17)\n"
+                        + "\tat surefire.MyTest.test(MyTest.java:13)\n"
+                        + "\tat sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\n"
+                        + "\tat sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)\n"
+                        + "\tat sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)\n"
+                        + "\tat java.lang.reflect.Method.invoke(Method.java:606)\n"
+                        + "\tat org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)\n"
+                        + "\tat org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)\n"
+                        + "\tat org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)\n"
+                        + "\tat org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)\n"
+                        + "\tat org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)\n"
+                        + "\tat org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)\n"
+                        + "\tat org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)\n"
+                        + "\tat org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)\n"
+                        + "\tat org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)\n"
+                        + "\tat org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)\n"
+                        + "\tat org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)\n"
+                        + "\tat org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)\n"
+                        + "\tat org.junit.runners.ParentRunner.run(ParentRunner.java:363)\n"
+                        + "\tat org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:272)\n"
+                        + "\tat org.apache.maven.surefire.junit4.JUnit4Provider.executeWithRerun(JUnit4Provider.java:167)\n"
+                        + "\tat org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:147)\n"
+                        + "\tat org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:130)\n"
+                        + "\tat org.apache.maven.surefire.booter.ForkedBooter.invokeProviderInSameClassLoader(ForkedBooter.java:211)\n"
+                        + "\tat org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:163)\n"
+                        + "\tat org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:105)\n"
+                        + "\tCaused by: java.lang.IndexOutOfBoundsException\n"
+                        + "\tat surefire.MyTest.failure(MyTest.java:33)\n"
+                        + "\tat surefire.MyTest.access$100(MyTest.java:9)\n"
+                        + "\tat surefire.MyTest$Nested.run(MyTest.java:38)\n"
+                        + "\tat surefire.MyTest.delegate(MyTest.java:29)\n"
+                        + "\tat surefire.MyTest.rethrownDelegate(MyTest.java:22)"
+                        + "
"))); } - public void testSurefireReportEnclosedTrimStackTrace() - throws Exception - { - File testPom = new File( getUnitBaseDir(), "surefire-report-enclosed-trimStackTrace/plugin-config.xml" ); - SurefireReportMojo mojo = createReportMojo( testPom ); + public void testSurefireReportEnclosedTrimStackTrace() throws Exception { + File testPom = new File(getUnitBaseDir(), "surefire-report-enclosed-trimStackTrace/plugin-config.xml"); + SurefireReportMojo mojo = createReportMojo(testPom); mojo.execute(); - File report = new File( getBasedir(), "target/site/unit/surefire-report-enclosed-trimStackTrace/surefire-report.html" ); - renderer( mojo, report ); - assertTrue( report.exists() ); - String htmlContent = FileUtils.fileRead( report ); - - assertThat( htmlContent, - containsString( toSystemNewLine( "\n" - + "1\n" - + "1\n" - + "0\n" - + "0\n" - + "0%\n" - + "0" ) ) ); - - assertThat( htmlContent, - containsString( toSystemNewLine( "\n" - + "surefire\n" - + "1\n" - + "1\n" - + "0\n" - + "0\n" - + "0%\n" - + "0" ) ) ); - assertThat( htmlContent, - containsString( toSystemNewLine( "\n" - + "" - + "" - + "\"\"" - + "" - + "\n" - + "MyTest$A\n" - + "1\n" - + "1\n" - + "0\n" - + "0\n" - + "0%\n" - + "0" ) ) ); - - assertThat( htmlContent, containsString( ">surefire.MyTest$A:45" ) ); - - assertThat( htmlContent, containsString( "./xref-test/surefire/MyTest$A.html#L45" ) ); - - assertThat( htmlContent, containsString( toSystemNewLine( "
"
-        + "java.lang.RuntimeException: java.lang.IndexOutOfBoundsException\n"
-        + "\tat surefire.MyTest.failure(MyTest.java:33)\n"
-        + "\tat surefire.MyTest.access$100(MyTest.java:9)\n"
-        + "\tat surefire.MyTest$Nested.run(MyTest.java:38)\n"
-        + "\tat surefire.MyTest.delegate(MyTest.java:29)\n"
-        + "\tat surefire.MyTest.rethrownDelegate(MyTest.java:22)\n"
-        + "\tat surefire.MyTest.newRethrownDelegate(MyTest.java:17)\n"
-        + "\tat surefire.MyTest.access$200(MyTest.java:9)\n"
-        + "\tat surefire.MyTest$A.t(MyTest.java:45)\n"
-        + "
" ) ) ); + File report = + new File(getBasedir(), "target/site/unit/surefire-report-enclosed-trimStackTrace/surefire-report.html"); + renderer(mojo, report); + assertTrue(report.exists()); + String htmlContent = FileUtils.fileRead(report); + + assertThat( + htmlContent, + containsString(toSystemNewLine("\n" + + "1\n" + + "1\n" + + "0\n" + + "0\n" + + "0%\n" + + "0"))); + + assertThat( + htmlContent, + containsString(toSystemNewLine("\n" + + "surefire\n" + + "1\n" + + "1\n" + + "0\n" + + "0\n" + + "0%\n" + + "0"))); + assertThat( + htmlContent, + containsString(toSystemNewLine("\n" + + "" + + "" + + "\"\"" + + "" + + "\n" + + "MyTest$A\n" + + "1\n" + + "1\n" + + "0\n" + + "0\n" + + "0%\n" + + "0"))); + + assertThat(htmlContent, containsString(">surefire.MyTest$A:45")); + + assertThat(htmlContent, containsString("./xref-test/surefire/MyTest$A.html#L45")); + + assertThat( + htmlContent, + containsString(toSystemNewLine("
"
+                        + "java.lang.RuntimeException: java.lang.IndexOutOfBoundsException\n"
+                        + "\tat surefire.MyTest.failure(MyTest.java:33)\n"
+                        + "\tat surefire.MyTest.access$100(MyTest.java:9)\n"
+                        + "\tat surefire.MyTest$Nested.run(MyTest.java:38)\n"
+                        + "\tat surefire.MyTest.delegate(MyTest.java:29)\n"
+                        + "\tat surefire.MyTest.rethrownDelegate(MyTest.java:22)\n"
+                        + "\tat surefire.MyTest.newRethrownDelegate(MyTest.java:17)\n"
+                        + "\tat surefire.MyTest.access$200(MyTest.java:9)\n"
+                        + "\tat surefire.MyTest$A.t(MyTest.java:45)\n"
+                        + "
"))); } - public void testSurefireReportEnclosed() - throws Exception - { - File testPom = new File( getUnitBaseDir(), "surefire-report-enclosed/plugin-config.xml" ); - SurefireReportMojo mojo = createReportMojo( testPom ); + public void testSurefireReportEnclosed() throws Exception { + File testPom = new File(getUnitBaseDir(), "surefire-report-enclosed/plugin-config.xml"); + SurefireReportMojo mojo = createReportMojo(testPom); mojo.execute(); - File report = new File( getBasedir(), "target/site/unit/surefire-report-enclosed/surefire-report.html" ); - renderer( mojo, report ); - assertTrue( report.exists() ); - String htmlContent = FileUtils.fileRead( report ); - - assertThat( htmlContent, - containsString( toSystemNewLine( "\n" - + "1\n" - + "1\n" - + "0\n" - + "0\n" - + "0%\n" - + "0" ) ) ); - - assertThat( htmlContent, - containsString( toSystemNewLine( "\n" - + "surefire\n" - + "1\n" - + "1\n" - + "0\n" - + "0\n" - + "0%\n" - + "0" ) ) ); - assertThat( htmlContent, - containsString( toSystemNewLine( "\n" - + "" - + "" - + "\"\"" - + "" - + "\n" - + "MyTest$A\n" - + "1\n" - + "1\n" - + "0\n" - + "0\n" - + "0%\n" - + "0" ) ) ); - - assertThat( htmlContent, containsString( ">surefire.MyTest$A:45" ) ); - - assertThat( htmlContent, containsString( "./xref-test/surefire/MyTest$A.html#L45" ) ); - - assertThat( htmlContent, containsString( toSystemNewLine( - "
" + "java.lang.RuntimeException: java.lang.IndexOutOfBoundsException\n"
-                + "\tat surefire.MyTest.rethrownDelegate(MyTest.java:24)\n"
-                + "\tat surefire.MyTest.newRethrownDelegate(MyTest.java:17)\n"
-                + "\tat surefire.MyTest.access$200(MyTest.java:9)\n" + "\tat surefire.MyTest$A.t(MyTest.java:45)\n"
-                + "\tat sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\n"
-                + "\tat sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)\n"
-                + "\tat sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)\n"
-                + "\tat java.lang.reflect.Method.invoke(Method.java:606)\n"
-                + "\tat org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)\n"
-                + "\tat org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)\n"
-                + "\tat org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)\n"
-                + "\tat org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)\n"
-                + "\tat org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)\n"
-                + "\tat org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)\n"
-                + "\tat org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)\n"
-                + "\tat org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)\n"
-                + "\tat org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)\n"
-                + "\tat org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)\n"
-                + "\tat org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)\n"
-                + "\tat org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)\n"
-                + "\tat org.junit.runners.ParentRunner.run(ParentRunner.java:363)\n"
-                + "\tat org.junit.runners.Suite.runChild(Suite.java:128)\n"
-                + "\tat org.junit.runners.Suite.runChild(Suite.java:27)\n"
-                + "\tat org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)\n"
-                + "\tat org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)\n"
-                + "\tat org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)\n"
-                + "\tat org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)\n"
-                + "\tat org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)\n"
-                + "\tat org.junit.runners.ParentRunner.run(ParentRunner.java:363)\n"
-                + "\tat org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:272)\n"
-                + "\tat org.apache.maven.surefire.junit4.JUnit4Provider.executeWithRerun(JUnit4Provider.java:167)\n"
-                + "\tat org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:147)\n"
-                + "\tat org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:130)\n"
-                + "\tat org.apache.maven.surefire.booter.ForkedBooter.invokeProviderInSameClassLoader(ForkedBooter.java:211)\n"
-                + "\tat org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:163)\n"
-                + "\tat org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:105)\n"
-                + "\tCaused by: java.lang.IndexOutOfBoundsException\n"
-                + "\tat surefire.MyTest.failure(MyTest.java:33)\n" + "\tat surefire.MyTest.access$100(MyTest.java:9)\n"
-                + "\tat surefire.MyTest$Nested.run(MyTest.java:38)\n"
-                + "\tat surefire.MyTest.delegate(MyTest.java:29)\n"
-                + "\tat surefire.MyTest.rethrownDelegate(MyTest.java:22)\n"
-                + "
" ) ) ); + File report = new File(getBasedir(), "target/site/unit/surefire-report-enclosed/surefire-report.html"); + renderer(mojo, report); + assertTrue(report.exists()); + String htmlContent = FileUtils.fileRead(report); + + assertThat( + htmlContent, + containsString(toSystemNewLine("\n" + + "1\n" + + "1\n" + + "0\n" + + "0\n" + + "0%\n" + + "0"))); + + assertThat( + htmlContent, + containsString(toSystemNewLine("\n" + + "surefire\n" + + "1\n" + + "1\n" + + "0\n" + + "0\n" + + "0%\n" + + "0"))); + assertThat( + htmlContent, + containsString(toSystemNewLine("\n" + + "" + + "" + + "\"\"" + + "" + + "\n" + + "MyTest$A\n" + + "1\n" + + "1\n" + + "0\n" + + "0\n" + + "0%\n" + + "0"))); + + assertThat(htmlContent, containsString(">surefire.MyTest$A:45")); + + assertThat(htmlContent, containsString("./xref-test/surefire/MyTest$A.html#L45")); + + assertThat( + htmlContent, + containsString( + toSystemNewLine("
" + "java.lang.RuntimeException: java.lang.IndexOutOfBoundsException\n"
+                                + "\tat surefire.MyTest.rethrownDelegate(MyTest.java:24)\n"
+                                + "\tat surefire.MyTest.newRethrownDelegate(MyTest.java:17)\n"
+                                + "\tat surefire.MyTest.access$200(MyTest.java:9)\n"
+                                + "\tat surefire.MyTest$A.t(MyTest.java:45)\n"
+                                + "\tat sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\n"
+                                + "\tat sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)\n"
+                                + "\tat sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)\n"
+                                + "\tat java.lang.reflect.Method.invoke(Method.java:606)\n"
+                                + "\tat org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)\n"
+                                + "\tat org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)\n"
+                                + "\tat org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)\n"
+                                + "\tat org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)\n"
+                                + "\tat org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)\n"
+                                + "\tat org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)\n"
+                                + "\tat org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)\n"
+                                + "\tat org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)\n"
+                                + "\tat org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)\n"
+                                + "\tat org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)\n"
+                                + "\tat org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)\n"
+                                + "\tat org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)\n"
+                                + "\tat org.junit.runners.ParentRunner.run(ParentRunner.java:363)\n"
+                                + "\tat org.junit.runners.Suite.runChild(Suite.java:128)\n"
+                                + "\tat org.junit.runners.Suite.runChild(Suite.java:27)\n"
+                                + "\tat org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)\n"
+                                + "\tat org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)\n"
+                                + "\tat org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)\n"
+                                + "\tat org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)\n"
+                                + "\tat org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)\n"
+                                + "\tat org.junit.runners.ParentRunner.run(ParentRunner.java:363)\n"
+                                + "\tat org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:272)\n"
+                                + "\tat org.apache.maven.surefire.junit4.JUnit4Provider.executeWithRerun(JUnit4Provider.java:167)\n"
+                                + "\tat org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:147)\n"
+                                + "\tat org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:130)\n"
+                                + "\tat org.apache.maven.surefire.booter.ForkedBooter.invokeProviderInSameClassLoader(ForkedBooter.java:211)\n"
+                                + "\tat org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:163)\n"
+                                + "\tat org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:105)\n"
+                                + "\tCaused by: java.lang.IndexOutOfBoundsException\n"
+                                + "\tat surefire.MyTest.failure(MyTest.java:33)\n"
+                                + "\tat surefire.MyTest.access$100(MyTest.java:9)\n"
+                                + "\tat surefire.MyTest$Nested.run(MyTest.java:38)\n"
+                                + "\tat surefire.MyTest.delegate(MyTest.java:29)\n"
+                                + "\tat surefire.MyTest.rethrownDelegate(MyTest.java:22)\n"
+                                + "
"))); } - public void testCustomTitleAndDescriptionReport() - throws Exception - { - File testPom = new File( getUnitBaseDir(), "surefire-1183/plugin-config.xml" ); - SurefireReportMojo mojo = createReportMojo( testPom ); - - File outputDir = (File) getVariableValueFromObject( mojo, "outputDirectory" ); - String outputName = (String) getVariableValueFromObject( mojo, "outputName" ); - File reportsDir = (File) getVariableValueFromObject( mojo, "reportsDirectory" ); - String title = (String) getVariableValueFromObject( mojo, "title" ); - String description = (String) getVariableValueFromObject( mojo, "description" ); - - assertEquals( new File( getBasedir() + "/target/site/unit/surefire-1183" ), outputDir ); - assertEquals( new File( getBasedir() + "/src/test/resources/unit/surefire-1183/acceptancetest-reports" ) - .getAbsolutePath(), reportsDir.getAbsolutePath() ); - assertEquals( "acceptance-test-report", outputName ); - assertEquals( "Acceptance Test", title ); - assertEquals( "Acceptance Test Description", description ); + public void testCustomTitleAndDescriptionReport() throws Exception { + File testPom = new File(getUnitBaseDir(), "surefire-1183/plugin-config.xml"); + SurefireReportMojo mojo = createReportMojo(testPom); + + File outputDir = (File) getVariableValueFromObject(mojo, "outputDirectory"); + String outputName = (String) getVariableValueFromObject(mojo, "outputName"); + File reportsDir = (File) getVariableValueFromObject(mojo, "reportsDirectory"); + String title = (String) getVariableValueFromObject(mojo, "title"); + String description = (String) getVariableValueFromObject(mojo, "description"); + + assertEquals(new File(getBasedir() + "/target/site/unit/surefire-1183"), outputDir); + assertEquals( + new File(getBasedir() + "/src/test/resources/unit/surefire-1183/acceptancetest-reports") + .getAbsolutePath(), + reportsDir.getAbsolutePath()); + assertEquals("acceptance-test-report", outputName); + assertEquals("Acceptance Test", title); + assertEquals("Acceptance Test Description", description); mojo.execute(); - File report = new File( getBasedir(), "target/site/acceptance-test-report.html" ); - renderer( mojo, report ); + File report = new File(getBasedir(), "target/site/acceptance-test-report.html"); + renderer(mojo, report); - assertTrue( report.exists() ); + assertTrue(report.exists()); - String htmlContent = FileUtils.fileRead ( report ); - assertTrue( htmlContent.contains ( "

Acceptance Test

" ) ); + String htmlContent = FileUtils.fileRead(report); + assertTrue(htmlContent.contains("

Acceptance Test

")); } /** @@ -625,25 +645,20 @@ public void testCustomTitleAndDescriptionReport() * @throws RendererException if any * @throws IOException if any */ - private void renderer( SurefireReportMojo mojo, File outputHtml ) - throws RendererException, IOException - { + private void renderer(SurefireReportMojo mojo, File outputHtml) throws RendererException, IOException { Writer writer = null; SiteRenderingContext context = new SiteRenderingContext(); - context.setDecoration( new DecorationModel() ); - context.setTemplateName( "org/apache/maven/doxia/siterenderer/resources/default-site.vm" ); - context.setLocale( Locale.ENGLISH ); + context.setDecoration(new DecorationModel()); + context.setTemplateName("org/apache/maven/doxia/siterenderer/resources/default-site.vm"); + context.setLocale(Locale.ENGLISH); - try - { + try { outputHtml.getParentFile().mkdirs(); - writer = WriterFactory.newXmlWriter( outputHtml ); + writer = WriterFactory.newXmlWriter(outputHtml); - renderer.generateDocument( writer, (SiteRendererSink) mojo.getSink(), context ); - } - finally - { - IOUtil.close( writer ); + renderer.generateDocument(writer, (SiteRendererSink) mojo.getSink(), context); + } finally { + IOUtil.close(writer); } } } diff --git a/maven-surefire-report-plugin/src/test/java/org/apache/maven/plugins/surefire/report/SurefireSchemaValidationTest.java b/maven-surefire-report-plugin/src/test/java/org/apache/maven/plugins/surefire/report/SurefireSchemaValidationTest.java index 2d9f1679c9..8e28c95daa 100644 --- a/maven-surefire-report-plugin/src/test/java/org/apache/maven/plugins/surefire/report/SurefireSchemaValidationTest.java +++ b/maven-surefire-report-plugin/src/test/java/org/apache/maven/plugins/surefire/report/SurefireSchemaValidationTest.java @@ -1,3 +1,21 @@ +/* + * 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.maven.plugins.surefire.report; /* @@ -19,6 +37,8 @@ * under the License. */ +import javax.xml.transform.stream.StreamSource; + import java.io.File; import java.io.IOException; import java.net.URISyntaxException; @@ -26,8 +46,6 @@ import java.nio.file.Path; import java.nio.file.Paths; -import javax.xml.transform.stream.StreamSource; - import junit.framework.TestCase; import org.apache.maven.shared.utils.io.DirectoryScanner; import org.junit.Assert; @@ -41,64 +59,68 @@ /** * */ -public class SurefireSchemaValidationTest - extends TestCase -{ - @SuppressWarnings( "checkstyle:methodname" ) - public void testValidate_XMLs_against_schema() - throws Exception - { +public class SurefireSchemaValidationTest extends TestCase { + @SuppressWarnings("checkstyle:methodname") + public void testValidate_XMLs_against_schema() throws Exception { File basedir = getProjectBasedir(); - File xsd = getSchemaFile( basedir ); - Assert.assertTrue( "XSD schema validation not found", xsd.exists() ); + File xsd = getSchemaFile(basedir); + Assert.assertTrue("XSD schema validation not found", xsd.exists()); // looks for all xml surefire report in test resources DirectoryScanner ds = new DirectoryScanner(); - ds.setBasedir( basedir ); - ds.setIncludes( "**/TEST-*.xml" ); + ds.setBasedir(basedir); + ds.setIncludes("**/TEST-*.xml"); ds.scan(); String[] xmlFiles = ds.getIncludedFiles(); - assertThat( xmlFiles ).describedAs( "No XML surefire reports found to validate" ).isNotEmpty(); + assertThat(xmlFiles) + .describedAs("No XML surefire reports found to validate") + .isNotEmpty(); - Validator v = Validator.forLanguage( Languages.W3C_XML_SCHEMA_NS_URI ); - v.setSchemaSource( new StreamSource( xsd ) ); + Validator v = Validator.forLanguage(Languages.W3C_XML_SCHEMA_NS_URI); + v.setSchemaSource(new StreamSource(xsd)); - for ( String xmlFile : xmlFiles ) - { - ValidationResult vr = v.validateInstance( new StreamSource( new File( basedir, xmlFile ) ) ); + for (String xmlFile : xmlFiles) { + ValidationResult vr = v.validateInstance(new StreamSource(new File(basedir, xmlFile))); StringBuilder msg = new StringBuilder(); - if ( !vr.isValid() ) - { - msg.append( xmlFile ).append( " has violations:" ); - for ( ValidationProblem problem : vr.getProblems() ) - { - msg.append( "\n" ) // - .append( " - " ).append( problem.getType() ) // - .append( " at row:" ).append( problem.getLine() ) // - .append( " col:" ).append( problem.getColumn() ) // - .append( ' ' ).append( problem.getMessage() ); + if (!vr.isValid()) { + msg.append(xmlFile).append(" has violations:"); + for (ValidationProblem problem : vr.getProblems()) { + msg.append("\n") // + .append(" - ") + .append(problem.getType()) // + .append(" at row:") + .append(problem.getLine()) // + .append(" col:") + .append(problem.getColumn()) // + .append(' ') + .append(problem.getMessage()); } } - Assert.assertTrue( Utils.toSystemNewLine( msg.toString() ), vr.isValid() ); + Assert.assertTrue(Utils.toSystemNewLine(msg.toString()), vr.isValid()); } } - private File getProjectBasedir() - throws URISyntaxException - { + private File getProjectBasedir() throws URISyntaxException { // get the root path of test-classes - URL basedirURL = SurefireSchemaValidationTest.class.getClassLoader().getResource( "." ); - return new File( basedirURL.toURI() ); + URL basedirURL = SurefireSchemaValidationTest.class.getClassLoader().getResource("."); + return new File(basedirURL.toURI()); } - private File getSchemaFile( File basedir ) - throws IOException - { + private File getSchemaFile(File basedir) throws IOException { // get the schema file placed in a different module - Path xsd = Paths.get( basedir.getAbsolutePath(), "..", "..", "..", "maven-surefire-plugin", "src", "site", - "resources", "xsd", "surefire-test-report-3.0.xsd" ); + Path xsd = Paths.get( + basedir.getAbsolutePath(), + "..", + "..", + "..", + "maven-surefire-plugin", + "src", + "site", + "resources", + "xsd", + "surefire-test-report-3.0.xsd"); return xsd.toFile().getCanonicalFile(); } } diff --git a/maven-surefire-report-plugin/src/test/java/org/apache/maven/plugins/surefire/report/Utils.java b/maven-surefire-report-plugin/src/test/java/org/apache/maven/plugins/surefire/report/Utils.java index 0c689de3bb..00f4776af3 100644 --- a/maven-surefire-report-plugin/src/test/java/org/apache/maven/plugins/surefire/report/Utils.java +++ b/maven-surefire-report-plugin/src/test/java/org/apache/maven/plugins/surefire/report/Utils.java @@ -1,3 +1,21 @@ +/* + * 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.maven.plugins.surefire.report; /* @@ -22,23 +40,17 @@ /** * */ -public final class Utils -{ - private Utils() - { - throw new IllegalStateException( "no instantiable constructor" ); +public final class Utils { + private Utils() { + throw new IllegalStateException("no instantiable constructor"); } - public static String toSystemNewLine( String s ) - { - String newLine = System.getProperty( "line.separator" ); - StringBuilder b = new StringBuilder( s ); - for ( int i = 0; i < b.length(); i++ ) - { - if ( b.charAt( i ) == '\n' ) - { - b.deleteCharAt( i ) - .insert( i, newLine ); + public static String toSystemNewLine(String s) { + String newLine = System.getProperty("line.separator"); + StringBuilder b = new StringBuilder(s); + for (int i = 0; i < b.length(); i++) { + if (b.charAt(i) == '\n') { + b.deleteCharAt(i).insert(i, newLine); i += newLine.length() - 1; } } diff --git a/maven-surefire-report-plugin/src/test/java/org/apache/maven/plugins/surefire/report/stubs/DependencyArtifactStubFactory.java b/maven-surefire-report-plugin/src/test/java/org/apache/maven/plugins/surefire/report/stubs/DependencyArtifactStubFactory.java index e91d6467ee..01c383f45b 100644 --- a/maven-surefire-report-plugin/src/test/java/org/apache/maven/plugins/surefire/report/stubs/DependencyArtifactStubFactory.java +++ b/maven-surefire-report-plugin/src/test/java/org/apache/maven/plugins/surefire/report/stubs/DependencyArtifactStubFactory.java @@ -1,3 +1,21 @@ +/* + * 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.maven.plugins.surefire.report.stubs; /* @@ -31,42 +49,44 @@ * DependencyArtifactStubFactory * */ -public class DependencyArtifactStubFactory - extends ArtifactStubFactory -{ +public class DependencyArtifactStubFactory extends ArtifactStubFactory { private boolean flattenedPath = true; - public DependencyArtifactStubFactory( File theWorkingDir, boolean theCreateFiles, boolean flattenedPath ) - { - this( theWorkingDir, theCreateFiles ); + public DependencyArtifactStubFactory(File theWorkingDir, boolean theCreateFiles, boolean flattenedPath) { + this(theWorkingDir, theCreateFiles); this.flattenedPath = flattenedPath; } - public DependencyArtifactStubFactory( File theWorkingDir, boolean theCreateFiles ) - { - super( theWorkingDir, theCreateFiles ); + public DependencyArtifactStubFactory(File theWorkingDir, boolean theCreateFiles) { + super(theWorkingDir, theCreateFiles); } @Override - public Artifact createArtifact( String groupId, String artifactId, VersionRange versionRange, String scope, - String type, String classifier, boolean optional ) - throws IOException - { + public Artifact createArtifact( + String groupId, + String artifactId, + VersionRange versionRange, + String scope, + String type, + String classifier, + boolean optional) + throws IOException { File workingDir = getWorkingDir(); - if ( !flattenedPath ) - { + if (!flattenedPath) { // don't use flatten directories, won't happen at runtime - String path = groupId.replace( '.', '/' ) + '/' - + artifactId + '/' - + ArtifactUtils.toSnapshotVersion( versionRange.getRecommendedVersion().toString() ); - setWorkingDir( new File( workingDir, path ) ); + String path = groupId.replace('.', '/') + + '/' + + artifactId + + '/' + + ArtifactUtils.toSnapshotVersion( + versionRange.getRecommendedVersion().toString()); + setWorkingDir(new File(workingDir, path)); } - Artifact artifact = - super.createArtifact( groupId, artifactId, versionRange, scope, type, classifier, optional ); + Artifact artifact = super.createArtifact(groupId, artifactId, versionRange, scope, type, classifier, optional); - setWorkingDir( workingDir ); + setWorkingDir(workingDir); return artifact; } diff --git a/maven-surefire-report-plugin/src/test/java/org/apache/maven/plugins/surefire/report/stubs/SurefireRepMavenProjectStub.java b/maven-surefire-report-plugin/src/test/java/org/apache/maven/plugins/surefire/report/stubs/SurefireRepMavenProjectStub.java index cc2bac2903..33a6e14a46 100644 --- a/maven-surefire-report-plugin/src/test/java/org/apache/maven/plugins/surefire/report/stubs/SurefireRepMavenProjectStub.java +++ b/maven-surefire-report-plugin/src/test/java/org/apache/maven/plugins/surefire/report/stubs/SurefireRepMavenProjectStub.java @@ -1,3 +1,21 @@ +/* + * 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.maven.plugins.surefire.report.stubs; /* @@ -19,8 +37,9 @@ * under the License. */ -import java.util.List; import java.util.Collections; +import java.util.List; + import org.apache.maven.artifact.repository.ArtifactRepository; import org.apache.maven.artifact.repository.ArtifactRepositoryPolicy; import org.apache.maven.artifact.repository.MavenArtifactRepository; @@ -33,39 +52,36 @@ /** * @author Allan Ramirez */ -public class SurefireRepMavenProjectStub - extends MavenProjectStub -{ +public class SurefireRepMavenProjectStub extends MavenProjectStub { /** * {@inheritDoc} */ @Override - public List getReportPlugins() - { + public List getReportPlugins() { Reporting reporting = new Reporting(); ReportPlugin reportPlugin = new ReportPlugin(); - reportPlugin.setGroupId( "org.apache.maven.plugins" ); - reportPlugin.setArtifactId( "maven-jxr-plugin" ); - reportPlugin.setVersion( "2.0-SNAPSHOT" ); - reporting.addPlugin( reportPlugin ); + reportPlugin.setGroupId("org.apache.maven.plugins"); + reportPlugin.setArtifactId("maven-jxr-plugin"); + reportPlugin.setVersion("2.0-SNAPSHOT"); + reporting.addPlugin(reportPlugin); Model model = new Model(); - model.setReporting( reporting ); + model.setReporting(reporting); return reporting.getPlugins(); } @Override - public List getRemoteArtifactRepositories() - { - ArtifactRepository repository = - new MavenArtifactRepository( "central", "https://repo1.maven.org/maven2", - new DefaultRepositoryLayout(), - new ArtifactRepositoryPolicy(), - new ArtifactRepositoryPolicy() ); + public List getRemoteArtifactRepositories() { + ArtifactRepository repository = new MavenArtifactRepository( + "central", + "https://repo1.maven.org/maven2", + new DefaultRepositoryLayout(), + new ArtifactRepositoryPolicy(), + new ArtifactRepositoryPolicy()); - return Collections.singletonList( repository ); + return Collections.singletonList(repository); } } diff --git a/maven-surefire-report-plugin/src/test/java/org/apache/maven/plugins/surefire/report/stubs/SurefireRepMavenProjectStub2.java b/maven-surefire-report-plugin/src/test/java/org/apache/maven/plugins/surefire/report/stubs/SurefireRepMavenProjectStub2.java index 0a41412505..98d455bef3 100644 --- a/maven-surefire-report-plugin/src/test/java/org/apache/maven/plugins/surefire/report/stubs/SurefireRepMavenProjectStub2.java +++ b/maven-surefire-report-plugin/src/test/java/org/apache/maven/plugins/surefire/report/stubs/SurefireRepMavenProjectStub2.java @@ -1,3 +1,21 @@ +/* + * 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.maven.plugins.surefire.report.stubs; /* @@ -28,15 +46,12 @@ /** * @author Allan Ramirez */ -public class SurefireRepMavenProjectStub2 - extends MavenProjectStub -{ +public class SurefireRepMavenProjectStub2 extends MavenProjectStub { /** * {@inheritDoc} */ @Override - public List getReportPlugins() - { + public List getReportPlugins() { return new ArrayList<>(); } } diff --git a/pom.xml b/pom.xml index cd8669a826..65f6e8e6e8 100644 --- a/pom.xml +++ b/pom.xml @@ -1,3 +1,4 @@ + - 4.0.0 - maven-parent org.apache.maven - 36 + maven-parent + 39 org.apache.maven.surefire @@ -68,8 +68,8 @@ ${maven.surefire.scm.devConnection} ${maven.surefire.scm.devConnection} - https://github.com/apache/maven-surefire/tree/${project.scm.tag} surefire-3.0.0-M8 + https://github.com/apache/maven-surefire/tree/${project.scm.tag} jira @@ -193,11 +193,11 @@ org.apache.maven - maven-model + maven-model - org.sonatype.sisu - sisu-inject-plexus + org.sonatype.sisu + sisu-inject-plexus @@ -322,8 +322,8 @@ org.jacoco org.jacoco.agent - runtime ${jacocoVersion} + runtime com.googlecode.junit-toolbox @@ -380,11 +380,13 @@ maven-surefire-plugin - 3.0.0-M7 + 3.0.0-M7 + false - ${jvm.args.tests} + ${jvm.args.tests} + false false @@ -461,17 +463,18 @@ **/*.iws **/*.versionsBackup **/dependency-reduced-pom.xml - .repository/** + .repository/** + src/test/resources/**/* src/test/resources/**/*.css **/*.jj - src/main/resources/META-INF/services/org.apache.maven.surefire.api.provider.SurefireProvider - + src/main/resources/META-INF/services/org.apache.maven.surefire.api.provider.SurefireProvider DEPENDENCIES .m2/** .m2 .travis.yml .mvn/wrapper/maven-wrapper.properties + **/.gitattributes @@ -483,11 +486,11 @@ signature-check - - verify check + + verify true @@ -524,22 +527,23 @@ org.apache.maven.plugins maven-surefire-report-plugin - 3.0.0-M7 + 3.0.0-M7 + - - ide-development - - 3-SNAPSHOT - + ide-development + + 3-SNAPSHOT + jdk9+ diff --git a/surefire-api/pom.xml b/surefire-api/pom.xml index 8a581b0548..df34625963 100644 --- a/surefire-api/pom.xml +++ b/surefire-api/pom.xml @@ -1,3 +1,4 @@ + - 4.0.0 @@ -53,9 +53,9 @@ test - powermock-reflect org.powermock - test + powermock-reflect + test @@ -64,6 +64,9 @@ org.jacoco jacoco-maven-plugin + + jacoco.agent + jacoco-agent @@ -72,9 +75,6 @@ - - jacoco.agent - maven-surefire-plugin @@ -88,7 +88,8 @@ org.apache.maven.surefire surefire-shadefire - 3.0.0-M7 + 3.0.0-M7 + diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/api/booter/BaseProviderFactory.java b/surefire-api/src/main/java/org/apache/maven/surefire/api/booter/BaseProviderFactory.java index 1436e98dc6..9658ee2b59 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/api/booter/BaseProviderFactory.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/api/booter/BaseProviderFactory.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.api.booter; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,11 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.api.booter; + +import java.util.Collections; +import java.util.List; +import java.util.Map; import org.apache.maven.surefire.api.cli.CommandLineOption; import org.apache.maven.surefire.api.provider.CommandChainReader; @@ -35,18 +38,12 @@ import org.apache.maven.surefire.api.util.RunOrderCalculator; import org.apache.maven.surefire.api.util.ScanResult; -import java.util.Collections; -import java.util.List; -import java.util.Map; - import static java.util.Collections.emptyList; /** * @author Kristian Rosenvold */ -public class BaseProviderFactory - implements ProviderParameters -{ +public class BaseProviderFactory implements ProviderParameters { private final boolean insideFork; private ReporterFactory reporterFactory; @@ -73,136 +70,115 @@ public class BaseProviderFactory private CommandChainReader commandReader; - public BaseProviderFactory( boolean insideFork ) - { + public BaseProviderFactory(boolean insideFork) { this.insideFork = insideFork; } @Override - public CommandChainReader getCommandReader() - { + public CommandChainReader getCommandReader() { return commandReader; } - public void setCommandReader( CommandChainReader commandReader ) - { + public void setCommandReader(CommandChainReader commandReader) { this.commandReader = commandReader; } @Override @Deprecated - public DirectoryScanner getDirectoryScanner() - { + public DirectoryScanner getDirectoryScanner() { return directoryScannerParameters == null - ? null : new DefaultDirectoryScanner( directoryScannerParameters.getTestClassesDirectory(), - directoryScannerParameters.getIncludes(), - directoryScannerParameters.getExcludes(), - directoryScannerParameters.getSpecificTests() ); + ? null + : new DefaultDirectoryScanner( + directoryScannerParameters.getTestClassesDirectory(), + directoryScannerParameters.getIncludes(), + directoryScannerParameters.getExcludes(), + directoryScannerParameters.getSpecificTests()); } @Override - public ScanResult getScanResult() - { - return DefaultScanResult.from( providerProperties ); + public ScanResult getScanResult() { + return DefaultScanResult.from(providerProperties); } - private int getThreadCount() - { - final String threadcount = providerProperties.get( ProviderParameterNames.THREADCOUNT_PROP ); - return threadcount == null ? 1 : Math.max( Integer.parseInt( threadcount ), 1 ); + private int getThreadCount() { + final String threadcount = providerProperties.get(ProviderParameterNames.THREADCOUNT_PROP); + return threadcount == null ? 1 : Math.max(Integer.parseInt(threadcount), 1); } @Override - public RunOrderCalculator getRunOrderCalculator() - { - return new DefaultRunOrderCalculator( runOrderParameters, getThreadCount() ); + public RunOrderCalculator getRunOrderCalculator() { + return new DefaultRunOrderCalculator(runOrderParameters, getThreadCount()); } - public void setReporterFactory( ReporterFactory reporterFactory ) - { + public void setReporterFactory(ReporterFactory reporterFactory) { this.reporterFactory = reporterFactory; } @Override - public ReporterFactory getReporterFactory() - { + public ReporterFactory getReporterFactory() { return reporterFactory; } - public void setDirectoryScannerParameters( DirectoryScannerParameters directoryScannerParameters ) - { + public void setDirectoryScannerParameters(DirectoryScannerParameters directoryScannerParameters) { this.directoryScannerParameters = directoryScannerParameters; } - public void setReporterConfiguration( ReporterConfiguration reporterConfiguration ) - { + public void setReporterConfiguration(ReporterConfiguration reporterConfiguration) { this.reporterConfiguration = reporterConfiguration; } - public void setClassLoaders( ClassLoader testClassLoader ) - { + public void setClassLoaders(ClassLoader testClassLoader) { this.testClassLoader = testClassLoader; } - public void setTestRequest( TestRequest testRequest ) - { + public void setTestRequest(TestRequest testRequest) { this.testRequest = testRequest; } @Override - public DirectoryScannerParameters getDirectoryScannerParameters() - { + public DirectoryScannerParameters getDirectoryScannerParameters() { return directoryScannerParameters; } @Override - public ReporterConfiguration getReporterConfiguration() - { + public ReporterConfiguration getReporterConfiguration() { return reporterConfiguration; } @Override - public TestRequest getTestRequest() - { + public TestRequest getTestRequest() { return testRequest; } @Override - public ClassLoader getTestClassLoader() - { + public ClassLoader getTestClassLoader() { return testClassLoader; } - public void setProviderProperties( Map providerProperties ) - { + public void setProviderProperties(Map providerProperties) { this.providerProperties = providerProperties; } @Override - public Map getProviderProperties() - { + public Map getProviderProperties() { return providerProperties; } @Override - public TestArtifactInfo getTestArtifactInfo() - { + public TestArtifactInfo getTestArtifactInfo() { return testArtifactInfo; } - public void setTestArtifactInfo( TestArtifactInfo testArtifactInfo ) - { + public void setTestArtifactInfo(TestArtifactInfo testArtifactInfo) { this.testArtifactInfo = testArtifactInfo; } - public void setRunOrderParameters( RunOrderParameters runOrderParameters ) - { + public void setRunOrderParameters(RunOrderParameters runOrderParameters) { this.runOrderParameters = runOrderParameters; } @Override - public List getMainCliOptions() - { + public List getMainCliOptions() { return mainCliOptions; } @@ -211,14 +187,12 @@ public List getMainCliOptions() * * @param mainCliOptions options */ - public void setMainCliOptions( List mainCliOptions ) - { + public void setMainCliOptions(List mainCliOptions) { this.mainCliOptions = mainCliOptions == null ? Collections.emptyList() : mainCliOptions; } @Override - public int getSkipAfterFailureCount() - { + public int getSkipAfterFailureCount() { return skipAfterFailureCount; } @@ -227,25 +201,21 @@ public int getSkipAfterFailureCount() * * @param skipAfterFailureCount the value in config parameter "skipAfterFailureCount" */ - public void setSkipAfterFailureCount( int skipAfterFailureCount ) - { + public void setSkipAfterFailureCount(int skipAfterFailureCount) { this.skipAfterFailureCount = skipAfterFailureCount; } @Override - public boolean isInsideFork() - { + public boolean isInsideFork() { return insideFork; } @Override - public Integer getSystemExitTimeout() - { + public Integer getSystemExitTimeout() { return systemExitTimeout; } - public void setSystemExitTimeout( Integer systemExitTimeout ) - { + public void setSystemExitTimeout(Integer systemExitTimeout) { this.systemExitTimeout = systemExitTimeout; } } diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/api/booter/BiProperty.java b/surefire-api/src/main/java/org/apache/maven/surefire/api/booter/BiProperty.java index 61862e725f..e43d574056 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/api/booter/BiProperty.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/api/booter/BiProperty.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.api.booter; /* @@ -27,24 +45,20 @@ * @param first property * @param second property */ -public final class BiProperty -{ +public final class BiProperty { private final P1 p1; private final P2 p2; - public BiProperty( P1 p1, P2 p2 ) - { + public BiProperty(P1 p1, P2 p2) { this.p1 = p1; this.p2 = p2; } - public P1 getP1() - { + public P1 getP1() { return p1; } - public P2 getP2() - { + public P2 getP2() { return p2; } } diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/api/booter/Command.java b/surefire-api/src/main/java/org/apache/maven/surefire/api/booter/Command.java index d768e11422..df86fee543 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/api/booter/Command.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/api/booter/Command.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.api.booter; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.api.booter; import java.util.Objects; @@ -30,44 +29,37 @@ * @author Tibor Digana (tibor17) * @since 2.19 */ -public final class Command -{ - public static final Command TEST_SET_FINISHED = new Command( MasterProcessCommand.TEST_SET_FINISHED ); - public static final Command SKIP_SINCE_NEXT_TEST = new Command( MasterProcessCommand.SKIP_SINCE_NEXT_TEST ); - public static final Command NOOP = new Command( MasterProcessCommand.NOOP ); - public static final Command BYE_ACK = new Command( MasterProcessCommand.BYE_ACK ); +public final class Command { + public static final Command TEST_SET_FINISHED = new Command(MasterProcessCommand.TEST_SET_FINISHED); + public static final Command SKIP_SINCE_NEXT_TEST = new Command(MasterProcessCommand.SKIP_SINCE_NEXT_TEST); + public static final Command NOOP = new Command(MasterProcessCommand.NOOP); + public static final Command BYE_ACK = new Command(MasterProcessCommand.BYE_ACK); private final MasterProcessCommand command; private final String data; - public Command( MasterProcessCommand command, String data ) - { - this.command = requireNonNull( command ); + public Command(MasterProcessCommand command, String data) { + this.command = requireNonNull(command); this.data = data; } - public Command( MasterProcessCommand command ) - { - this( command, null ); + public Command(MasterProcessCommand command) { + this(command, null); } - public static Command toShutdown( Shutdown shutdownType ) - { - return new Command( MasterProcessCommand.SHUTDOWN, shutdownType.name() ); + public static Command toShutdown(Shutdown shutdownType) { + return new Command(MasterProcessCommand.SHUTDOWN, shutdownType.name()); } - public static Command toRunClass( String runClass ) - { - return new Command( MasterProcessCommand.RUN_CLASS, runClass ); + public static Command toRunClass(String runClass) { + return new Command(MasterProcessCommand.RUN_CLASS, runClass); } - public MasterProcessCommand getCommandType() - { + public MasterProcessCommand getCommandType() { return command; } - public String getData() - { + public String getData() { return data; } @@ -75,38 +67,32 @@ public String getData() * @return {@link Shutdown} or {@link Shutdown#DEFAULT} if {@link #getData()} is null or blank string * @throws IllegalArgumentException if string data {@link #getData()} is not applicable to enum {@link Shutdown} */ - public Shutdown toShutdownData() - { - if ( command != MasterProcessCommand.SHUTDOWN ) - { - throw new IllegalStateException( "expected MasterProcessCommand.SHUTDOWN" ); + public Shutdown toShutdownData() { + if (command != MasterProcessCommand.SHUTDOWN) { + throw new IllegalStateException("expected MasterProcessCommand.SHUTDOWN"); } - return isBlank( data ) ? Shutdown.DEFAULT : Shutdown.valueOf( data ); + return isBlank(data) ? Shutdown.DEFAULT : Shutdown.valueOf(data); } @Override - public boolean equals( Object o ) - { - if ( this == o ) - { + public boolean equals(Object o) { + if (this == o) { return true; } - if ( o == null || getClass() != o.getClass() ) - { + if (o == null || getClass() != o.getClass()) { return false; } Command arg = (Command) o; - return command == arg.command && Objects.equals( data, arg.data ); + return command == arg.command && Objects.equals(data, arg.data); } @Override - public int hashCode() - { + public int hashCode() { int result = command.hashCode(); - result = 31 * result + ( data != null ? data.hashCode() : 0 ); + result = 31 * result + (data != null ? data.hashCode() : 0); return result; } } diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/api/booter/Constants.java b/surefire-api/src/main/java/org/apache/maven/surefire/api/booter/Constants.java index 639aba8b53..d57db47406 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/api/booter/Constants.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/api/booter/Constants.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.api.booter; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.api.booter; import java.nio.charset.Charset; @@ -27,12 +26,11 @@ /** * */ -public final class Constants -{ +public final class Constants { private static final String MAGIC_NUMBER_FOR_EVENTS = "maven-surefire-event"; public static final String MAGIC_NUMBER_FOR_COMMANDS = "maven-surefire-command"; - public static final byte[] MAGIC_NUMBER_FOR_EVENTS_BYTES = MAGIC_NUMBER_FOR_EVENTS.getBytes( US_ASCII ); - public static final byte[] MAGIC_NUMBER_FOR_COMMANDS_BYTES = MAGIC_NUMBER_FOR_COMMANDS.getBytes( US_ASCII ); + public static final byte[] MAGIC_NUMBER_FOR_EVENTS_BYTES = MAGIC_NUMBER_FOR_EVENTS.getBytes(US_ASCII); + public static final byte[] MAGIC_NUMBER_FOR_COMMANDS_BYTES = MAGIC_NUMBER_FOR_COMMANDS.getBytes(US_ASCII); public static final Charset DEFAULT_STREAM_ENCODING = UTF_8; - public static final byte[] DEFAULT_STREAM_ENCODING_BYTES = UTF_8.name().getBytes( US_ASCII ); + public static final byte[] DEFAULT_STREAM_ENCODING_BYTES = UTF_8.name().getBytes(US_ASCII); } diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/api/booter/DumpErrorSingleton.java b/surefire-api/src/main/java/org/apache/maven/surefire/api/booter/DumpErrorSingleton.java index 791dae5674..073ea3fe21 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/api/booter/DumpErrorSingleton.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/api/booter/DumpErrorSingleton.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.api.booter; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,11 +16,12 @@ * specific language governing permissions and limitations * under the License. */ - -import org.apache.maven.surefire.api.util.internal.DumpFileUtils; +package org.apache.maven.surefire.api.booter; import java.io.File; +import org.apache.maven.surefire.api.util.internal.DumpFileUtils; + import static org.apache.maven.surefire.api.util.internal.DumpFileUtils.newDumpFile; /** @@ -32,8 +31,7 @@ * @author Tibor Digana (tibor17) * @since 2.20 */ -public final class DumpErrorSingleton -{ +public final class DumpErrorSingleton { public static final String DUMP_FILE_EXT = ".dump"; public static final String DUMPSTREAM_FILE_EXT = ".dumpstream"; private static final DumpErrorSingleton SINGLETON = new DumpErrorSingleton(); @@ -42,72 +40,59 @@ public final class DumpErrorSingleton private File dumpStreamFile; private File binaryDumpStreamFile; - private DumpErrorSingleton() - { - } + private DumpErrorSingleton() {} - public static DumpErrorSingleton getSingleton() - { + public static DumpErrorSingleton getSingleton() { return SINGLETON; } - public synchronized void init( File reportsDir, String dumpFileName ) - { - dumpFile = createDumpFile( reportsDir, dumpFileName ); - dumpStreamFile = createDumpStreamFile( reportsDir, dumpFileName ); + public synchronized void init(File reportsDir, String dumpFileName) { + dumpFile = createDumpFile(reportsDir, dumpFileName); + dumpStreamFile = createDumpStreamFile(reportsDir, dumpFileName); String fileNameWithoutExtension = - dumpFileName.contains( "." ) ? dumpFileName.substring( 0, dumpFileName.lastIndexOf( '.' ) ) : dumpFileName; - binaryDumpStreamFile = newDumpFile( reportsDir, fileNameWithoutExtension + "-commands.bin" ); + dumpFileName.contains(".") ? dumpFileName.substring(0, dumpFileName.lastIndexOf('.')) : dumpFileName; + binaryDumpStreamFile = newDumpFile(reportsDir, fileNameWithoutExtension + "-commands.bin"); } - public synchronized File dumpException( Throwable t, String msg ) - { - DumpFileUtils.dumpException( t, msg == null ? "null" : msg, dumpFile ); + public synchronized File dumpException(Throwable t, String msg) { + DumpFileUtils.dumpException(t, msg == null ? "null" : msg, dumpFile); return dumpFile; } - public synchronized File dumpException( Throwable t ) - { - DumpFileUtils.dumpException( t, dumpFile ); + public synchronized File dumpException(Throwable t) { + DumpFileUtils.dumpException(t, dumpFile); return dumpFile; } - public synchronized File dumpText( String msg ) - { - DumpFileUtils.dumpText( msg == null ? "null" : msg, dumpFile ); + public synchronized File dumpText(String msg) { + DumpFileUtils.dumpText(msg == null ? "null" : msg, dumpFile); return dumpFile; } - public synchronized File dumpStreamException( Throwable t, String msg ) - { - DumpFileUtils.dumpException( t, msg == null ? "null" : msg, dumpStreamFile ); + public synchronized File dumpStreamException(Throwable t, String msg) { + DumpFileUtils.dumpException(t, msg == null ? "null" : msg, dumpStreamFile); return dumpStreamFile; } - public synchronized File dumpStreamException( Throwable t ) - { - DumpFileUtils.dumpException( t, dumpStreamFile ); + public synchronized File dumpStreamException(Throwable t) { + DumpFileUtils.dumpException(t, dumpStreamFile); return dumpStreamFile; } - public synchronized File dumpStreamText( String msg ) - { - DumpFileUtils.dumpText( msg == null ? "null" : msg, dumpStreamFile ); + public synchronized File dumpStreamText(String msg) { + DumpFileUtils.dumpText(msg == null ? "null" : msg, dumpStreamFile); return dumpStreamFile; } - public File getCommandStreamBinaryFile() - { + public File getCommandStreamBinaryFile() { return binaryDumpStreamFile; } - private File createDumpFile( File reportsDir, String dumpFileName ) - { - return newDumpFile( reportsDir, dumpFileName + DUMP_FILE_EXT ); + private File createDumpFile(File reportsDir, String dumpFileName) { + return newDumpFile(reportsDir, dumpFileName + DUMP_FILE_EXT); } - private File createDumpStreamFile( File reportsDir, String dumpFileName ) - { - return newDumpFile( reportsDir, dumpFileName + DUMPSTREAM_FILE_EXT ); + private File createDumpStreamFile(File reportsDir, String dumpFileName) { + return newDumpFile(reportsDir, dumpFileName + DUMPSTREAM_FILE_EXT); } } diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/api/booter/ForkedProcessEventType.java b/surefire-api/src/main/java/org/apache/maven/surefire/api/booter/ForkedProcessEventType.java index f82bb51f24..5d66f792bf 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/api/booter/ForkedProcessEventType.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/api/booter/ForkedProcessEventType.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.api.booter; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.api.booter; import static java.nio.charset.StandardCharsets.US_ASCII; @@ -27,9 +26,8 @@ * @author Tibor Digana (tibor17) * @since 3.0.0-M4 */ -@SuppressWarnings( "checkstyle:linelength" ) -public enum ForkedProcessEventType -{ +@SuppressWarnings("checkstyle:linelength") +public enum ForkedProcessEventType { /** * This is the opcode "sys-prop". The frame is composed of segments and the separator characters ':' *
@@ -40,7 +38,7 @@ public enum ForkedProcessEventType
      *     
  • the opcode is "sys-prop" * */ - BOOTERCODE_SYSPROPS( "sys-prop" ), + BOOTERCODE_SYSPROPS("sys-prop"), /** * This is the opcode "testset-starting". The frame is composed of segments and the separator characters ':' @@ -52,7 +50,7 @@ public enum ForkedProcessEventType *
  • the opcode is "testset-starting" * */ - BOOTERCODE_TESTSET_STARTING( "testset-starting" ), + BOOTERCODE_TESTSET_STARTING("testset-starting"), /** * This is the opcode "testset-completed". The frame is composed of segments and the separator characters ':' @@ -64,7 +62,7 @@ public enum ForkedProcessEventType *
  • the opcode is "testset-completed" * */ - BOOTERCODE_TESTSET_COMPLETED( "testset-completed" ), + BOOTERCODE_TESTSET_COMPLETED("testset-completed"), /** * This is the opcode "test-starting". The frame is composed of segments and the separator characters ':' @@ -76,7 +74,7 @@ public enum ForkedProcessEventType *
  • the opcode is "test-starting" * */ - BOOTERCODE_TEST_STARTING( "test-starting" ), + BOOTERCODE_TEST_STARTING("test-starting"), /** * This is the opcode "test-succeeded". The frame is composed of segments and the separator characters ':' @@ -88,7 +86,7 @@ public enum ForkedProcessEventType *
  • the opcode is "test-succeeded" * */ - BOOTERCODE_TEST_SUCCEEDED( "test-succeeded" ), + BOOTERCODE_TEST_SUCCEEDED("test-succeeded"), /** * This is the opcode "test-failed". The frame is composed of segments and the separator characters ':' @@ -100,7 +98,7 @@ public enum ForkedProcessEventType *
  • the opcode is "test-failed" * */ - BOOTERCODE_TEST_FAILED( "test-failed" ), + BOOTERCODE_TEST_FAILED("test-failed"), /** * This is the opcode "test-skipped". The frame is composed of segments and the separator characters ':' @@ -112,7 +110,7 @@ public enum ForkedProcessEventType *
  • the opcode is "test-skipped" * */ - BOOTERCODE_TEST_SKIPPED( "test-skipped" ), + BOOTERCODE_TEST_SKIPPED("test-skipped"), /** * This is the opcode "test-error". The frame is composed of segments and the separator characters ':' @@ -124,7 +122,7 @@ public enum ForkedProcessEventType *
  • the opcode is "test-error" * */ - BOOTERCODE_TEST_ERROR( "test-error" ), + BOOTERCODE_TEST_ERROR("test-error"), /** * This is the opcode "test-assumption-failure". The frame is composed of segments and the separator characters ':' @@ -136,7 +134,7 @@ public enum ForkedProcessEventType *
  • the opcode is "test-assumption-failure" * */ - BOOTERCODE_TEST_ASSUMPTIONFAILURE( "test-assumption-failure" ), + BOOTERCODE_TEST_ASSUMPTIONFAILURE("test-assumption-failure"), /** * This is the opcode "std-out-stream". The frame is composed of segments and the separator characters ':' @@ -148,7 +146,7 @@ public enum ForkedProcessEventType *
  • the opcode is "std-out-stream" * */ - BOOTERCODE_STDOUT( "std-out-stream" ), + BOOTERCODE_STDOUT("std-out-stream"), /** * This is the opcode "std-out-stream-new-line". The frame is composed of segments and the separator characters ':' @@ -160,7 +158,7 @@ public enum ForkedProcessEventType *
  • the opcode is "std-out-stream-new-line" * */ - BOOTERCODE_STDOUT_NEW_LINE( "std-out-stream-new-line" ), + BOOTERCODE_STDOUT_NEW_LINE("std-out-stream-new-line"), /** * This is the opcode "std-err-stream". The frame is composed of segments and the separator characters ':' @@ -172,7 +170,7 @@ public enum ForkedProcessEventType *
  • the opcode is "std-err-stream" * */ - BOOTERCODE_STDERR( "std-err-stream" ), + BOOTERCODE_STDERR("std-err-stream"), /** * This is the opcode "std-err-stream-new-line". The frame is composed of segments and the separator characters ':' @@ -184,7 +182,7 @@ public enum ForkedProcessEventType *
  • the opcode is "std-err-stream-new-line" * */ - BOOTERCODE_STDERR_NEW_LINE( "std-err-stream-new-line" ), + BOOTERCODE_STDERR_NEW_LINE("std-err-stream-new-line"), /** * This is the opcode "console-info-log". The frame is composed of segments and the separator characters ':' @@ -196,7 +194,7 @@ public enum ForkedProcessEventType *
  • the opcode is "console-info-log" * */ - BOOTERCODE_CONSOLE_INFO( "console-info-log" ), + BOOTERCODE_CONSOLE_INFO("console-info-log"), /** * This is the opcode "console-debug-log". The frame is composed of segments and the separator characters ':' @@ -208,7 +206,7 @@ public enum ForkedProcessEventType *
  • the opcode is "console-debug-log" * */ - BOOTERCODE_CONSOLE_DEBUG( "console-debug-log" ), + BOOTERCODE_CONSOLE_DEBUG("console-debug-log"), /** * This is the opcode "console-warning-log". The frame is composed of segments and the separator characters ':' @@ -220,7 +218,7 @@ public enum ForkedProcessEventType *
  • the opcode is "console-warning-log" * */ - BOOTERCODE_CONSOLE_WARNING( "console-warning-log" ), + BOOTERCODE_CONSOLE_WARNING("console-warning-log"), /** * This is the opcode "console-error-log". The frame is composed of segments and the separator characters ':' @@ -232,7 +230,7 @@ public enum ForkedProcessEventType *
  • the opcode is "console-error-log" * */ - BOOTERCODE_CONSOLE_ERROR( "console-error-log" ), + BOOTERCODE_CONSOLE_ERROR("console-error-log"), /** * This is the opcode "bye". The frame is composed of segments and the separator characters ':' @@ -244,7 +242,7 @@ public enum ForkedProcessEventType *
  • the opcode is "bye" * */ - BOOTERCODE_BYE( "bye" ), + BOOTERCODE_BYE("bye"), /** * This is the opcode "stop-on-next-test". The frame is composed of segments and the separator characters ':' @@ -256,7 +254,7 @@ public enum ForkedProcessEventType *
  • the opcode is "stop-on-next-test" * */ - BOOTERCODE_STOP_ON_NEXT_TEST( "stop-on-next-test" ), + BOOTERCODE_STOP_ON_NEXT_TEST("stop-on-next-test"), /** * This is the opcode "next-test". The frame is composed of segments and the separator characters ':' @@ -268,7 +266,7 @@ public enum ForkedProcessEventType *
  • the opcode is "next-test" * */ - BOOTERCODE_NEXT_TEST( "next-test" ), + BOOTERCODE_NEXT_TEST("next-test"), /** * This is the opcode "jvm-exit-error". The frame is composed of segments and the separator characters ':' @@ -280,34 +278,29 @@ public enum ForkedProcessEventType *
  • the opcode is "jvm-exit-error" * */ - BOOTERCODE_JVM_EXIT_ERROR( "jvm-exit-error" ); + BOOTERCODE_JVM_EXIT_ERROR("jvm-exit-error"); private final String opcode; private final byte[] opcodeBinary; - ForkedProcessEventType( String opcode ) - { + ForkedProcessEventType(String opcode) { this.opcode = opcode; - opcodeBinary = opcode.getBytes( US_ASCII ); + opcodeBinary = opcode.getBytes(US_ASCII); } - public String getOpcode() - { + public String getOpcode() { return opcode; } - public byte[] getOpcodeBinary() - { + public byte[] getOpcodeBinary() { return opcodeBinary; } - public boolean isSysPropCategory() - { + public boolean isSysPropCategory() { return this == BOOTERCODE_SYSPROPS; } - public boolean isTestCategory() - { + public boolean isTestCategory() { return this == BOOTERCODE_TESTSET_STARTING || this == BOOTERCODE_TESTSET_COMPLETED || this == BOOTERCODE_TEST_STARTING @@ -318,31 +311,28 @@ public boolean isTestCategory() || this == BOOTERCODE_TEST_ASSUMPTIONFAILURE; } - public boolean isStandardStreamCategory() - { - return this == BOOTERCODE_STDOUT || this == BOOTERCODE_STDOUT_NEW_LINE - || this == BOOTERCODE_STDERR || this == BOOTERCODE_STDERR_NEW_LINE; + public boolean isStandardStreamCategory() { + return this == BOOTERCODE_STDOUT + || this == BOOTERCODE_STDOUT_NEW_LINE + || this == BOOTERCODE_STDERR + || this == BOOTERCODE_STDERR_NEW_LINE; } - public boolean isConsoleCategory() - { + public boolean isConsoleCategory() { return this == BOOTERCODE_CONSOLE_INFO || this == BOOTERCODE_CONSOLE_DEBUG || this == BOOTERCODE_CONSOLE_WARNING; } - public boolean isConsoleErrorCategory() - { + public boolean isConsoleErrorCategory() { return this == BOOTERCODE_CONSOLE_ERROR; } - public boolean isControlCategory() - { + public boolean isControlCategory() { return this == BOOTERCODE_BYE || this == BOOTERCODE_STOP_ON_NEXT_TEST || this == BOOTERCODE_NEXT_TEST; } - public boolean isJvmExitError() - { + public boolean isJvmExitError() { return this == BOOTERCODE_JVM_EXIT_ERROR; } } diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/api/booter/ForkingReporterFactory.java b/surefire-api/src/main/java/org/apache/maven/surefire/api/booter/ForkingReporterFactory.java index cf7ad5b918..01ce9fff67 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/api/booter/ForkingReporterFactory.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/api/booter/ForkingReporterFactory.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.api.booter; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.api.booter; import org.apache.maven.surefire.api.report.ReporterFactory; import org.apache.maven.surefire.api.report.TestReportListener; @@ -29,28 +28,23 @@ * * @author Kristian Rosenvold */ -public class ForkingReporterFactory - implements ReporterFactory -{ +public class ForkingReporterFactory implements ReporterFactory { private final boolean trimstackTrace; private final MasterProcessChannelEncoder eventChannel; - public ForkingReporterFactory( boolean trimstackTrace, MasterProcessChannelEncoder eventChannel ) - { + public ForkingReporterFactory(boolean trimstackTrace, MasterProcessChannelEncoder eventChannel) { this.trimstackTrace = trimstackTrace; this.eventChannel = eventChannel; } @Override - public TestReportListener createTestReportListener() - { - return new ForkingRunListener( eventChannel, trimstackTrace ); + public TestReportListener createTestReportListener() { + return new ForkingRunListener(eventChannel, trimstackTrace); } @Override - public RunResult close() - { - return new RunResult( 17, 17, 17, 17 ); + public RunResult close() { + return new RunResult(17, 17, 17, 17); } } diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/api/booter/ForkingRunListener.java b/surefire-api/src/main/java/org/apache/maven/surefire/api/booter/ForkingRunListener.java index b987228e7b..4f152931d1 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/api/booter/ForkingRunListener.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/api/booter/ForkingRunListener.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.api.booter; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,10 +16,11 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.api.booter; +import org.apache.maven.surefire.api.report.ReportEntry; import org.apache.maven.surefire.api.report.TestOutputReportEntry; import org.apache.maven.surefire.api.report.TestReportListener; -import org.apache.maven.surefire.api.report.ReportEntry; import org.apache.maven.surefire.api.report.TestSetReportEntry; /** @@ -41,135 +40,112 @@ * * @author Kristian Rosenvold */ -public class ForkingRunListener - implements TestReportListener -{ +public class ForkingRunListener implements TestReportListener { private final MasterProcessChannelEncoder target; private final boolean trim; - public ForkingRunListener( MasterProcessChannelEncoder target, boolean trim ) - { + public ForkingRunListener(MasterProcessChannelEncoder target, boolean trim) { this.target = target; this.trim = trim; } @Override - public void testSetStarting( TestSetReportEntry report ) - { - target.testSetStarting( report, trim ); + public void testSetStarting(TestSetReportEntry report) { + target.testSetStarting(report, trim); } @Override - public void testSetCompleted( TestSetReportEntry report ) - { - target.testSetCompleted( report, trim ); + public void testSetCompleted(TestSetReportEntry report) { + target.testSetCompleted(report, trim); } @Override - public void testStarting( ReportEntry report ) - { - target.testStarting( report, trim ); + public void testStarting(ReportEntry report) { + target.testStarting(report, trim); } @Override - public void testSucceeded( ReportEntry report ) - { - target.testSucceeded( report, trim ); + public void testSucceeded(ReportEntry report) { + target.testSucceeded(report, trim); } @Override - public void testAssumptionFailure( ReportEntry report ) - { - target.testAssumptionFailure( report, trim ); + public void testAssumptionFailure(ReportEntry report) { + target.testAssumptionFailure(report, trim); } @Override - public void testError( ReportEntry report ) - { - target.testError( report, trim ); + public void testError(ReportEntry report) { + target.testError(report, trim); } @Override - public void testFailed( ReportEntry report ) - { - target.testFailed( report, trim ); + public void testFailed(ReportEntry report) { + target.testFailed(report, trim); } @Override - public void testSkipped( ReportEntry report ) - { - target.testSkipped( report, trim ); + public void testSkipped(ReportEntry report) { + target.testSkipped(report, trim); } @Override - public void testExecutionSkippedByUser() - { + public void testExecutionSkippedByUser() { target.stopOnNextTest(); } @Override - public void writeTestOutput( TestOutputReportEntry reportEntry ) - { - target.testOutput( reportEntry ); + public void writeTestOutput(TestOutputReportEntry reportEntry) { + target.testOutput(reportEntry); } @Override - public boolean isDebugEnabled() - { + public boolean isDebugEnabled() { return true; } @Override - public void debug( String message ) - { - target.consoleDebugLog( message ); + public void debug(String message) { + target.consoleDebugLog(message); } @Override - public boolean isInfoEnabled() - { + public boolean isInfoEnabled() { return true; } @Override - public void info( String message ) - { - target.consoleInfoLog( message ); + public void info(String message) { + target.consoleInfoLog(message); } @Override - public boolean isWarnEnabled() - { + public boolean isWarnEnabled() { return true; } @Override - public void warning( String message ) - { - target.consoleWarningLog( message ); + public void warning(String message) { + target.consoleWarningLog(message); } @Override - public boolean isErrorEnabled() - { + public boolean isErrorEnabled() { return true; } @Override - public void error( String message ) - { - target.consoleErrorLog( message ); + public void error(String message) { + target.consoleErrorLog(message); } @Override - public void error( String message, Throwable t ) - { - target.consoleErrorLog( message, t ); + public void error(String message, Throwable t) { + target.consoleErrorLog(message, t); } @Override - public void error( Throwable t ) - { - error( null, t ); + public void error(Throwable t) { + error(null, t); } } diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/api/booter/MasterProcessChannelDecoder.java b/surefire-api/src/main/java/org/apache/maven/surefire/api/booter/MasterProcessChannelDecoder.java index 0571afa16f..1153855001 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/api/booter/MasterProcessChannelDecoder.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/api/booter/MasterProcessChannelDecoder.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.api.booter; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,8 +16,10 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.api.booter; import javax.annotation.Nonnull; + import java.io.IOException; /** @@ -27,9 +27,7 @@ * received by the child forked Surefire process. The session must be open after the MasterProcessChannelDecoderFactory * has created the decoder instance. The session can be closed on the decoder instance. */ -public interface MasterProcessChannelDecoder - extends AutoCloseable -{ +public interface MasterProcessChannelDecoder extends AutoCloseable { /** * Reads the bytes from a channel, waiting until the command is read completely or * the channel throws {@link java.io.EOFException}. @@ -39,7 +37,8 @@ public interface MasterProcessChannelDecoder * @return decoded command * @throws IOException exception in channel */ - @Nonnull Command decode() throws IOException; + @Nonnull + Command decode() throws IOException; @Override void close() throws IOException; diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/api/booter/MasterProcessChannelEncoder.java b/surefire-api/src/main/java/org/apache/maven/surefire/api/booter/MasterProcessChannelEncoder.java index 50e8c96a05..ed4a479c74 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/api/booter/MasterProcessChannelEncoder.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/api/booter/MasterProcessChannelEncoder.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.api.booter; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.api.booter; import org.apache.maven.surefire.api.report.ReportEntry; import org.apache.maven.surefire.api.report.StackTraceWriter; @@ -30,8 +29,7 @@ * @author Tibor Digana (tibor17) * @since 3.0.0-M5 */ -public interface MasterProcessChannelEncoder -{ +public interface MasterProcessChannelEncoder { /** * @return {@code true} if the encoder's stream has got an error */ @@ -48,7 +46,7 @@ public interface MasterProcessChannelEncoder * @param reportEntry test set report entry * @param trimStackTraces {@code true} if stack trace trimming */ - void testSetStarting( TestSetReportEntry reportEntry, boolean trimStackTraces ); + void testSetStarting(TestSetReportEntry reportEntry, boolean trimStackTraces); /** * The test set has finished. @@ -56,7 +54,7 @@ public interface MasterProcessChannelEncoder * @param reportEntry test set report entry * @param trimStackTraces {@code true} if stack trace trimming */ - void testSetCompleted( TestSetReportEntry reportEntry, boolean trimStackTraces ); + void testSetCompleted(TestSetReportEntry reportEntry, boolean trimStackTraces); /** * The test has started. @@ -64,7 +62,7 @@ public interface MasterProcessChannelEncoder * @param reportEntry test set report entry * @param trimStackTraces {@code true} if stack trace trimming */ - void testStarting( ReportEntry reportEntry, boolean trimStackTraces ); + void testStarting(ReportEntry reportEntry, boolean trimStackTraces); /** * The test has succeeded. @@ -72,7 +70,7 @@ public interface MasterProcessChannelEncoder * @param reportEntry test set report entry * @param trimStackTraces {@code true} if stack trace trimming */ - void testSucceeded( ReportEntry reportEntry, boolean trimStackTraces ); + void testSucceeded(ReportEntry reportEntry, boolean trimStackTraces); /** * The test has failed. @@ -80,7 +78,7 @@ public interface MasterProcessChannelEncoder * @param reportEntry test set report entry * @param trimStackTraces {@code true} if stack trace trimming */ - void testFailed( ReportEntry reportEntry, boolean trimStackTraces ); + void testFailed(ReportEntry reportEntry, boolean trimStackTraces); /** * The test is skipped. @@ -88,7 +86,7 @@ public interface MasterProcessChannelEncoder * @param reportEntry test set report entry * @param trimStackTraces {@code true} if stack trace trimming */ - void testSkipped( ReportEntry reportEntry, boolean trimStackTraces ); + void testSkipped(ReportEntry reportEntry, boolean trimStackTraces); /** * The test error. @@ -96,7 +94,7 @@ public interface MasterProcessChannelEncoder * @param reportEntry test set report entry * @param trimStackTraces {@code true} if stack trace trimming */ - void testError( ReportEntry reportEntry, boolean trimStackTraces ); + void testError(ReportEntry reportEntry, boolean trimStackTraces); /** * The test assumption failure. @@ -104,35 +102,35 @@ public interface MasterProcessChannelEncoder * @param reportEntry test set report entry * @param trimStackTraces {@code true} if stack trace trimming */ - void testAssumptionFailure( ReportEntry reportEntry, boolean trimStackTraces ); + void testAssumptionFailure(ReportEntry reportEntry, boolean trimStackTraces); /** * Test output, a line or characters. * * @param reportEntry std/out or std/err context */ - void testOutput( TestOutputReportEntry reportEntry ); + void testOutput(TestOutputReportEntry reportEntry); /** * Info log. * * @param msg message of info logger */ - void consoleInfoLog( String msg ); + void consoleInfoLog(String msg); /** * Error log. * * @param msg message of error logger */ - void consoleErrorLog( String msg ); + void consoleErrorLog(String msg); /** * Error log. * * @param t exception */ - void consoleErrorLog( Throwable t ); + void consoleErrorLog(Throwable t); /** * Error log. @@ -140,7 +138,7 @@ public interface MasterProcessChannelEncoder * @param msg additional error message * @param t exception */ - void consoleErrorLog( String msg, Throwable t ); + void consoleErrorLog(String msg, Throwable t); /** * Error log. @@ -148,21 +146,21 @@ public interface MasterProcessChannelEncoder * @param stackTraceWriter printable stack trace * @param trimStackTraces {@code true} if selected trimmed stack trace to print into encoder channel/stream */ - void consoleErrorLog( StackTraceWriter stackTraceWriter, boolean trimStackTraces ); + void consoleErrorLog(StackTraceWriter stackTraceWriter, boolean trimStackTraces); /** * Debug log. * * @param msg message of debug logger */ - void consoleDebugLog( String msg ); + void consoleDebugLog(String msg); /** * Warning log. * * @param msg message of warning logger */ - void consoleWarningLog( String msg ); + void consoleWarningLog(String msg); /** * Say BYE on exit. @@ -186,5 +184,5 @@ public interface MasterProcessChannelEncoder * @param stackTraceWriter printable stack trace * @param trimStackTraces {@code true} if selected trimmed stack trace to print into encoder channel/stream */ - void sendExitError( StackTraceWriter stackTraceWriter, boolean trimStackTraces ); + void sendExitError(StackTraceWriter stackTraceWriter, boolean trimStackTraces); } diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/api/booter/MasterProcessCommand.java b/surefire-api/src/main/java/org/apache/maven/surefire/api/booter/MasterProcessCommand.java index f492339c7a..d3d71980b7 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/api/booter/MasterProcessCommand.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/api/booter/MasterProcessCommand.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.api.booter; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,12 +16,13 @@ * specific language governing permissions and limitations * under the License. */ - -import org.apache.maven.surefire.api.stream.AbstractStreamDecoder.Segment; +package org.apache.maven.surefire.api.booter; import java.util.HashMap; import java.util.Map; +import org.apache.maven.surefire.api.stream.AbstractStreamDecoder.Segment; + import static java.nio.charset.StandardCharsets.US_ASCII; import static java.util.Objects.requireNonNull; @@ -33,16 +32,15 @@ * @author Tibor Digana (tibor17) * @since 2.19 */ -public enum MasterProcessCommand -{ - RUN_CLASS( "run-testclass", String.class ), - TEST_SET_FINISHED( "testset-finished", Void.class ), - SKIP_SINCE_NEXT_TEST( "skip-since-next-test", Void.class ), - SHUTDOWN( "shutdown", String.class ), +public enum MasterProcessCommand { + RUN_CLASS("run-testclass", String.class), + TEST_SET_FINISHED("testset-finished", Void.class), + SKIP_SINCE_NEXT_TEST("skip-since-next-test", Void.class), + SHUTDOWN("shutdown", String.class), /** To tell a forked process that the master process is still alive. Repeated after 10 seconds. */ - NOOP( "noop", Void.class ), - BYE_ACK( "bye-ack", Void.class ); + NOOP("noop", Void.class), + BYE_ACK("bye-ack", Void.class); // due to have fast and thread-safe Map public static final Map COMMAND_TYPES = segmentsToCmds(); @@ -51,46 +49,38 @@ public enum MasterProcessCommand private final byte[] opcodeBinary; private final Class dataType; - MasterProcessCommand( String opcode, Class dataType ) - { - this.opcode = requireNonNull( opcode, "value cannot be null" ); - opcodeBinary = opcode.getBytes( US_ASCII ); - this.dataType = requireNonNull( dataType, "dataType cannot be null" ); + MasterProcessCommand(String opcode, Class dataType) { + this.opcode = requireNonNull(opcode, "value cannot be null"); + opcodeBinary = opcode.getBytes(US_ASCII); + this.dataType = requireNonNull(dataType, "dataType cannot be null"); } - public byte[] getOpcodeBinary() - { + public byte[] getOpcodeBinary() { return opcodeBinary; } - public int getOpcodeLength() - { + public int getOpcodeLength() { return opcodeBinary.length; } - public Class getDataType() - { + public Class getDataType() { return dataType; } - public boolean hasDataType() - { + public boolean hasDataType() { return dataType != Void.class; } @Override - public String toString() - { + public String toString() { return opcode; } - private static Map segmentsToCmds() - { + private static Map segmentsToCmds() { Map commands = new HashMap<>(); - for ( MasterProcessCommand command : MasterProcessCommand.values() ) - { - byte[] array = command.toString().getBytes( US_ASCII ); - commands.put( new Segment( array, 0, array.length ), command ); + for (MasterProcessCommand command : MasterProcessCommand.values()) { + byte[] array = command.toString().getBytes(US_ASCII); + commands.put(new Segment(array, 0, array.length), command); } return commands; } diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/api/booter/ProviderParameterNames.java b/surefire-api/src/main/java/org/apache/maven/surefire/api/booter/ProviderParameterNames.java index d4ae91e33d..74857f475d 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/api/booter/ProviderParameterNames.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/api/booter/ProviderParameterNames.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.api.booter; /* @@ -22,8 +40,7 @@ /** * @author Kristian Rosenvold */ -public class ProviderParameterNames -{ +public class ProviderParameterNames { public static final String TESTNG_EXCLUDEDGROUPS_PROP = "excludegroups"; public static final String TESTNG_GROUPS_PROP = "groups"; @@ -47,5 +64,4 @@ public class ProviderParameterNames public static final String PARALLEL_TIMEOUTFORCED_PROP = "paralleltimeoutforced"; public static final String PARALLEL_OPTIMIZE_PROP = "paralleloptimization"; - } diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/api/booter/Shutdown.java b/surefire-api/src/main/java/org/apache/maven/surefire/api/booter/Shutdown.java index e0baa56c60..55604760f4 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/api/booter/Shutdown.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/api/booter/Shutdown.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.api.booter; /* @@ -26,71 +44,56 @@ * @author Tibor Digana (tibor17) * @since 2.19 */ -public enum Shutdown -{ - DEFAULT( "testset" ), - EXIT( "exit" ), - KILL( "kill" ); +public enum Shutdown { + DEFAULT("testset"), + EXIT("exit"), + KILL("kill"); private final String param; - Shutdown( String param ) - { + Shutdown(String param) { this.param = param; } - public String getParam() - { + public String getParam() { return param; } - public boolean isKill() - { + public boolean isKill() { return this == KILL; } - public boolean isExit() - { + public boolean isExit() { return this == EXIT; } - public boolean isDefaultShutdown() - { + public boolean isDefaultShutdown() { return this == DEFAULT; } - public static boolean isKnown( String param ) - { - for ( Shutdown shutdown : values() ) - { - if ( shutdown.param.equals( param ) ) - { + public static boolean isKnown(String param) { + for (Shutdown shutdown : values()) { + if (shutdown.param.equals(param)) { return true; } } return false; } - public static String listParameters() - { + public static String listParameters() { StringBuilder values = new StringBuilder(); - for ( Shutdown shutdown : values() ) - { - if ( values.length() != 0 ) - { - values.append( ", " ); + for (Shutdown shutdown : values()) { + if (values.length() != 0) { + values.append(", "); } - values.append( shutdown.getParam() ); + values.append(shutdown.getParam()); } return values.toString(); } - public static Shutdown parameterOf( String parameter ) - { - for ( Shutdown shutdown : values() ) - { - if ( shutdown.param.equals( parameter ) ) - { + public static Shutdown parameterOf(String parameter) { + for (Shutdown shutdown : values()) { + if (shutdown.param.equals(parameter)) { return shutdown; } } diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/api/cli/CommandLineOption.java b/surefire-api/src/main/java/org/apache/maven/surefire/api/cli/CommandLineOption.java index fb3c2336b9..d050201d9e 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/api/cli/CommandLineOption.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/api/cli/CommandLineOption.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.api.cli; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.api.cli; import java.util.ArrayList; import java.util.Collection; @@ -30,18 +29,20 @@ * @since 2.19 * @see command line options */ -public enum CommandLineOption -{ - REACTOR_FAIL_FAST , REACTOR_FAIL_AT_END, REACTOR_FAIL_NEVER, +public enum CommandLineOption { + REACTOR_FAIL_FAST, + REACTOR_FAIL_AT_END, + REACTOR_FAIL_NEVER, SHOW_ERRORS, - LOGGING_LEVEL_WARN, LOGGING_LEVEL_INFO, LOGGING_LEVEL_ERROR, LOGGING_LEVEL_DEBUG; + LOGGING_LEVEL_WARN, + LOGGING_LEVEL_INFO, + LOGGING_LEVEL_ERROR, + LOGGING_LEVEL_DEBUG; - public static List fromStrings( Collection elements ) - { - List options = new ArrayList<>( elements.size() ); - for ( String element : elements ) - { - options.add( valueOf( element ) ); + public static List fromStrings(Collection elements) { + List options = new ArrayList<>(elements.size()); + for (String element : elements) { + options.add(valueOf(element)); } return options; } diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/api/event/AbstractConsoleEvent.java b/surefire-api/src/main/java/org/apache/maven/surefire/api/event/AbstractConsoleEvent.java index 94b7287fae..5407f3707b 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/api/event/AbstractConsoleEvent.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/api/event/AbstractConsoleEvent.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.api.event; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.api.event; import org.apache.maven.surefire.api.booter.ForkedProcessEventType; @@ -26,60 +25,50 @@ * * @since 3.0.0-M5 */ -public abstract class AbstractConsoleEvent extends Event -{ +public abstract class AbstractConsoleEvent extends Event { private final String message; - protected AbstractConsoleEvent( ForkedProcessEventType eventType, String message ) - { - super( eventType ); + protected AbstractConsoleEvent(ForkedProcessEventType eventType, String message) { + super(eventType); this.message = message; } - public String getMessage() - { + public String getMessage() { return message; } @Override - public boolean isControlCategory() - { + public boolean isControlCategory() { return false; } @Override - public boolean isConsoleCategory() - { + public boolean isConsoleCategory() { return true; } @Override - public boolean isConsoleErrorCategory() - { + public boolean isConsoleErrorCategory() { return false; } @Override - public boolean isStandardStreamCategory() - { + public boolean isStandardStreamCategory() { return false; } @Override - public boolean isSysPropCategory() - { + public boolean isSysPropCategory() { return false; } @Override - public boolean isTestCategory() - { + public boolean isTestCategory() { return false; } @Override - public boolean isJvmExitError() - { + public boolean isJvmExitError() { return false; } } diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/api/event/AbstractStandardStreamEvent.java b/surefire-api/src/main/java/org/apache/maven/surefire/api/event/AbstractStandardStreamEvent.java index 4393ee3d60..c66b5b2af8 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/api/event/AbstractStandardStreamEvent.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/api/event/AbstractStandardStreamEvent.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.api.event; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.api.event; import org.apache.maven.surefire.api.booter.ForkedProcessEventType; import org.apache.maven.surefire.api.report.RunMode; @@ -27,75 +26,63 @@ * * @since 3.0.0-M5 */ -public abstract class AbstractStandardStreamEvent extends Event -{ +public abstract class AbstractStandardStreamEvent extends Event { private final RunMode runMode; private final Long testRunId; private final String message; - protected AbstractStandardStreamEvent( ForkedProcessEventType eventType, RunMode runMode, Long testRunId, - String message ) - { - super( eventType ); + protected AbstractStandardStreamEvent( + ForkedProcessEventType eventType, RunMode runMode, Long testRunId, String message) { + super(eventType); this.runMode = runMode; this.testRunId = testRunId; this.message = message; } - public RunMode getRunMode() - { + public RunMode getRunMode() { return runMode; } - public Long getTestRunId() - { + public Long getTestRunId() { return testRunId; } - public String getMessage() - { + public String getMessage() { return message; } @Override - public boolean isControlCategory() - { + public boolean isControlCategory() { return false; } @Override - public boolean isConsoleCategory() - { + public boolean isConsoleCategory() { return false; } @Override - public boolean isConsoleErrorCategory() - { + public boolean isConsoleErrorCategory() { return false; } @Override - public boolean isStandardStreamCategory() - { + public boolean isStandardStreamCategory() { return true; } @Override - public boolean isSysPropCategory() - { + public boolean isSysPropCategory() { return false; } @Override - public boolean isTestCategory() - { + public boolean isTestCategory() { return false; } @Override - public boolean isJvmExitError() - { + public boolean isJvmExitError() { return false; } } diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/api/event/AbstractTestControlEvent.java b/surefire-api/src/main/java/org/apache/maven/surefire/api/event/AbstractTestControlEvent.java index a43ed33420..863a5ebfb5 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/api/event/AbstractTestControlEvent.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/api/event/AbstractTestControlEvent.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.api.event; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.api.event; import org.apache.maven.surefire.api.booter.ForkedProcessEventType; import org.apache.maven.surefire.api.report.ReportEntry; @@ -28,60 +27,50 @@ * @since 3.0.0-M5 * @param TestSetReportEntry or ReportEntry */ -public abstract class AbstractTestControlEvent extends Event -{ +public abstract class AbstractTestControlEvent extends Event { private final T reportEntry; - public AbstractTestControlEvent( ForkedProcessEventType eventType, T reportEntry ) - { - super( eventType ); + public AbstractTestControlEvent(ForkedProcessEventType eventType, T reportEntry) { + super(eventType); this.reportEntry = reportEntry; } - public T getReportEntry() - { + public T getReportEntry() { return reportEntry; } @Override - public boolean isControlCategory() - { + public boolean isControlCategory() { return false; } @Override - public boolean isConsoleCategory() - { + public boolean isConsoleCategory() { return false; } @Override - public boolean isConsoleErrorCategory() - { + public boolean isConsoleErrorCategory() { return false; } @Override - public boolean isStandardStreamCategory() - { + public boolean isStandardStreamCategory() { return false; } @Override - public boolean isSysPropCategory() - { + public boolean isSysPropCategory() { return false; } @Override - public boolean isTestCategory() - { + public boolean isTestCategory() { return true; } @Override - public boolean isJvmExitError() - { + public boolean isJvmExitError() { return false; } } diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/api/event/ConsoleDebugEvent.java b/surefire-api/src/main/java/org/apache/maven/surefire/api/event/ConsoleDebugEvent.java index e9bc6d7aaa..ddcade3578 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/api/event/ConsoleDebugEvent.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/api/event/ConsoleDebugEvent.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.api.event; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.api.event; import static org.apache.maven.surefire.api.booter.ForkedProcessEventType.BOOTERCODE_CONSOLE_DEBUG; @@ -26,10 +25,8 @@ * * @since 3.0.0-M5 */ -public final class ConsoleDebugEvent extends AbstractConsoleEvent -{ - public ConsoleDebugEvent( String message ) - { - super( BOOTERCODE_CONSOLE_DEBUG, message ); +public final class ConsoleDebugEvent extends AbstractConsoleEvent { + public ConsoleDebugEvent(String message) { + super(BOOTERCODE_CONSOLE_DEBUG, message); } } diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/api/event/ConsoleErrorEvent.java b/surefire-api/src/main/java/org/apache/maven/surefire/api/event/ConsoleErrorEvent.java index c4d58e5217..a27a99bde8 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/api/event/ConsoleErrorEvent.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/api/event/ConsoleErrorEvent.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.api.event; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.api.event; import org.apache.maven.surefire.api.report.StackTraceWriter; @@ -28,60 +27,50 @@ * * @since 3.0.0-M5 */ -public final class ConsoleErrorEvent extends Event -{ +public final class ConsoleErrorEvent extends Event { private final StackTraceWriter stackTraceWriter; - public ConsoleErrorEvent( StackTraceWriter stackTraceWriter ) - { - super( BOOTERCODE_CONSOLE_ERROR ); + public ConsoleErrorEvent(StackTraceWriter stackTraceWriter) { + super(BOOTERCODE_CONSOLE_ERROR); this.stackTraceWriter = stackTraceWriter; } - public StackTraceWriter getStackTraceWriter() - { + public StackTraceWriter getStackTraceWriter() { return stackTraceWriter; } @Override - public boolean isControlCategory() - { + public boolean isControlCategory() { return false; } @Override - public boolean isConsoleCategory() - { + public boolean isConsoleCategory() { return true; } @Override - public boolean isConsoleErrorCategory() - { + public boolean isConsoleErrorCategory() { return true; } @Override - public boolean isStandardStreamCategory() - { + public boolean isStandardStreamCategory() { return false; } @Override - public boolean isSysPropCategory() - { + public boolean isSysPropCategory() { return false; } @Override - public boolean isTestCategory() - { + public boolean isTestCategory() { return false; } @Override - public boolean isJvmExitError() - { + public boolean isJvmExitError() { return false; } } diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/api/event/ConsoleInfoEvent.java b/surefire-api/src/main/java/org/apache/maven/surefire/api/event/ConsoleInfoEvent.java index 97cd73a65a..309affc9c2 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/api/event/ConsoleInfoEvent.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/api/event/ConsoleInfoEvent.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.api.event; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.api.event; import static org.apache.maven.surefire.api.booter.ForkedProcessEventType.BOOTERCODE_CONSOLE_INFO; @@ -26,10 +25,8 @@ * * @since 3.0.0-M5 */ -public final class ConsoleInfoEvent extends AbstractConsoleEvent -{ - public ConsoleInfoEvent( String message ) - { - super( BOOTERCODE_CONSOLE_INFO, message ); +public final class ConsoleInfoEvent extends AbstractConsoleEvent { + public ConsoleInfoEvent(String message) { + super(BOOTERCODE_CONSOLE_INFO, message); } } diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/api/event/ConsoleWarningEvent.java b/surefire-api/src/main/java/org/apache/maven/surefire/api/event/ConsoleWarningEvent.java index db522ebbbe..3c9d452796 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/api/event/ConsoleWarningEvent.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/api/event/ConsoleWarningEvent.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.api.event; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.api.event; import static org.apache.maven.surefire.api.booter.ForkedProcessEventType.BOOTERCODE_CONSOLE_WARNING; @@ -26,10 +25,8 @@ * * @since 3.0.0-M5 */ -public final class ConsoleWarningEvent extends AbstractConsoleEvent -{ - public ConsoleWarningEvent( String message ) - { - super( BOOTERCODE_CONSOLE_WARNING, message ); +public final class ConsoleWarningEvent extends AbstractConsoleEvent { + public ConsoleWarningEvent(String message) { + super(BOOTERCODE_CONSOLE_WARNING, message); } } diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/api/event/ControlByeEvent.java b/surefire-api/src/main/java/org/apache/maven/surefire/api/event/ControlByeEvent.java index 898a1d68c4..723847b910 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/api/event/ControlByeEvent.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/api/event/ControlByeEvent.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.api.event; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.api.event; import static org.apache.maven.surefire.api.booter.ForkedProcessEventType.BOOTERCODE_BYE; @@ -26,52 +25,43 @@ * * @since 3.0.0-M5 */ -public final class ControlByeEvent extends Event -{ - public ControlByeEvent() - { - super( BOOTERCODE_BYE ); +public final class ControlByeEvent extends Event { + public ControlByeEvent() { + super(BOOTERCODE_BYE); } @Override - public boolean isControlCategory() - { + public boolean isControlCategory() { return true; } @Override - public boolean isConsoleCategory() - { + public boolean isConsoleCategory() { return false; } @Override - public boolean isConsoleErrorCategory() - { + public boolean isConsoleErrorCategory() { return false; } @Override - public boolean isStandardStreamCategory() - { + public boolean isStandardStreamCategory() { return false; } @Override - public boolean isSysPropCategory() - { + public boolean isSysPropCategory() { return false; } @Override - public boolean isTestCategory() - { + public boolean isTestCategory() { return false; } @Override - public boolean isJvmExitError() - { + public boolean isJvmExitError() { return false; } } diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/api/event/ControlNextTestEvent.java b/surefire-api/src/main/java/org/apache/maven/surefire/api/event/ControlNextTestEvent.java index c71204dcd5..05ffbad566 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/api/event/ControlNextTestEvent.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/api/event/ControlNextTestEvent.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.api.event; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.api.event; import static org.apache.maven.surefire.api.booter.ForkedProcessEventType.BOOTERCODE_NEXT_TEST; @@ -26,52 +25,43 @@ * * @since 3.0.0-M5 */ -public final class ControlNextTestEvent extends Event -{ - public ControlNextTestEvent() - { - super( BOOTERCODE_NEXT_TEST ); +public final class ControlNextTestEvent extends Event { + public ControlNextTestEvent() { + super(BOOTERCODE_NEXT_TEST); } @Override - public boolean isControlCategory() - { + public boolean isControlCategory() { return true; } @Override - public boolean isConsoleCategory() - { + public boolean isConsoleCategory() { return false; } @Override - public boolean isConsoleErrorCategory() - { + public boolean isConsoleErrorCategory() { return false; } @Override - public boolean isStandardStreamCategory() - { + public boolean isStandardStreamCategory() { return false; } @Override - public boolean isSysPropCategory() - { + public boolean isSysPropCategory() { return false; } @Override - public boolean isTestCategory() - { + public boolean isTestCategory() { return false; } @Override - public boolean isJvmExitError() - { + public boolean isJvmExitError() { return false; } } diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/api/event/ControlStopOnNextTestEvent.java b/surefire-api/src/main/java/org/apache/maven/surefire/api/event/ControlStopOnNextTestEvent.java index 7a3c3dd998..cba953c503 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/api/event/ControlStopOnNextTestEvent.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/api/event/ControlStopOnNextTestEvent.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.api.event; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.api.event; import static org.apache.maven.surefire.api.booter.ForkedProcessEventType.BOOTERCODE_STOP_ON_NEXT_TEST; @@ -26,52 +25,43 @@ * * @since 3.0.0-M5 */ -public final class ControlStopOnNextTestEvent extends Event -{ - public ControlStopOnNextTestEvent() - { - super( BOOTERCODE_STOP_ON_NEXT_TEST ); +public final class ControlStopOnNextTestEvent extends Event { + public ControlStopOnNextTestEvent() { + super(BOOTERCODE_STOP_ON_NEXT_TEST); } @Override - public boolean isControlCategory() - { + public boolean isControlCategory() { return true; } @Override - public boolean isConsoleCategory() - { + public boolean isConsoleCategory() { return false; } @Override - public boolean isConsoleErrorCategory() - { + public boolean isConsoleErrorCategory() { return false; } @Override - public boolean isStandardStreamCategory() - { + public boolean isStandardStreamCategory() { return false; } @Override - public boolean isSysPropCategory() - { + public boolean isSysPropCategory() { return false; } @Override - public boolean isTestCategory() - { + public boolean isTestCategory() { return false; } @Override - public boolean isJvmExitError() - { + public boolean isJvmExitError() { return false; } } diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/api/event/Event.java b/surefire-api/src/main/java/org/apache/maven/surefire/api/event/Event.java index 6e94cfd546..eb4aba97fc 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/api/event/Event.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/api/event/Event.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.api.event; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.api.event; import org.apache.maven.surefire.api.booter.ForkedProcessEventType; @@ -27,25 +26,28 @@ * @author Tibor Digana (tibor17) * @since 3.0.0-M5 */ -public abstract class Event -{ +public abstract class Event { private final ForkedProcessEventType eventType; - public Event( ForkedProcessEventType eventType ) - { + public Event(ForkedProcessEventType eventType) { this.eventType = eventType; } public abstract boolean isControlCategory(); + public abstract boolean isConsoleCategory(); + public abstract boolean isConsoleErrorCategory(); + public abstract boolean isStandardStreamCategory(); + public abstract boolean isSysPropCategory(); + public abstract boolean isTestCategory(); + public abstract boolean isJvmExitError(); - public final ForkedProcessEventType getEventType() - { + public final ForkedProcessEventType getEventType() { return eventType; } } diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/api/event/JvmExitErrorEvent.java b/surefire-api/src/main/java/org/apache/maven/surefire/api/event/JvmExitErrorEvent.java index 2112fc750d..da2e2293db 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/api/event/JvmExitErrorEvent.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/api/event/JvmExitErrorEvent.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.api.event; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.api.event; import org.apache.maven.surefire.api.report.StackTraceWriter; @@ -28,60 +27,50 @@ * * @since 3.0.0-M5 */ -public final class JvmExitErrorEvent extends Event -{ +public final class JvmExitErrorEvent extends Event { private final StackTraceWriter stackTraceWriter; - public JvmExitErrorEvent( StackTraceWriter stackTraceWriter ) - { - super( BOOTERCODE_JVM_EXIT_ERROR ); + public JvmExitErrorEvent(StackTraceWriter stackTraceWriter) { + super(BOOTERCODE_JVM_EXIT_ERROR); this.stackTraceWriter = stackTraceWriter; } - public StackTraceWriter getStackTraceWriter() - { + public StackTraceWriter getStackTraceWriter() { return stackTraceWriter; } @Override - public boolean isControlCategory() - { + public boolean isControlCategory() { return false; } @Override - public boolean isConsoleCategory() - { + public boolean isConsoleCategory() { return false; } @Override - public boolean isConsoleErrorCategory() - { + public boolean isConsoleErrorCategory() { return false; } @Override - public boolean isStandardStreamCategory() - { + public boolean isStandardStreamCategory() { return false; } @Override - public boolean isSysPropCategory() - { + public boolean isSysPropCategory() { return false; } @Override - public boolean isTestCategory() - { + public boolean isTestCategory() { return false; } @Override - public boolean isJvmExitError() - { + public boolean isJvmExitError() { return true; } } diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/api/event/StandardStreamErrEvent.java b/surefire-api/src/main/java/org/apache/maven/surefire/api/event/StandardStreamErrEvent.java index 7188b8b1e1..27ce8e6418 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/api/event/StandardStreamErrEvent.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/api/event/StandardStreamErrEvent.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.api.event; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.api.event; import org.apache.maven.surefire.api.report.RunMode; @@ -28,10 +27,8 @@ * * @since 3.0.0-M5 */ -public final class StandardStreamErrEvent extends AbstractStandardStreamEvent -{ - public StandardStreamErrEvent( RunMode runMode, Long testRunId, String message ) - { - super( BOOTERCODE_STDERR, runMode, testRunId, message ); +public final class StandardStreamErrEvent extends AbstractStandardStreamEvent { + public StandardStreamErrEvent(RunMode runMode, Long testRunId, String message) { + super(BOOTERCODE_STDERR, runMode, testRunId, message); } } diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/api/event/StandardStreamErrWithNewLineEvent.java b/surefire-api/src/main/java/org/apache/maven/surefire/api/event/StandardStreamErrWithNewLineEvent.java index 968dcb3f08..29ca5ef13e 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/api/event/StandardStreamErrWithNewLineEvent.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/api/event/StandardStreamErrWithNewLineEvent.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.api.event; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.api.event; import org.apache.maven.surefire.api.report.RunMode; @@ -28,10 +27,8 @@ * * @since 3.0.0-M5 */ -public final class StandardStreamErrWithNewLineEvent extends AbstractStandardStreamEvent -{ - public StandardStreamErrWithNewLineEvent( RunMode runMode, Long testRunId, String message ) - { - super( BOOTERCODE_STDERR_NEW_LINE, runMode, testRunId, message ); +public final class StandardStreamErrWithNewLineEvent extends AbstractStandardStreamEvent { + public StandardStreamErrWithNewLineEvent(RunMode runMode, Long testRunId, String message) { + super(BOOTERCODE_STDERR_NEW_LINE, runMode, testRunId, message); } } diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/api/event/StandardStreamOutEvent.java b/surefire-api/src/main/java/org/apache/maven/surefire/api/event/StandardStreamOutEvent.java index 1525de7eed..22e96c33dd 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/api/event/StandardStreamOutEvent.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/api/event/StandardStreamOutEvent.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.api.event; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.api.event; import org.apache.maven.surefire.api.report.RunMode; @@ -28,10 +27,8 @@ * * @since 3.0.0-M5 */ -public final class StandardStreamOutEvent extends AbstractStandardStreamEvent -{ - public StandardStreamOutEvent( RunMode runMode, Long testRunId, String message ) - { - super( BOOTERCODE_STDOUT, runMode, testRunId, message ); +public final class StandardStreamOutEvent extends AbstractStandardStreamEvent { + public StandardStreamOutEvent(RunMode runMode, Long testRunId, String message) { + super(BOOTERCODE_STDOUT, runMode, testRunId, message); } } diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/api/event/StandardStreamOutWithNewLineEvent.java b/surefire-api/src/main/java/org/apache/maven/surefire/api/event/StandardStreamOutWithNewLineEvent.java index b566bf9087..9f5356c5ed 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/api/event/StandardStreamOutWithNewLineEvent.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/api/event/StandardStreamOutWithNewLineEvent.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.api.event; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.api.event; import org.apache.maven.surefire.api.report.RunMode; @@ -28,10 +27,8 @@ * * @since 3.0.0-M5 */ -public final class StandardStreamOutWithNewLineEvent extends AbstractStandardStreamEvent -{ - public StandardStreamOutWithNewLineEvent( RunMode runMode, Long testRunId, String message ) - { - super( BOOTERCODE_STDOUT_NEW_LINE, runMode, testRunId, message ); +public final class StandardStreamOutWithNewLineEvent extends AbstractStandardStreamEvent { + public StandardStreamOutWithNewLineEvent(RunMode runMode, Long testRunId, String message) { + super(BOOTERCODE_STDOUT_NEW_LINE, runMode, testRunId, message); } } diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/api/event/SystemPropertyEvent.java b/surefire-api/src/main/java/org/apache/maven/surefire/api/event/SystemPropertyEvent.java index 0b293b544d..425540fba7 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/api/event/SystemPropertyEvent.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/api/event/SystemPropertyEvent.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.api.event; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.api.event; import org.apache.maven.surefire.api.report.RunMode; @@ -28,81 +27,68 @@ * * @since 3.0.0-M5 */ -public final class SystemPropertyEvent extends Event -{ +public final class SystemPropertyEvent extends Event { private final RunMode runMode; private final Long testRunId; private final String key; private final String value; - public SystemPropertyEvent( RunMode runMode, Long testRunId, String key, String value ) - { - super( BOOTERCODE_SYSPROPS ); + public SystemPropertyEvent(RunMode runMode, Long testRunId, String key, String value) { + super(BOOTERCODE_SYSPROPS); this.runMode = runMode; this.testRunId = testRunId; this.key = key; this.value = value; } - public RunMode getRunMode() - { + public RunMode getRunMode() { return runMode; } - public Long getTestRunId() - { + public Long getTestRunId() { return testRunId; } - public String getKey() - { + public String getKey() { return key; } - public String getValue() - { + public String getValue() { return value; } @Override - public boolean isControlCategory() - { + public boolean isControlCategory() { return false; } @Override - public boolean isConsoleCategory() - { + public boolean isConsoleCategory() { return false; } @Override - public boolean isConsoleErrorCategory() - { + public boolean isConsoleErrorCategory() { return false; } @Override - public boolean isStandardStreamCategory() - { + public boolean isStandardStreamCategory() { return false; } @Override - public boolean isSysPropCategory() - { + public boolean isSysPropCategory() { return true; } @Override - public boolean isTestCategory() - { + public boolean isTestCategory() { return false; } @Override - public boolean isJvmExitError() - { + public boolean isJvmExitError() { return false; } } diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/api/event/TestAssumptionFailureEvent.java b/surefire-api/src/main/java/org/apache/maven/surefire/api/event/TestAssumptionFailureEvent.java index c702dc80d9..aba4cfa60c 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/api/event/TestAssumptionFailureEvent.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/api/event/TestAssumptionFailureEvent.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.api.event; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.api.event; import org.apache.maven.surefire.api.report.ReportEntry; @@ -28,10 +27,8 @@ * * @since 3.0.0-M5 */ -public final class TestAssumptionFailureEvent extends AbstractTestControlEvent -{ - public TestAssumptionFailureEvent( ReportEntry reportEntry ) - { - super( BOOTERCODE_TEST_ASSUMPTIONFAILURE, reportEntry ); +public final class TestAssumptionFailureEvent extends AbstractTestControlEvent { + public TestAssumptionFailureEvent(ReportEntry reportEntry) { + super(BOOTERCODE_TEST_ASSUMPTIONFAILURE, reportEntry); } } diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/api/event/TestErrorEvent.java b/surefire-api/src/main/java/org/apache/maven/surefire/api/event/TestErrorEvent.java index a66f63c046..35f9947140 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/api/event/TestErrorEvent.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/api/event/TestErrorEvent.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.api.event; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.api.event; import org.apache.maven.surefire.api.report.ReportEntry; @@ -28,10 +27,8 @@ * * @since 3.0.0-M5 */ -public final class TestErrorEvent extends AbstractTestControlEvent -{ - public TestErrorEvent( ReportEntry reportEntry ) - { - super( BOOTERCODE_TEST_ERROR, reportEntry ); +public final class TestErrorEvent extends AbstractTestControlEvent { + public TestErrorEvent(ReportEntry reportEntry) { + super(BOOTERCODE_TEST_ERROR, reportEntry); } } diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/api/event/TestFailedEvent.java b/surefire-api/src/main/java/org/apache/maven/surefire/api/event/TestFailedEvent.java index 1905e07ac1..22c4c221c3 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/api/event/TestFailedEvent.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/api/event/TestFailedEvent.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.api.event; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.api.event; import org.apache.maven.surefire.api.report.ReportEntry; @@ -28,10 +27,8 @@ * * @since 3.0.0-M5 */ -public final class TestFailedEvent extends AbstractTestControlEvent -{ - public TestFailedEvent( ReportEntry reportEntry ) - { - super( BOOTERCODE_TEST_FAILED, reportEntry ); +public final class TestFailedEvent extends AbstractTestControlEvent { + public TestFailedEvent(ReportEntry reportEntry) { + super(BOOTERCODE_TEST_FAILED, reportEntry); } } diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/api/event/TestSkippedEvent.java b/surefire-api/src/main/java/org/apache/maven/surefire/api/event/TestSkippedEvent.java index f33b52823c..c0622fdb00 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/api/event/TestSkippedEvent.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/api/event/TestSkippedEvent.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.api.event; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.api.event; import org.apache.maven.surefire.api.report.ReportEntry; @@ -28,10 +27,8 @@ * * @since 3.0.0-M5 */ -public final class TestSkippedEvent extends AbstractTestControlEvent -{ - public TestSkippedEvent( ReportEntry reportEntry ) - { - super( BOOTERCODE_TEST_SKIPPED, reportEntry ); +public final class TestSkippedEvent extends AbstractTestControlEvent { + public TestSkippedEvent(ReportEntry reportEntry) { + super(BOOTERCODE_TEST_SKIPPED, reportEntry); } } diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/api/event/TestStartingEvent.java b/surefire-api/src/main/java/org/apache/maven/surefire/api/event/TestStartingEvent.java index 9ef3e71626..eb1edcad22 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/api/event/TestStartingEvent.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/api/event/TestStartingEvent.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.api.event; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.api.event; import org.apache.maven.surefire.api.report.ReportEntry; @@ -28,10 +27,8 @@ * * @since 3.0.0-M5 */ -public final class TestStartingEvent extends AbstractTestControlEvent -{ - public TestStartingEvent( ReportEntry reportEntry ) - { - super( BOOTERCODE_TEST_STARTING, reportEntry ); +public final class TestStartingEvent extends AbstractTestControlEvent { + public TestStartingEvent(ReportEntry reportEntry) { + super(BOOTERCODE_TEST_STARTING, reportEntry); } } diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/api/event/TestSucceededEvent.java b/surefire-api/src/main/java/org/apache/maven/surefire/api/event/TestSucceededEvent.java index fad36eb7d4..1f571c22d4 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/api/event/TestSucceededEvent.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/api/event/TestSucceededEvent.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.api.event; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.api.event; import org.apache.maven.surefire.api.report.ReportEntry; @@ -28,10 +27,8 @@ * * @since 3.0.0-M5 */ -public final class TestSucceededEvent extends AbstractTestControlEvent -{ - public TestSucceededEvent( ReportEntry reportEntry ) - { - super( BOOTERCODE_TEST_SUCCEEDED, reportEntry ); +public final class TestSucceededEvent extends AbstractTestControlEvent { + public TestSucceededEvent(ReportEntry reportEntry) { + super(BOOTERCODE_TEST_SUCCEEDED, reportEntry); } } diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/api/event/TestsetCompletedEvent.java b/surefire-api/src/main/java/org/apache/maven/surefire/api/event/TestsetCompletedEvent.java index 2d82a39b44..e69adb9d61 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/api/event/TestsetCompletedEvent.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/api/event/TestsetCompletedEvent.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.api.event; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.api.event; import org.apache.maven.surefire.api.report.TestSetReportEntry; @@ -28,10 +27,8 @@ * * @since 3.0.0-M5 */ -public final class TestsetCompletedEvent extends AbstractTestControlEvent -{ - public TestsetCompletedEvent( TestSetReportEntry reportEntry ) - { - super( BOOTERCODE_TESTSET_COMPLETED, reportEntry ); +public final class TestsetCompletedEvent extends AbstractTestControlEvent { + public TestsetCompletedEvent(TestSetReportEntry reportEntry) { + super(BOOTERCODE_TESTSET_COMPLETED, reportEntry); } } diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/api/event/TestsetStartingEvent.java b/surefire-api/src/main/java/org/apache/maven/surefire/api/event/TestsetStartingEvent.java index 5518f0d6ab..85c2963736 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/api/event/TestsetStartingEvent.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/api/event/TestsetStartingEvent.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.api.event; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.api.event; import org.apache.maven.surefire.api.report.TestSetReportEntry; @@ -28,10 +27,8 @@ * * @since 3.0.0-M5 */ -public final class TestsetStartingEvent extends AbstractTestControlEvent -{ - public TestsetStartingEvent( TestSetReportEntry reportEntry ) - { - super( BOOTERCODE_TESTSET_STARTING, reportEntry ); +public final class TestsetStartingEvent extends AbstractTestControlEvent { + public TestsetStartingEvent(TestSetReportEntry reportEntry) { + super(BOOTERCODE_TESTSET_STARTING, reportEntry); } } diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/api/filter/NonAbstractClassFilter.java b/surefire-api/src/main/java/org/apache/maven/surefire/api/filter/NonAbstractClassFilter.java index f7c2aed708..9b6f2ccb8f 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/api/filter/NonAbstractClassFilter.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/api/filter/NonAbstractClassFilter.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.api.filter; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,19 +16,18 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.api.filter; import java.lang.reflect.Modifier; + import org.apache.maven.surefire.api.util.ScannerFilter; /** * @author Kristian Rosenvold */ -public class NonAbstractClassFilter - implements ScannerFilter -{ +public class NonAbstractClassFilter implements ScannerFilter { @Override - public boolean accept( Class testClass ) - { - return !Modifier.isAbstract( testClass.getModifiers() ); + public boolean accept(Class testClass) { + return !Modifier.isAbstract(testClass.getModifiers()); } } diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/api/filter/SpecificTestClassFilter.java b/surefire-api/src/main/java/org/apache/maven/surefire/api/filter/SpecificTestClassFilter.java index 112f5eecef..5efc91c17f 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/api/filter/SpecificTestClassFilter.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/api/filter/SpecificTestClassFilter.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.api.filter; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,70 +16,61 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.api.filter; import java.util.Collections; import java.util.HashSet; import java.util.Set; -import org.apache.maven.surefire.shared.utils.io.SelectorUtils; + import org.apache.maven.surefire.api.util.ScannerFilter; +import org.apache.maven.surefire.shared.utils.io.SelectorUtils; /** * Filter for test class files * */ -public class SpecificTestClassFilter - implements ScannerFilter -{ +public class SpecificTestClassFilter implements ScannerFilter { - private static final char FS = System.getProperty( "file.separator" ).charAt( 0 ); + private static final char FS = System.getProperty("file.separator").charAt(0); private static final String JAVA_CLASS_FILE_EXTENSION = ".class"; private Set names; - public SpecificTestClassFilter( String[] classNames ) - { - if ( classNames != null && classNames.length > 0 ) - { + public SpecificTestClassFilter(String[] classNames) { + if (classNames != null && classNames.length > 0) { names = new HashSet<>(); - Collections.addAll( names, classNames ); + Collections.addAll(names, classNames); } } @Override - public boolean accept( Class testClass ) - { + public boolean accept(Class testClass) { // If the tests enumeration is empty, allow anything. boolean result = true; - if ( names != null && !names.isEmpty() ) - { - String className = testClass.getName().replace( '.', FS ) + JAVA_CLASS_FILE_EXTENSION; + if (names != null && !names.isEmpty()) { + String className = testClass.getName().replace('.', FS) + JAVA_CLASS_FILE_EXTENSION; boolean found = false; - for ( String pattern : names ) - { - if ( '\\' == FS ) - { - pattern = pattern.replace( '/', FS ); + for (String pattern : names) { + if ('\\' == FS) { + pattern = pattern.replace('/', FS); } // This is the same utility used under the covers in the plexus DirectoryScanner, and // therefore in the surefire DefaultDirectoryScanner implementation. - if ( SelectorUtils.matchPath( pattern, className, true ) ) - { + if (SelectorUtils.matchPath(pattern, className, true)) { found = true; break; } } - if ( !found ) - { + if (!found) { result = false; } } return result; } - } diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/api/fork/ForkNodeArguments.java b/surefire-api/src/main/java/org/apache/maven/surefire/api/fork/ForkNodeArguments.java index ee5c2bfdff..c3561df931 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/api/fork/ForkNodeArguments.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/api/fork/ForkNodeArguments.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.api.fork; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,21 +16,22 @@ * specific language governing permissions and limitations * under the License. */ - -import org.apache.maven.plugin.surefire.log.api.ConsoleLogger; +package org.apache.maven.surefire.api.fork; import javax.annotation.Nonnegative; import javax.annotation.Nonnull; + import java.io.File; +import org.apache.maven.plugin.surefire.log.api.ConsoleLogger; + /** * The properties related to the current JVM. * * @author Tibor Digana (tibor17) * @since 3.0.0-M5 */ -public interface ForkNodeArguments -{ +public interface ForkNodeArguments { @Nonnull String getSessionId(); @@ -45,12 +44,12 @@ public interface ForkNodeArguments int getForkChannelId(); @Nonnull - File dumpStreamText( @Nonnull String text ); + File dumpStreamText(@Nonnull String text); @Nonnull - File dumpStreamException( @Nonnull Throwable t ); + File dumpStreamException(@Nonnull Throwable t); - void logWarningAtEnd( @Nonnull String text ); + void logWarningAtEnd(@Nonnull String text); @Nonnull ConsoleLogger getConsoleLogger(); diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/api/provider/AbstractProvider.java b/surefire-api/src/main/java/org/apache/maven/surefire/api/provider/AbstractProvider.java index c193f91d7c..fb4169cc06 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/api/provider/AbstractProvider.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/api/provider/AbstractProvider.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.api.provider; /* @@ -24,18 +42,13 @@ * * @author Kristian Rosenvold */ -public abstract class AbstractProvider - implements SurefireProvider -{ +public abstract class AbstractProvider implements SurefireProvider { private final Thread creatingThread = Thread.currentThread(); @Override - public void cancel() - { - synchronized ( creatingThread ) - { - if ( creatingThread.isAlive() ) - { + public void cancel() { + synchronized (creatingThread) { + if (creatingThread.isAlive()) { creatingThread.interrupt(); } } diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/api/provider/CommandChainReader.java b/surefire-api/src/main/java/org/apache/maven/surefire/api/provider/CommandChainReader.java index 8993774fc3..d432ca7ba5 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/api/provider/CommandChainReader.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/api/provider/CommandChainReader.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.api.provider; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,18 +16,17 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.api.provider; import org.apache.maven.surefire.api.testset.TestSetFailedException; /** * Hiding CommandReader instance in provider. */ -public interface CommandChainReader -{ - boolean awaitStarted() - throws TestSetFailedException; +public interface CommandChainReader { + boolean awaitStarted() throws TestSetFailedException; - void addSkipNextTestsListener( CommandListener listener ); + void addSkipNextTestsListener(CommandListener listener); - void addShutdownListener( CommandListener listener ); + void addShutdownListener(CommandListener listener); } diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/api/provider/CommandListener.java b/surefire-api/src/main/java/org/apache/maven/surefire/api/provider/CommandListener.java index 4544b4f38e..bf8aee79ff 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/api/provider/CommandListener.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/api/provider/CommandListener.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.api.provider; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,13 +16,13 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.api.provider; import org.apache.maven.surefire.api.booter.Command; /** * Command listener interface. */ -public interface CommandListener -{ - void update( Command command ); +public interface CommandListener { + void update(Command command); } diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/api/provider/ProviderParameters.java b/surefire-api/src/main/java/org/apache/maven/surefire/api/provider/ProviderParameters.java index 34a2ffa689..71caddaee4 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/api/provider/ProviderParameters.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/api/provider/ProviderParameters.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.api.provider; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,10 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.api.provider; + +import java.util.List; +import java.util.Map; import org.apache.maven.surefire.api.cli.CommandLineOption; import org.apache.maven.surefire.api.report.ReporterConfiguration; @@ -29,9 +31,6 @@ import org.apache.maven.surefire.api.util.RunOrderCalculator; import org.apache.maven.surefire.api.util.ScanResult; -import java.util.List; -import java.util.Map; - /** * Injected into the providers upon provider construction. Allows the provider to request services and data it needs. *
    @@ -42,8 +41,7 @@ * * @author Kristian Rosenvold */ -public interface ProviderParameters -{ +public interface ProviderParameters { /** * Provides a directory scanner that enforces the includes/excludes parameters that were passed to surefire. * See #getDirectoryScannerParameters for details @@ -61,7 +59,6 @@ public interface ProviderParameters */ ScanResult getScanResult(); - /** * Provides a service to calculate run order of tests. Applied after directory scanning. * @@ -97,7 +94,6 @@ public interface ProviderParameters * * @return The testRequest */ - TestRequest getTestRequest(); /** diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/api/provider/SurefireProvider.java b/surefire-api/src/main/java/org/apache/maven/surefire/api/provider/SurefireProvider.java index 4e04aad24c..a3194b355e 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/api/provider/SurefireProvider.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/api/provider/SurefireProvider.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.api.provider; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,8 +16,10 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.api.provider; import java.lang.reflect.InvocationTargetException; + import org.apache.maven.surefire.api.report.ReporterException; import org.apache.maven.surefire.api.suite.RunResult; import org.apache.maven.surefire.api.testset.TestSetFailedException; @@ -41,8 +41,7 @@ * * @author Kristian Rosenvold */ -public interface SurefireProvider -{ +public interface SurefireProvider { /** * Determines the number of forks. *
    @@ -66,9 +65,8 @@ public interface SurefireProvider * When testset fails * @throws InvocationTargetException fails in {@code ProviderFactory} */ - @SuppressWarnings( "checkstyle:redundantthrows" ) - RunResult invoke( Object forkTestSet ) - throws TestSetFailedException, ReporterException, InvocationTargetException; + @SuppressWarnings("checkstyle:redundantthrows") + RunResult invoke(Object forkTestSet) throws TestSetFailedException, ReporterException, InvocationTargetException; /** * Makes an attempt at cancelling the current run, giving the provider a chance to notify diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/api/report/CategorizedReportEntry.java b/surefire-api/src/main/java/org/apache/maven/surefire/api/report/CategorizedReportEntry.java index 63faadd0f3..4dc6d7f2ab 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/api/report/CategorizedReportEntry.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/api/report/CategorizedReportEntry.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.api.report; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,9 +16,11 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.api.report; import javax.annotation.Nonnegative; import javax.annotation.Nonnull; + import java.util.Collections; import java.util.Map; import java.util.Objects; @@ -30,79 +30,132 @@ /** * @author Kristian Rosenvold */ -public class CategorizedReportEntry - extends SimpleReportEntry -{ +public class CategorizedReportEntry extends SimpleReportEntry { public static final String GROUP_PREFIX = " (of "; private static final String GROUP_SUFIX = ")"; private final String group; - public CategorizedReportEntry( @Nonnull RunMode runMode, @Nonnegative Long testRunId, - String source, String name, String group ) - { - this( runMode, testRunId, source, name, group, null, null ); + public CategorizedReportEntry( + @Nonnull RunMode runMode, @Nonnegative Long testRunId, String source, String name, String group) { + this(runMode, testRunId, source, name, group, null, null); } - public CategorizedReportEntry( @Nonnull RunMode runMode, @Nonnegative Long testRunId, - String source, String name, String group, StackTraceWriter stackTraceWriter, - Integer elapsed ) - { - super( runMode, testRunId, source, null, name, null, stackTraceWriter, elapsed ); + public CategorizedReportEntry( + @Nonnull RunMode runMode, + @Nonnegative Long testRunId, + String source, + String name, + String group, + StackTraceWriter stackTraceWriter, + Integer elapsed) { + super(runMode, testRunId, source, null, name, null, stackTraceWriter, elapsed); this.group = group; } - public CategorizedReportEntry( @Nonnull RunMode runMode, @Nonnegative Long testRunId, - String source, String name, String group, StackTraceWriter stackTraceWriter, - Integer elapsed, String message ) - { - this( runMode, testRunId, source, null, name, null, - group, stackTraceWriter, elapsed, message, Collections.emptyMap() ); + public CategorizedReportEntry( + @Nonnull RunMode runMode, + @Nonnegative Long testRunId, + String source, + String name, + String group, + StackTraceWriter stackTraceWriter, + Integer elapsed, + String message) { + this( + runMode, + testRunId, + source, + null, + name, + null, + group, + stackTraceWriter, + elapsed, + message, + Collections.emptyMap()); } - public CategorizedReportEntry( @Nonnull RunMode runMode, @Nonnegative Long testRunId, - String source, String sourceText, String name, String nameText, - String group, StackTraceWriter stackTraceWriter, - Integer elapsed, String message, Map systemProperties ) - { - super( runMode, testRunId, source, sourceText, name, nameText, stackTraceWriter, elapsed, message, - systemProperties ); + public CategorizedReportEntry( + @Nonnull RunMode runMode, + @Nonnegative Long testRunId, + String source, + String sourceText, + String name, + String nameText, + String group, + StackTraceWriter stackTraceWriter, + Integer elapsed, + String message, + Map systemProperties) { + super( + runMode, + testRunId, + source, + sourceText, + name, + nameText, + stackTraceWriter, + elapsed, + message, + systemProperties); this.group = group; } - public static TestSetReportEntry reportEntry( @Nonnull RunMode runMode, @Nonnegative Long testRunId, - String source, String sourceText, String name, String nameText, - String group, - StackTraceWriter stackTraceWriter, Integer elapsed, String message, - Map systemProperties ) - { + public static TestSetReportEntry reportEntry( + @Nonnull RunMode runMode, + @Nonnegative Long testRunId, + String source, + String sourceText, + String name, + String nameText, + String group, + StackTraceWriter stackTraceWriter, + Integer elapsed, + String message, + Map systemProperties) { return group != null - ? new CategorizedReportEntry( runMode, testRunId, source, sourceText, name, nameText, - group, stackTraceWriter, elapsed, message, systemProperties ) - : new SimpleReportEntry( runMode, testRunId, source, sourceText, name, nameText, - stackTraceWriter, elapsed, message, systemProperties ); + ? new CategorizedReportEntry( + runMode, + testRunId, + source, + sourceText, + name, + nameText, + group, + stackTraceWriter, + elapsed, + message, + systemProperties) + : new SimpleReportEntry( + runMode, + testRunId, + source, + sourceText, + name, + nameText, + stackTraceWriter, + elapsed, + message, + systemProperties); } @Override - public String getGroup() - { + public String getGroup() { return group; } @Override - public String getNameWithGroup() - { + public String getNameWithGroup() { return isNameWithGroup() ? getSourceName() + GROUP_PREFIX + getGroup() + GROUP_SUFIX : getSourceName(); } @Override - public String getReportNameWithGroup() - { + public String getReportNameWithGroup() { String sourceText = getSourceText(); - if ( isBlank ( sourceText ) ) - { + if (isBlank(sourceText)) { return null; } @@ -110,36 +163,30 @@ public String getReportNameWithGroup() } @Override - public boolean equals( Object o ) - { - if ( this == o ) - { + public boolean equals(Object o) { + if (this == o) { return true; } - if ( o == null || getClass() != o.getClass() ) - { + if (o == null || getClass() != o.getClass()) { return false; } - if ( !super.equals( o ) ) - { + if (!super.equals(o)) { return false; } CategorizedReportEntry that = (CategorizedReportEntry) o; - return Objects.equals( group, that.group ); + return Objects.equals(group, that.group); } @Override - public int hashCode() - { + public int hashCode() { int result = super.hashCode(); - result = 31 * result + ( group != null ? group.hashCode() : 0 ); + result = 31 * result + (group != null ? group.hashCode() : 0); return result; } - private boolean isNameWithGroup() - { - return getGroup() != null && !getGroup().equals( getSourceName() ); + private boolean isNameWithGroup() { + return getGroup() != null && !getGroup().equals(getSourceName()); } } diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/api/report/ConsoleOutputCapture.java b/surefire-api/src/main/java/org/apache/maven/surefire/api/report/ConsoleOutputCapture.java index 095dab0f74..a0297b114e 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/api/report/ConsoleOutputCapture.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/api/report/ConsoleOutputCapture.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.api.report; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.api.report; import javax.annotation.Nonnull; @@ -36,208 +35,166 @@ * Deals with system.out/err. *
    */ -public final class ConsoleOutputCapture -{ - public static void startCapture( TestOutputReceiver target ) - { - setOut( new ForwardingPrintStream( true, target ) ); - setErr( new ForwardingPrintStream( false, target ) ); +public final class ConsoleOutputCapture { + public static void startCapture(TestOutputReceiver target) { + setOut(new ForwardingPrintStream(true, target)); + setErr(new ForwardingPrintStream(false, target)); } - private static final class ForwardingPrintStream - extends PrintStream - { + private static final class ForwardingPrintStream extends PrintStream { private final boolean isStdout; private final TestOutputReceiver target; - ForwardingPrintStream( boolean stdout, TestOutputReceiver target ) - { - super( new NullOutputStream() ); + ForwardingPrintStream(boolean stdout, TestOutputReceiver target) { + super(new NullOutputStream()); isStdout = stdout; this.target = target; } @Override - public void write( @Nonnull byte[] buf, int off, int len ) - { - String log = new String( buf, off, len ); - target.writeTestOutput( isStdout ? stdOut( log ) : stdErr( log ) ); + public void write(@Nonnull byte[] buf, int off, int len) { + String log = new String(buf, off, len); + target.writeTestOutput(isStdout ? stdOut(log) : stdErr(log)); } - public void write( @Nonnull byte[] b ) - throws IOException - { - write( b, 0, b.length ); + public void write(@Nonnull byte[] b) throws IOException { + write(b, 0, b.length); } @Override - public void write( int b ) - { - try - { - write( new byte[] { (byte) b } ); - } - catch ( IOException e ) - { + public void write(int b) { + try { + write(new byte[] {(byte) b}); + } catch (IOException e) { setError(); } } @Override - public void println( boolean x ) - { - println( x ? "true" : "false" ); + public void println(boolean x) { + println(x ? "true" : "false"); } @Override - public void println( char x ) - { - println( String.valueOf( x ) ); + public void println(char x) { + println(String.valueOf(x)); } @Override - public void println( int x ) - { - println( String.valueOf( x ) ); + public void println(int x) { + println(String.valueOf(x)); } @Override - public void println( long x ) - { - println( String.valueOf( x ) ); + public void println(long x) { + println(String.valueOf(x)); } @Override - public void println( float x ) - { - println( String.valueOf( x ) ); + public void println(float x) { + println(String.valueOf(x)); } @Override - public void println( double x ) - { - println( String.valueOf( x ) ); + public void println(double x) { + println(String.valueOf(x)); } @Override - public void println( @Nonnull char[] x ) - { - println( String.valueOf( x ) ); + public void println(@Nonnull char[] x) { + println(String.valueOf(x)); } @Override - public void println( Object x ) - { - println( String.valueOf( x ) ); + public void println(Object x) { + println(String.valueOf(x)); } @Override - public void println( String s ) - { + public void println(String s) { String log = s == null ? "null" : s; - target.writeTestOutput( isStdout ? stdOutln( log ) : stdErrln( log ) ); + target.writeTestOutput(isStdout ? stdOutln(log) : stdErrln(log)); } @Override - public void println() - { - target.writeTestOutput( isStdout ? stdOutln( "" ) : stdErrln( "" ) ); + public void println() { + target.writeTestOutput(isStdout ? stdOutln("") : stdErrln("")); } @Override - public void print( boolean x ) - { - print( x ? "true" : "false" ); + public void print(boolean x) { + print(x ? "true" : "false"); } @Override - public void print( char x ) - { - print( String.valueOf( x ) ); + public void print(char x) { + print(String.valueOf(x)); } @Override - public void print( int x ) - { - print( String.valueOf( x ) ); + public void print(int x) { + print(String.valueOf(x)); } @Override - public void print( long x ) - { - print( String.valueOf( x ) ); + public void print(long x) { + print(String.valueOf(x)); } @Override - public void print( float x ) - { - print( String.valueOf( x ) ); + public void print(float x) { + print(String.valueOf(x)); } @Override - public void print( double x ) - { - print( String.valueOf( x ) ); + public void print(double x) { + print(String.valueOf(x)); } @Override - public void print( @Nonnull char[] x ) - { - print( String.valueOf( x ) ); + public void print(@Nonnull char[] x) { + print(String.valueOf(x)); } @Override - public void print( Object x ) - { - print( String.valueOf( x ) ); + public void print(Object x) { + print(String.valueOf(x)); } @Override - public void print( String s ) - { + public void print(String s) { String log = s == null ? "null" : s; - target.writeTestOutput( isStdout ? stdOut( log ) : stdErr( log ) ); + target.writeTestOutput(isStdout ? stdOut(log) : stdErr(log)); } @Override - public PrintStream append( CharSequence csq ) - { - print( csq == null ? "null" : csq.toString() ); + public PrintStream append(CharSequence csq) { + print(csq == null ? "null" : csq.toString()); return this; } @Override - public PrintStream append( CharSequence csq, int start, int end ) - { + public PrintStream append(CharSequence csq, int start, int end) { CharSequence s = csq == null ? "null" : csq; - print( s.subSequence( start, end ).toString() ); + print(s.subSequence(start, end).toString()); return this; } @Override - public PrintStream append( char c ) - { - print( c ); + public PrintStream append(char c) { + print(c); return this; } @Override - public void close() - { - } + public void close() {} @Override - public void flush() - { - } + public void flush() {} } - private static final class NullOutputStream - extends OutputStream - { + private static final class NullOutputStream extends OutputStream { @Override - public void write( int b ) - { - } + public void write(int b) {} } } diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/api/report/ConsoleOutputReceiverForCurrentThread.java b/surefire-api/src/main/java/org/apache/maven/surefire/api/report/ConsoleOutputReceiverForCurrentThread.java index 0874b2b9f8..c71b0cae13 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/api/report/ConsoleOutputReceiverForCurrentThread.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/api/report/ConsoleOutputReceiverForCurrentThread.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.api.report; /* @@ -22,29 +40,20 @@ /** * @author Kristian Rosenvold */ -public final class ConsoleOutputReceiverForCurrentThread -{ - private static final ThreadLocal CURRENT - = new InheritableThreadLocal<>(); +public final class ConsoleOutputReceiverForCurrentThread { + private static final ThreadLocal CURRENT = new InheritableThreadLocal<>(); - private ConsoleOutputReceiverForCurrentThread() - { - } + private ConsoleOutputReceiverForCurrentThread() {} - public static TestOutputReceiver get() - { + public static TestOutputReceiver get() { return CURRENT.get(); } - public static void set( TestOutputReceiver testOutputReceiver ) - { - CURRENT.set( testOutputReceiver ); + public static void set(TestOutputReceiver testOutputReceiver) { + CURRENT.set(testOutputReceiver); } - public static void remove() - { + public static void remove() { CURRENT.remove(); } - } - diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/api/report/LegacyPojoStackTraceWriter.java b/surefire-api/src/main/java/org/apache/maven/surefire/api/report/LegacyPojoStackTraceWriter.java index ffb09c7fa8..21466f41b4 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/api/report/LegacyPojoStackTraceWriter.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/api/report/LegacyPojoStackTraceWriter.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.api.report; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,53 +16,46 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.api.report; +import java.io.PrintWriter; +import java.io.StringWriter; import org.apache.maven.surefire.api.util.internal.StringUtils; -import static org.apache.maven.surefire.shared.utils.StringUtils.isNotEmpty; -import java.io.PrintWriter; -import java.io.StringWriter; +import static org.apache.maven.surefire.shared.utils.StringUtils.isNotEmpty; /** * Write the trace out for a POJO test. Java 1.5 compatible. * * @author Brett Porter */ -public class LegacyPojoStackTraceWriter - implements StackTraceWriter -{ +public class LegacyPojoStackTraceWriter implements StackTraceWriter { private final Throwable t; private final String testClass; private final String testMethod; - public LegacyPojoStackTraceWriter( String testClass, String testMethod, Throwable t ) - { + public LegacyPojoStackTraceWriter(String testClass, String testMethod, Throwable t) { this.testClass = testClass; this.testMethod = testMethod; this.t = t; } @Override - public String writeTraceToString() - { - if ( t != null ) - { + public String writeTraceToString() { + if (t != null) { StringWriter w = new StringWriter(); - try ( PrintWriter stackTrace = new PrintWriter( w ) ) - { - t.printStackTrace( stackTrace ); + try (PrintWriter stackTrace = new PrintWriter(w)) { + t.printStackTrace(stackTrace); } StringBuffer builder = w.getBuffer(); - if ( isMultiLineExceptionMessage( t ) ) - { + if (isMultiLineExceptionMessage(t)) { // SUREFIRE-986 String exc = t.getClass().getName() + ": "; - if ( StringUtils.startsWith( builder, exc ) ) - { - builder.insert( exc.length(), '\n' ); + if (StringUtils.startsWith(builder, exc)) { + builder.insert(exc.length(), '\n'); } } return builder.toString(); @@ -73,98 +64,78 @@ public String writeTraceToString() } @Override - public String smartTrimmedStackTrace() - { + public String smartTrimmedStackTrace() { StringBuilder result = new StringBuilder(); - result.append( testClass ); - result.append( "#" ); - result.append( testMethod ); + result.append(testClass); + result.append("#"); + result.append(testMethod); SafeThrowable throwable = getThrowable(); Throwable target = throwable.getTarget(); - if ( target != null ) - { - if ( ! ( target instanceof AssertionError ) ) - { - result.append( ' ' ) - .append( target.getClass().getSimpleName() ); + if (target != null) { + if (!(target instanceof AssertionError)) { + result.append(' ').append(target.getClass().getSimpleName()); } final String msg = throwable.getMessage(); - if ( isNotEmpty( msg ) ) - { - result.append( ' ' ) - .append( msg ); + if (isNotEmpty(msg)) { + result.append(' ').append(msg); } } return result.toString(); } - private static boolean isMultiLineExceptionMessage( Throwable t ) - { + private static boolean isMultiLineExceptionMessage(Throwable t) { String msg = t.getLocalizedMessage(); - if ( msg != null ) - { + if (msg != null) { int countNewLines = 0; - for ( int i = 0, length = msg.length(); i < length; i++ ) - { - if ( msg.charAt( i ) == '\n' ) - { - if ( ++countNewLines == 2 ) - { + for (int i = 0, length = msg.length(); i < length; i++) { + if (msg.charAt(i) == '\n') { + if (++countNewLines == 2) { break; } } } - return countNewLines > 1 || countNewLines == 1 && !msg.trim().endsWith( "\n" ); + return countNewLines > 1 || countNewLines == 1 && !msg.trim().endsWith("\n"); } return false; } @Override - public String writeTrimmedTraceToString() - { + public String writeTrimmedTraceToString() { String text = writeTraceToString(); String marker = "at " + testClass + "." + testMethod; - String[] lines = StringUtils.split( text, "\n" ); + String[] lines = StringUtils.split(text, "\n"); int lastLine = lines.length - 1; int causedByLine = -1; // skip first - for ( int i = 1; i < lines.length; i++ ) - { + for (int i = 1; i < lines.length; i++) { String line = lines[i].trim(); - if ( line.startsWith( marker ) ) - { + if (line.startsWith(marker)) { lastLine = i; - } - else if ( line.startsWith( "Caused by" ) ) - { + } else if (line.startsWith("Caused by")) { causedByLine = i; break; } } StringBuilder trace = new StringBuilder(); - for ( int i = 0; i <= lastLine; i++ ) - { - trace.append( lines[i] ); - trace.append( "\n" ); + for (int i = 0; i <= lastLine; i++) { + trace.append(lines[i]); + trace.append("\n"); } - if ( causedByLine != -1 ) - { - for ( int i = causedByLine; i < lines.length; i++ ) - { - trace.append( lines[i] ); - trace.append( "\n" ); + if (causedByLine != -1) { + for (int i = causedByLine; i < lines.length; i++) { + trace.append(lines[i]); + trace.append("\n"); } } return trace.toString(); } @Override - public SafeThrowable getThrowable() - { - return new SafeThrowable( t ); + public SafeThrowable getThrowable() { + return new SafeThrowable(t); } } diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/api/report/OutputReportEntry.java b/surefire-api/src/main/java/org/apache/maven/surefire/api/report/OutputReportEntry.java index 5dabbc7d35..e238bdaea7 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/api/report/OutputReportEntry.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/api/report/OutputReportEntry.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.api.report; /* @@ -35,8 +53,7 @@ * The second situation happens when ForkingRunListener and TestSetRunListener handles * {@link TestOutputReportEntry} which contains {@link RunMode} and testRunId. */ -public interface OutputReportEntry -{ +public interface OutputReportEntry { String getLog(); boolean isStdOut(); diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/api/report/ReportEntry.java b/surefire-api/src/main/java/org/apache/maven/surefire/api/report/ReportEntry.java index 4d08ad1b8d..f2c33aa51a 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/api/report/ReportEntry.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/api/report/ReportEntry.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.api.report; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.api.report; import javax.annotation.Nonnull; @@ -25,8 +24,7 @@ * Describes a single entry for a test report * */ -public interface ReportEntry -{ +public interface ReportEntry { /** * The class name of the test * @@ -84,8 +82,7 @@ public interface ReportEntry * @param fallback usually 0 * @return elapsed time if {@link #getElapsed()} is not null; otherwise returns {@code fallback} */ - int getElapsed( int fallback ); - + int getElapsed(int fallback); /** * A message relating to a non-successful termination. diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/api/report/ReporterConfiguration.java b/surefire-api/src/main/java/org/apache/maven/surefire/api/report/ReporterConfiguration.java index 324ebbcf5b..532d18f456 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/api/report/ReporterConfiguration.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/api/report/ReporterConfiguration.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.api.report; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.api.report; import java.io.File; @@ -28,13 +27,11 @@ * * @author Kristian Rosenvold */ -public class ReporterConfiguration -{ +public class ReporterConfiguration { private final File reportsDirectory; private final boolean trimStackTrace; - public ReporterConfiguration( File reportsDirectory, boolean trimStackTrace ) - { + public ReporterConfiguration(File reportsDirectory, boolean trimStackTrace) { this.reportsDirectory = reportsDirectory; this.trimStackTrace = trimStackTrace; } @@ -44,8 +41,7 @@ public ReporterConfiguration( File reportsDirectory, boolean trimStackTrace ) * * @return A file pointing at the specified directory */ - public File getReportsDirectory() - { + public File getReportsDirectory() { return reportsDirectory; } @@ -54,8 +50,7 @@ public File getReportsDirectory() * * @return true if stacktraces should be trimmed in reporting */ - public boolean isTrimStackTrace() - { + public boolean isTrimStackTrace() { return trimStackTrace; } } diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/api/report/ReporterException.java b/surefire-api/src/main/java/org/apache/maven/surefire/api/report/ReporterException.java index ef9df1187c..246e573ca7 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/api/report/ReporterException.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/api/report/ReporterException.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.api.report; /* @@ -19,17 +37,13 @@ * under the License. */ - /** * Exception occurring during report generation. * * @author Brett Porter */ -public class ReporterException - extends RuntimeException -{ - public ReporterException( String message, Exception nested ) - { - super( message, nested ); +public class ReporterException extends RuntimeException { + public ReporterException(String message, Exception nested) { + super(message, nested); } } diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/api/report/ReporterFactory.java b/surefire-api/src/main/java/org/apache/maven/surefire/api/report/ReporterFactory.java index 52a434c648..80dde24f0c 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/api/report/ReporterFactory.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/api/report/ReporterFactory.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.api.report; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.api.report; import org.apache.maven.surefire.api.suite.RunResult; @@ -26,8 +25,7 @@ * * @author Kristian Rosenvold */ -public interface ReporterFactory -{ +public interface ReporterFactory { /** * Creates a reporter listener. * @@ -41,5 +39,4 @@ public interface ReporterFactory * @return The run result */ RunResult close(); - } diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/api/report/RunListener.java b/surefire-api/src/main/java/org/apache/maven/surefire/api/report/RunListener.java index acb8e43f38..799891cbff 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/api/report/RunListener.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/api/report/RunListener.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.api.report; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.api.report; import org.apache.maven.surefire.api.provider.SurefireProvider; @@ -28,15 +27,14 @@ * An instance of a reporter is not guaranteed to be thread-safe and concurrent test frameworks * must request an instance of a reporter per-thread from the ReporterFactory. */ -public interface RunListener -{ +public interface RunListener { /** * Indicates the start of a given test-set * * @param report the report entry describing the testset * @throws ReporterException When reporting fails */ - void testSetStarting( TestSetReportEntry report ); + void testSetStarting(TestSetReportEntry report); /** * Indicates end of a given test-set @@ -44,21 +42,21 @@ public interface RunListener * @param report the report entry describing the testset * @throws ReporterException When reporting fails */ - void testSetCompleted( TestSetReportEntry report ); + void testSetCompleted(TestSetReportEntry report); /** * Event fired when a test is about to start * * @param report The report entry to log for */ - void testStarting( ReportEntry report ); + void testStarting(ReportEntry report); /** * Event fired when a test ended successfully * * @param report The report entry to log for */ - void testSucceeded( ReportEntry report ); + void testSucceeded(ReportEntry report); /** * Event fired when a test assumption failure was encountered. @@ -66,28 +64,28 @@ public interface RunListener * * @param report The report entry to log for */ - void testAssumptionFailure( ReportEntry report ); + void testAssumptionFailure(ReportEntry report); /** * Event fired when a test ended with an error (non anticipated problem) * * @param report The report entry to log for */ - void testError( ReportEntry report ); + void testError(ReportEntry report); /** * Event fired when a test ended with a failure (anticipated problem) * * @param report The report entry to log for */ - void testFailed( ReportEntry report ); + void testFailed(ReportEntry report); /** * Event fired when a test is skipped * * @param report The report entry to log for */ - void testSkipped( ReportEntry report ); + void testSkipped(ReportEntry report); /** * Event fired skipping an execution of remaining test-set in other fork(s); or does nothing if no forks. diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/api/report/RunMode.java b/surefire-api/src/main/java/org/apache/maven/surefire/api/report/RunMode.java index a1d1977250..d2d2444d83 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/api/report/RunMode.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/api/report/RunMode.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.api.report; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.api.report; import static java.nio.charset.StandardCharsets.US_ASCII; @@ -29,28 +28,24 @@ * @author Tibor Digana (tibor17) * @since 3.0.0-M4 */ -public enum RunMode -{ - NORMAL_RUN( "normal-run" ), - RERUN_TEST_AFTER_FAILURE( "rerun-test-after-failure" ); - //todo add here RERUN_TESTSET, see https://github.com/apache/maven-surefire/pull/221 +public enum RunMode { + NORMAL_RUN("normal-run"), + RERUN_TEST_AFTER_FAILURE("rerun-test-after-failure"); + // todo add here RERUN_TESTSET, see https://github.com/apache/maven-surefire/pull/221 private final String runmode; private final byte[] runmodeBinary; - RunMode( String runmode ) - { + RunMode(String runmode) { this.runmode = runmode; - runmodeBinary = runmode.getBytes( US_ASCII ); + runmodeBinary = runmode.getBytes(US_ASCII); } - public String getRunmode() - { + public String getRunmode() { return runmode; } - public byte[] getRunmodeBinary() - { + public byte[] getRunmodeBinary() { return runmodeBinary; } } diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/api/report/SafeThrowable.java b/surefire-api/src/main/java/org/apache/maven/surefire/api/report/SafeThrowable.java index 9378736b3c..04b89c941d 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/api/report/SafeThrowable.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/api/report/SafeThrowable.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.api.report; /* @@ -22,46 +40,34 @@ /** * Guards against misbehaving throwables */ -public class SafeThrowable -{ +public class SafeThrowable { private final Throwable target; - public SafeThrowable( Throwable target ) - { + public SafeThrowable(Throwable target) { this.target = target; } - public SafeThrowable( String message ) - { - this( new Throwable( message ) ); + public SafeThrowable(String message) { + this(new Throwable(message)); } - public String getLocalizedMessage() - { - try - { + public String getLocalizedMessage() { + try { return target.getLocalizedMessage(); - } - catch ( Throwable t ) - { + } catch (Throwable t) { return t.getLocalizedMessage(); } } - public String getMessage() - { - try - { + public String getMessage() { + try { return target.getMessage(); - } - catch ( Throwable t ) - { + } catch (Throwable t) { return t.getMessage(); } } - public Throwable getTarget() - { + public Throwable getTarget() { return target; } } diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/api/report/SimpleReportEntry.java b/surefire-api/src/main/java/org/apache/maven/surefire/api/report/SimpleReportEntry.java index 8862effc7e..729ee9feb4 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/api/report/SimpleReportEntry.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/api/report/SimpleReportEntry.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.api.report; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,22 +16,22 @@ * specific language governing permissions and limitations * under the License. */ - -import org.apache.maven.surefire.api.util.internal.ImmutableMap; +package org.apache.maven.surefire.api.report; import javax.annotation.Nonnull; + import java.util.Collections; import java.util.Map; import java.util.Objects; +import org.apache.maven.surefire.api.util.internal.ImmutableMap; + /** * Basic implementation of {@link TestSetReportEntry} (immutable and thread-safe object). * * @author Kristian Rosenvold */ -public class SimpleReportEntry - implements TestSetReportEntry -{ +public class SimpleReportEntry implements TestSetReportEntry { private final RunMode runMode; private final Long testRunId; @@ -54,44 +52,76 @@ public class SimpleReportEntry private final String message; - public SimpleReportEntry( @Nonnull RunMode runMode, Long testRunId, - String source, String sourceText, String name, String nameText ) - { - this( runMode, testRunId, source, sourceText, name, nameText, null, null ); - } - - public SimpleReportEntry( @Nonnull RunMode runMode, Long testRunId, - String source, String sourceText, String name, String nameText, - Map systemProperties ) - { - this( runMode, testRunId, source, sourceText, name, nameText, null, null, systemProperties ); - } - - private SimpleReportEntry( @Nonnull RunMode runMode, Long testRunId, - String source, String sourceText, String name, String nameText, - StackTraceWriter stackTraceWriter ) - { - this( runMode, testRunId, source, sourceText, name, nameText, stackTraceWriter, null ); - } - - public SimpleReportEntry( @Nonnull RunMode runMode, Long testRunId, - String source, String sourceText, String name, String nameText, Integer elapsed ) - { - this( runMode, testRunId, source, sourceText, name, nameText, null, elapsed ); - } - - public SimpleReportEntry( @Nonnull RunMode runMode, Long testRunId, - String source, String sourceText, String name, String nameText, String message ) - { - this( runMode, testRunId, - source, sourceText, name, nameText, null, null, message, Collections.emptyMap() ); - } - - public SimpleReportEntry( @Nonnull RunMode runMode, Long testRunId, - String source, String sourceText, String name, String nameText, - StackTraceWriter stackTraceWriter, Integer elapsed, String message, - Map systemProperties ) - { + public SimpleReportEntry( + @Nonnull RunMode runMode, Long testRunId, String source, String sourceText, String name, String nameText) { + this(runMode, testRunId, source, sourceText, name, nameText, null, null); + } + + public SimpleReportEntry( + @Nonnull RunMode runMode, + Long testRunId, + String source, + String sourceText, + String name, + String nameText, + Map systemProperties) { + this(runMode, testRunId, source, sourceText, name, nameText, null, null, systemProperties); + } + + private SimpleReportEntry( + @Nonnull RunMode runMode, + Long testRunId, + String source, + String sourceText, + String name, + String nameText, + StackTraceWriter stackTraceWriter) { + this(runMode, testRunId, source, sourceText, name, nameText, stackTraceWriter, null); + } + + public SimpleReportEntry( + @Nonnull RunMode runMode, + Long testRunId, + String source, + String sourceText, + String name, + String nameText, + Integer elapsed) { + this(runMode, testRunId, source, sourceText, name, nameText, null, elapsed); + } + + public SimpleReportEntry( + @Nonnull RunMode runMode, + Long testRunId, + String source, + String sourceText, + String name, + String nameText, + String message) { + this( + runMode, + testRunId, + source, + sourceText, + name, + nameText, + null, + null, + message, + Collections.emptyMap()); + } + + public SimpleReportEntry( + @Nonnull RunMode runMode, + Long testRunId, + String source, + String sourceText, + String name, + String nameText, + StackTraceWriter stackTraceWriter, + Integer elapsed, + String message, + Map systemProperties) { this.runMode = runMode; this.testRunId = testRunId; this.source = source; @@ -101,236 +131,248 @@ public SimpleReportEntry( @Nonnull RunMode runMode, Long testRunId, this.stackTraceWriter = stackTraceWriter; this.message = message; this.elapsed = elapsed; - this.systemProperties = new ImmutableMap<>( systemProperties ); - } - - public SimpleReportEntry( @Nonnull RunMode runMode, Long testRunId, - String source, String sourceText, String name, String nameText, - StackTraceWriter stackTraceWriter, Integer elapsed ) - { - this( runMode, testRunId, - source, sourceText, name, nameText, stackTraceWriter, elapsed, Collections.emptyMap() ); - } - - public SimpleReportEntry( @Nonnull RunMode runMode, Long testRunId, - String source, String sourceText, String name, String nameText, - StackTraceWriter stackTraceWriter, Integer elapsed, Map systemProperties ) - { - this( runMode, testRunId, source, sourceText, name, nameText, - stackTraceWriter, elapsed, safeGetMessage( stackTraceWriter ), systemProperties ); - } - - public static SimpleReportEntry assumption( RunMode runMode, Long testRunId, String source, - String sourceText, String name, String nameText, String message ) - { - return new SimpleReportEntry( runMode, testRunId, source, sourceText, name, nameText, message ); - } - - public static SimpleReportEntry ignored( RunMode runMode, Long testRunId, String source, - String sourceText, String name, String nameText, String message ) - { - return new SimpleReportEntry( runMode, testRunId, source, sourceText, name, nameText, message ); - } - - public static SimpleReportEntry withException( RunMode runMode, Long testRunId, String source, - String sourceText, String name, String nameText, - StackTraceWriter stackTraceWriter ) - { - return new SimpleReportEntry( runMode, testRunId, source, sourceText, name, nameText, stackTraceWriter ); - } - - private static String safeGetMessage( StackTraceWriter stackTraceWriter ) - { - try - { + this.systemProperties = new ImmutableMap<>(systemProperties); + } + + public SimpleReportEntry( + @Nonnull RunMode runMode, + Long testRunId, + String source, + String sourceText, + String name, + String nameText, + StackTraceWriter stackTraceWriter, + Integer elapsed) { + this( + runMode, + testRunId, + source, + sourceText, + name, + nameText, + stackTraceWriter, + elapsed, + Collections.emptyMap()); + } + + public SimpleReportEntry( + @Nonnull RunMode runMode, + Long testRunId, + String source, + String sourceText, + String name, + String nameText, + StackTraceWriter stackTraceWriter, + Integer elapsed, + Map systemProperties) { + this( + runMode, + testRunId, + source, + sourceText, + name, + nameText, + stackTraceWriter, + elapsed, + safeGetMessage(stackTraceWriter), + systemProperties); + } + + public static SimpleReportEntry assumption( + RunMode runMode, + Long testRunId, + String source, + String sourceText, + String name, + String nameText, + String message) { + return new SimpleReportEntry(runMode, testRunId, source, sourceText, name, nameText, message); + } + + public static SimpleReportEntry ignored( + RunMode runMode, + Long testRunId, + String source, + String sourceText, + String name, + String nameText, + String message) { + return new SimpleReportEntry(runMode, testRunId, source, sourceText, name, nameText, message); + } + + public static SimpleReportEntry withException( + RunMode runMode, + Long testRunId, + String source, + String sourceText, + String name, + String nameText, + StackTraceWriter stackTraceWriter) { + return new SimpleReportEntry(runMode, testRunId, source, sourceText, name, nameText, stackTraceWriter); + } + + private static String safeGetMessage(StackTraceWriter stackTraceWriter) { + try { SafeThrowable t = stackTraceWriter == null ? null : stackTraceWriter.getThrowable(); return t == null ? null : t.getMessage(); - } - catch ( Throwable t ) - { + } catch (Throwable t) { return t.getMessage(); } } @Override - public String getSourceName() - { + public String getSourceName() { return source; } @Override - public String getSourceText() - { + public String getSourceText() { return sourceText; } @Override - public String getName() - { + public String getName() { return name; } @Override - public String getNameText() - { + public String getNameText() { return nameText; } @Override - public String getGroup() - { + public String getGroup() { return null; } @Override - public StackTraceWriter getStackTraceWriter() - { + public StackTraceWriter getStackTraceWriter() { return stackTraceWriter; } @Override - public Integer getElapsed() - { + public Integer getElapsed() { return elapsed; } @Override - public int getElapsed( int fallback ) - { + public int getElapsed(int fallback) { return elapsed == null ? fallback : elapsed; } @Override - public String toString() - { + public String toString() { return "ReportEntry{" + "runMode='" + runMode + "', testRunId='" + testRunId - + "', source='" + source + "', sourceText='" + sourceText - + "', name='" + name + "', nameText='" + nameText + "', stackTraceWriter='" + stackTraceWriter - + "', elapsed='" + elapsed + "', message='" + message + "'}"; + + "', source='" + source + "', sourceText='" + sourceText + + "', name='" + name + "', nameText='" + nameText + "', stackTraceWriter='" + stackTraceWriter + + "', elapsed='" + elapsed + "', message='" + message + "'}"; } @Override - public String getMessage() - { + public String getMessage() { return message; } @Override - public boolean equals( Object o ) - { - if ( this == o ) - { + public boolean equals(Object o) { + if (this == o) { return true; } - if ( o == null || getClass() != o.getClass() ) - { + if (o == null || getClass() != o.getClass()) { return false; } SimpleReportEntry that = (SimpleReportEntry) o; - return isRunModeEqual( that ) && isTestRunIdEqual( that ) - && isSourceEqual( that ) && isSourceTextEqual( that ) - && isNameEqual( that ) && isNameTextEqual( that ) - && isStackEqual( that ) - && isElapsedTimeEqual( that ) - && isSystemPropertiesEqual( that ) - && isMessageEqual( that ); + return isRunModeEqual(that) + && isTestRunIdEqual(that) + && isSourceEqual(that) + && isSourceTextEqual(that) + && isNameEqual(that) + && isNameTextEqual(that) + && isStackEqual(that) + && isElapsedTimeEqual(that) + && isSystemPropertiesEqual(that) + && isMessageEqual(that); } @Override - public int hashCode() - { - int result = Objects.hashCode( getSourceName() ); - result = 31 * result + Objects.hashCode( getRunMode() ); - result = 31 * result + Objects.hashCode( getTestRunId() ); - result = 31 * result + Objects.hashCode( getSourceText() ); - result = 31 * result + Objects.hashCode( getName() ); - result = 31 * result + Objects.hashCode( getNameText() ); - result = 31 * result + Objects.hashCode( getStackTraceWriter() ); - result = 31 * result + Objects.hashCode( getElapsed() ); - result = 31 * result + Objects.hashCode( getSystemProperties() ); - result = 31 * result + Objects.hashCode( getMessage() ); + public int hashCode() { + int result = Objects.hashCode(getSourceName()); + result = 31 * result + Objects.hashCode(getRunMode()); + result = 31 * result + Objects.hashCode(getTestRunId()); + result = 31 * result + Objects.hashCode(getSourceText()); + result = 31 * result + Objects.hashCode(getName()); + result = 31 * result + Objects.hashCode(getNameText()); + result = 31 * result + Objects.hashCode(getStackTraceWriter()); + result = 31 * result + Objects.hashCode(getElapsed()); + result = 31 * result + Objects.hashCode(getSystemProperties()); + result = 31 * result + Objects.hashCode(getMessage()); return result; } @Override - public String getNameWithGroup() - { + public String getNameWithGroup() { return getSourceName(); } @Override - public String getReportNameWithGroup() - { + public String getReportNameWithGroup() { return getSourceText(); } @Override @Nonnull - public final RunMode getRunMode() - { + public final RunMode getRunMode() { return runMode; } @Override - public final Long getTestRunId() - { + public final Long getTestRunId() { return testRunId; } @Override - public Map getSystemProperties() - { + public Map getSystemProperties() { return systemProperties; } - private boolean isRunModeEqual( SimpleReportEntry en ) - { - return Objects.equals( getRunMode(), en.getRunMode() ); + private boolean isRunModeEqual(SimpleReportEntry en) { + return Objects.equals(getRunMode(), en.getRunMode()); } - private boolean isTestRunIdEqual( SimpleReportEntry en ) - { - return Objects.equals( getTestRunId(), en.getTestRunId() ); + private boolean isTestRunIdEqual(SimpleReportEntry en) { + return Objects.equals(getTestRunId(), en.getTestRunId()); } - private boolean isElapsedTimeEqual( SimpleReportEntry en ) - { - return Objects.equals( getElapsed(), en.getElapsed() ); + private boolean isElapsedTimeEqual(SimpleReportEntry en) { + return Objects.equals(getElapsed(), en.getElapsed()); } - private boolean isNameTextEqual( SimpleReportEntry en ) - { - return Objects.equals( getNameText(), en.getNameText() ); + private boolean isNameTextEqual(SimpleReportEntry en) { + return Objects.equals(getNameText(), en.getNameText()); } - private boolean isNameEqual( SimpleReportEntry en ) - { - return Objects.equals( getName(), en.getName() ); + private boolean isNameEqual(SimpleReportEntry en) { + return Objects.equals(getName(), en.getName()); } - private boolean isSourceEqual( SimpleReportEntry en ) - { - return Objects.equals( getSourceName(), en.getSourceName() ); + private boolean isSourceEqual(SimpleReportEntry en) { + return Objects.equals(getSourceName(), en.getSourceName()); } - private boolean isSourceTextEqual( SimpleReportEntry en ) - { - return Objects.equals( getSourceText(), en.getSourceText() ); + private boolean isSourceTextEqual(SimpleReportEntry en) { + return Objects.equals(getSourceText(), en.getSourceText()); } - private boolean isStackEqual( SimpleReportEntry en ) - { - return Objects.equals( getStackTraceWriter(), en.getStackTraceWriter() ); + private boolean isStackEqual(SimpleReportEntry en) { + return Objects.equals(getStackTraceWriter(), en.getStackTraceWriter()); } - private boolean isSystemPropertiesEqual( SimpleReportEntry en ) - { - return Objects.equals( getSystemProperties(), en.getSystemProperties() ); + private boolean isSystemPropertiesEqual(SimpleReportEntry en) { + return Objects.equals(getSystemProperties(), en.getSystemProperties()); } - private boolean isMessageEqual( SimpleReportEntry en ) - { - return Objects.equals( getMessage(), en.getMessage() ); + private boolean isMessageEqual(SimpleReportEntry en) { + return Objects.equals(getMessage(), en.getMessage()); } } diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/api/report/StackTraceWriter.java b/surefire-api/src/main/java/org/apache/maven/surefire/api/report/StackTraceWriter.java index bf28afaeb3..3681db4f6b 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/api/report/StackTraceWriter.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/api/report/StackTraceWriter.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.api.report; /* @@ -24,8 +42,7 @@ * * @author Brett Porter */ -public interface StackTraceWriter -{ +public interface StackTraceWriter { /** * Write the throwable to a string, without trimming. * diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/api/report/TestOutputReceiver.java b/surefire-api/src/main/java/org/apache/maven/surefire/api/report/TestOutputReceiver.java index 4f3d0c560a..ab7957516f 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/api/report/TestOutputReceiver.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/api/report/TestOutputReceiver.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.api.report; /* @@ -25,14 +43,12 @@ * * @param usually {@link TestOutputReportEntry} or {@link OutputReportEntry} */ -public interface TestOutputReceiver -{ +public interface TestOutputReceiver { /** * Forwards process output from the running test-case into the reporting system * * @param reportEntry wraps test output with descriptive information of the output */ - void writeTestOutput( T reportEntry ); - + void writeTestOutput(T reportEntry); } diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/api/report/TestOutputReportEntry.java b/surefire-api/src/main/java/org/apache/maven/surefire/api/report/TestOutputReportEntry.java index 3610f85c21..cf575274dd 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/api/report/TestOutputReportEntry.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/api/report/TestOutputReportEntry.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.api.report; /* @@ -24,8 +42,7 @@ * * {@inheritDoc} */ -public final class TestOutputReportEntry implements OutputReportEntry -{ +public final class TestOutputReportEntry implements OutputReportEntry { private final String log; private final boolean isStdOut; private final boolean newLine; @@ -41,8 +58,7 @@ public final class TestOutputReportEntry implements OutputReportEntry * @param runMode the phase of testset * @param testRunId unique id of the test run pointing to the test description */ - public TestOutputReportEntry( String log, boolean isStdOut, boolean newLine, RunMode runMode, Long testRunId ) - { + public TestOutputReportEntry(String log, boolean isStdOut, boolean newLine, RunMode runMode, Long testRunId) { this.log = log; this.isStdOut = isStdOut; this.newLine = newLine; @@ -57,13 +73,11 @@ public TestOutputReportEntry( String log, boolean isStdOut, boolean newLine, Run * @param isStdOut Indicates if this is stdout * @param newLine print on new line */ - private TestOutputReportEntry( String log, boolean isStdOut, boolean newLine ) - { - this( log, isStdOut, newLine, null, null ); + private TestOutputReportEntry(String log, boolean isStdOut, boolean newLine) { + this(log, isStdOut, newLine, null, null); } - public TestOutputReportEntry( OutputReportEntry reportEntry, RunMode runMode, Long testRunId ) - { + public TestOutputReportEntry(OutputReportEntry reportEntry, RunMode runMode, Long testRunId) { log = reportEntry.getLog(); isStdOut = reportEntry.isStdOut(); newLine = reportEntry.isNewLine(); @@ -72,50 +86,41 @@ public TestOutputReportEntry( OutputReportEntry reportEntry, RunMode runMode, Lo } @Override - public String getLog() - { + public String getLog() { return log; } @Override - public boolean isStdOut() - { + public boolean isStdOut() { return isStdOut; } @Override - public boolean isNewLine() - { + public boolean isNewLine() { return newLine; } - public RunMode getRunMode() - { + public RunMode getRunMode() { return runMode; } - public Long getTestRunId() - { + public Long getTestRunId() { return testRunId; } - public static OutputReportEntry stdOut( String log ) - { - return new TestOutputReportEntry( log, true, false ); + public static OutputReportEntry stdOut(String log) { + return new TestOutputReportEntry(log, true, false); } - public static TestOutputReportEntry stdOutln( String log ) - { - return new TestOutputReportEntry( log, true, true ); + public static TestOutputReportEntry stdOutln(String log) { + return new TestOutputReportEntry(log, true, true); } - public static TestOutputReportEntry stdErr( String log ) - { - return new TestOutputReportEntry( log, false, false ); + public static TestOutputReportEntry stdErr(String log) { + return new TestOutputReportEntry(log, false, false); } - public static TestOutputReportEntry stdErrln( String log ) - { - return new TestOutputReportEntry( log, false, true ); + public static TestOutputReportEntry stdErrln(String log) { + return new TestOutputReportEntry(log, false, true); } } diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/api/report/TestReportListener.java b/surefire-api/src/main/java/org/apache/maven/surefire/api/report/TestReportListener.java index 120361e777..dbc6a03227 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/api/report/TestReportListener.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/api/report/TestReportListener.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.api.report; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.api.report; import org.apache.maven.plugin.surefire.log.api.ConsoleLogger; @@ -42,6 +41,4 @@ * @param usually {@link TestOutputReportEntry} or {@link OutputReportEntry} */ public interface TestReportListener - extends RunListener, TestOutputReceiver, ConsoleLogger -{ -} + extends RunListener, TestOutputReceiver, ConsoleLogger {} diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/api/report/TestSetReportEntry.java b/surefire-api/src/main/java/org/apache/maven/surefire/api/report/TestSetReportEntry.java index 0350ea9f5a..d18cf6ef8b 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/api/report/TestSetReportEntry.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/api/report/TestSetReportEntry.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.api.report; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.api.report; import java.util.Map; @@ -29,7 +28,6 @@ * @see RunListener#testSetCompleted(TestSetReportEntry) * @since 2.20.1 */ -public interface TestSetReportEntry extends ReportEntry -{ +public interface TestSetReportEntry extends ReportEntry { Map getSystemProperties(); } diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/api/runorder/PrioritizedTest.java b/surefire-api/src/main/java/org/apache/maven/surefire/api/runorder/PrioritizedTest.java index 1a740a65ac..2186f83ee7 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/api/runorder/PrioritizedTest.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/api/runorder/PrioritizedTest.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.api.runorder; /* @@ -22,31 +40,25 @@ /** * @author Kristian Rosenvold */ -public class PrioritizedTest -{ +public class PrioritizedTest { private final Class clazz; private final Priority priority; - public PrioritizedTest( Class clazz, Priority pri ) - { + public PrioritizedTest(Class clazz, Priority pri) { this.clazz = clazz; this.priority = pri; } - public int getPriority() - { + public int getPriority() { return priority.getPriority(); } - - public int getTotalRuntime() - { + public int getTotalRuntime() { return priority.getTotalRuntime(); } - public Class getClazz() - { + public Class getClazz() { return clazz; } } diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/api/runorder/Priority.java b/surefire-api/src/main/java/org/apache/maven/surefire/api/runorder/Priority.java index b18546787f..a3127d5a06 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/api/runorder/Priority.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/api/runorder/Priority.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.api.runorder; /* @@ -22,8 +40,7 @@ /** * @author Kristian Rosenvold */ -public class Priority -{ +public class Priority { private final String className; int priority; @@ -32,8 +49,7 @@ public class Priority int minSuccessRate = Integer.MAX_VALUE; - public Priority( String className ) - { + public Priority(String className) { this.className = className; } @@ -43,43 +59,35 @@ public Priority( String className ) * @param className The class name * @return A priority */ - public static Priority newTestClassPriority( String className ) - { - Priority priority1 = new Priority( className ); - priority1.setPriority( 0 ); + public static Priority newTestClassPriority(String className) { + Priority priority1 = new Priority(className); + priority1.setPriority(0); priority1.minSuccessRate = 0; return priority1; } - public void addItem( RunEntryStatistics itemStat ) - { + public void addItem(RunEntryStatistics itemStat) { totalRuntime += itemStat.getRunTime(); - minSuccessRate = Math.min( minSuccessRate, itemStat.getSuccessfulBuilds() ); + minSuccessRate = Math.min(minSuccessRate, itemStat.getSuccessfulBuilds()); } - - public int getTotalRuntime() - { + public int getTotalRuntime() { return totalRuntime; } - public int getMinSuccessRate() - { + public int getMinSuccessRate() { return minSuccessRate; } - public String getClassName() - { + public String getClassName() { return className; } - public int getPriority() - { + public int getPriority() { return priority; } - public void setPriority( int priority ) - { + public void setPriority(int priority) { this.priority = priority; } } diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/api/runorder/RunEntryStatistics.java b/surefire-api/src/main/java/org/apache/maven/surefire/api/runorder/RunEntryStatistics.java index 36044f542d..87db9205a5 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/api/runorder/RunEntryStatistics.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/api/runorder/RunEntryStatistics.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.api.runorder; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,54 +16,47 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.api.runorder; import org.apache.maven.surefire.api.util.internal.ClassMethod; /** * @author Kristian Rosenvold */ -public class RunEntryStatistics -{ +public class RunEntryStatistics { private final int runTime; private final int successfulBuilds; private final ClassMethod classMethod; - RunEntryStatistics( int runTime, int successfulBuilds, String clazz, String method ) - { - this( runTime, successfulBuilds, new ClassMethod( clazz, method ) ); + RunEntryStatistics(int runTime, int successfulBuilds, String clazz, String method) { + this(runTime, successfulBuilds, new ClassMethod(clazz, method)); } - public RunEntryStatistics( int runTime, int successfulBuilds, ClassMethod classMethod ) - { + public RunEntryStatistics(int runTime, int successfulBuilds, ClassMethod classMethod) { this.runTime = runTime; this.successfulBuilds = successfulBuilds; this.classMethod = classMethod; } - public ClassMethod getClassMethod() - { + public ClassMethod getClassMethod() { return classMethod; } - public RunEntryStatistics nextGeneration( int runTime ) - { - return new RunEntryStatistics( runTime, successfulBuilds + 1, classMethod ); + public RunEntryStatistics nextGeneration(int runTime) { + return new RunEntryStatistics(runTime, successfulBuilds + 1, classMethod); } - public RunEntryStatistics nextGenerationFailure( int runTime ) - { - return new RunEntryStatistics( runTime, 0, classMethod ); + public RunEntryStatistics nextGenerationFailure(int runTime) { + return new RunEntryStatistics(runTime, 0, classMethod); } - public int getRunTime() - { + public int getRunTime() { return runTime; } - public int getSuccessfulBuilds() - { + public int getSuccessfulBuilds() { return successfulBuilds; } } diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/api/runorder/RunEntryStatisticsMap.java b/surefire-api/src/main/java/org/apache/maven/surefire/api/runorder/RunEntryStatisticsMap.java index 8bf02686c4..1d904e61c6 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/api/runorder/RunEntryStatisticsMap.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/api/runorder/RunEntryStatisticsMap.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.api.runorder; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,9 +16,7 @@ * specific language governing permissions and limitations * under the License. */ - -import org.apache.maven.surefire.api.report.ReportEntry; -import org.apache.maven.surefire.api.util.internal.ClassMethod; +package org.apache.maven.surefire.api.runorder; import java.io.BufferedWriter; import java.io.File; @@ -40,6 +36,9 @@ import java.util.Scanner; import java.util.concurrent.ConcurrentHashMap; +import org.apache.maven.surefire.api.report.ReportEntry; +import org.apache.maven.surefire.api.util.internal.ClassMethod; + import static java.lang.Integer.parseInt; import static java.nio.charset.StandardCharsets.UTF_8; import static java.util.Collections.sort; @@ -48,279 +47,224 @@ /** * @author Kristian Rosenvold */ -public final class RunEntryStatisticsMap -{ +public final class RunEntryStatisticsMap { private final Map runEntryStatistics; - private RunEntryStatisticsMap( Map runEntryStatistics ) - { - this.runEntryStatistics = new ConcurrentHashMap<>( runEntryStatistics ); + private RunEntryStatisticsMap(Map runEntryStatistics) { + this.runEntryStatistics = new ConcurrentHashMap<>(runEntryStatistics); } - public RunEntryStatisticsMap() - { + public RunEntryStatisticsMap() { runEntryStatistics = new ConcurrentHashMap<>(); } - public static RunEntryStatisticsMap fromFile( File file ) - { - if ( file.exists() ) - { - try - { - return fromStream( new FileInputStream( file ) ); + public static RunEntryStatisticsMap fromFile(File file) { + if (file.exists()) { + try { + return fromStream(new FileInputStream(file)); + } catch (IOException e) { + throw new RuntimeException(e); } - catch ( IOException e ) - { - throw new RuntimeException( e ); - } - } - else - { + } else { return new RunEntryStatisticsMap(); } } - public static RunEntryStatisticsMap fromStream( InputStream fileReader ) - { + public static RunEntryStatisticsMap fromStream(InputStream fileReader) { Map result = new HashMap<>(); - try ( Scanner scanner = new Scanner( fileReader, "UTF-8" ) ) - { + try (Scanner scanner = new Scanner(fileReader, "UTF-8")) { RunEntryStatistics previous = null; - while ( scanner.hasNextLine() ) - { + while (scanner.hasNextLine()) { String line = scanner.nextLine(); - if ( line.charAt( 0 ) == ' ' ) - { - previous = new RunEntryStatistics( previous.getRunTime(), + if (line.charAt(0) == ' ') { + previous = new RunEntryStatistics( + previous.getRunTime(), previous.getSuccessfulBuilds(), previous.getClassMethod().getClazz(), - previous.getClassMethod().getMethod() + NL + line.substring( 1 ) ); - } - else - { - if ( previous != null ) - { - result.put( previous.getClassMethod(), previous ); + previous.getClassMethod().getMethod() + NL + line.substring(1)); + } else { + if (previous != null) { + result.put(previous.getClassMethod(), previous); } - int to = line.indexOf( ',' ); + int to = line.indexOf(','); - String successfulBuildsString = line.substring( 0, to ); - int successfulBuilds = parseInt( successfulBuildsString ); + String successfulBuildsString = line.substring(0, to); + int successfulBuilds = parseInt(successfulBuildsString); int from = 1 + to; - to = line.indexOf( ',', from + 1 ); + to = line.indexOf(',', from + 1); - String runTimeString = line.substring( from, to ); - int runTime = parseInt( runTimeString ); + String runTimeString = line.substring(from, to); + int runTime = parseInt(runTimeString); from = 1 + to; - to = line.indexOf( ',', from + 1 ); + to = line.indexOf(',', from + 1); - String className = to == -1 ? line.substring( from ) : line.substring( from, to ); + String className = to == -1 ? line.substring(from) : line.substring(from, to); from = 1 + to; - String methodName = to == -1 ? null : line.substring( from ); + String methodName = to == -1 ? null : line.substring(from); - ClassMethod classMethod = new ClassMethod( className, methodName ); - previous = new RunEntryStatistics( runTime, successfulBuilds, classMethod ); + ClassMethod classMethod = new ClassMethod(className, methodName); + previous = new RunEntryStatistics(runTime, successfulBuilds, classMethod); } } - if ( previous != null ) - { - result.put( previous.getClassMethod(), previous ); + if (previous != null) { + result.put(previous.getClassMethod(), previous); } } - return new RunEntryStatisticsMap( result ); + return new RunEntryStatisticsMap(result); } - public void serialize( File statsFile ) - throws IOException - { - if ( statsFile.isFile() ) - { + public void serialize(File statsFile) throws IOException { + if (statsFile.isFile()) { //noinspection ResultOfMethodCallIgnored statsFile.delete(); } - OutputStream os = new FileOutputStream( statsFile ); - try ( BufferedWriter writer = new BufferedWriter( new OutputStreamWriter( os, UTF_8 ), 64 * 1024 ) ) - { - List items = new ArrayList<>( runEntryStatistics.values() ); - sort( items, new RunCountComparator() ); - for ( Iterator it = items.iterator(); it.hasNext(); ) - { + OutputStream os = new FileOutputStream(statsFile); + try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, UTF_8), 64 * 1024)) { + List items = new ArrayList<>(runEntryStatistics.values()); + sort(items, new RunCountComparator()); + for (Iterator it = items.iterator(); it.hasNext(); ) { RunEntryStatistics item = it.next(); ClassMethod test = item.getClassMethod(); String line = item.getSuccessfulBuilds() + "," + item.getRunTime() + "," + test.getClazz() + ","; - writer.write( line ); + writer.write(line); boolean wasFirstLine = false; String method = test.getMethod(); - if ( method == null ) - { + if (method == null) { continue; } - for ( Scanner scanner = new Scanner( method ); scanner.hasNextLine(); wasFirstLine = true ) - { + for (Scanner scanner = new Scanner(method); scanner.hasNextLine(); wasFirstLine = true) { String methodLine = scanner.nextLine(); - if ( wasFirstLine ) - { - writer.write( ' ' ); + if (wasFirstLine) { + writer.write(' '); } - writer.write( methodLine ); - if ( scanner.hasNextLine() ) - { + writer.write(methodLine); + if (scanner.hasNextLine()) { writer.newLine(); } } - if ( it.hasNext() ) - { + if (it.hasNext()) { writer.newLine(); } } } } - private RunEntryStatistics findOrCreate( ReportEntry reportEntry ) - { - ClassMethod classMethod = new ClassMethod( reportEntry.getSourceName(), reportEntry.getName() ); - RunEntryStatistics item = runEntryStatistics.get( classMethod ); - return item != null ? item : new RunEntryStatistics( reportEntry.getElapsed( 0 ), 0, classMethod ); + private RunEntryStatistics findOrCreate(ReportEntry reportEntry) { + ClassMethod classMethod = new ClassMethod(reportEntry.getSourceName(), reportEntry.getName()); + RunEntryStatistics item = runEntryStatistics.get(classMethod); + return item != null ? item : new RunEntryStatistics(reportEntry.getElapsed(0), 0, classMethod); } - public RunEntryStatistics createNextGeneration( ReportEntry reportEntry ) - { - RunEntryStatistics newItem = findOrCreate( reportEntry ); - return newItem.nextGeneration( reportEntry.getElapsed( 0 ) ); + public RunEntryStatistics createNextGeneration(ReportEntry reportEntry) { + RunEntryStatistics newItem = findOrCreate(reportEntry); + return newItem.nextGeneration(reportEntry.getElapsed(0)); } - public RunEntryStatistics createNextGenerationFailure( ReportEntry reportEntry ) - { - RunEntryStatistics newItem = findOrCreate( reportEntry ); - return newItem.nextGenerationFailure( reportEntry.getElapsed( 0 ) ); + public RunEntryStatistics createNextGenerationFailure(ReportEntry reportEntry) { + RunEntryStatistics newItem = findOrCreate(reportEntry); + return newItem.nextGenerationFailure(reportEntry.getElapsed(0)); } - public void add( RunEntryStatistics item ) - { - runEntryStatistics.put( item.getClassMethod(), item ); + public void add(RunEntryStatistics item) { + runEntryStatistics.put(item.getClassMethod(), item); } - static final class RunCountComparator - implements Comparator - { + static final class RunCountComparator implements Comparator { @Override - public int compare( RunEntryStatistics o, RunEntryStatistics o1 ) - { + public int compare(RunEntryStatistics o, RunEntryStatistics o1) { int runtime = o.getSuccessfulBuilds() - o1.getSuccessfulBuilds(); return runtime == 0 ? o.getRunTime() - o1.getRunTime() : runtime; } } - public List> getPrioritizedTestsClassRunTime( List> testsToRun, int threadCount ) - { - List prioritizedTests = getPrioritizedTests( testsToRun, new TestRuntimeComparator() ); - ThreadedExecutionScheduler threadedExecutionScheduler = new ThreadedExecutionScheduler( threadCount ); - for ( Object prioritizedTest1 : prioritizedTests ) - { - threadedExecutionScheduler.addTest( (PrioritizedTest) prioritizedTest1 ); + public List> getPrioritizedTestsClassRunTime(List> testsToRun, int threadCount) { + List prioritizedTests = getPrioritizedTests(testsToRun, new TestRuntimeComparator()); + ThreadedExecutionScheduler threadedExecutionScheduler = new ThreadedExecutionScheduler(threadCount); + for (Object prioritizedTest1 : prioritizedTests) { + threadedExecutionScheduler.addTest((PrioritizedTest) prioritizedTest1); } return threadedExecutionScheduler.getResult(); } - public List> getPrioritizedTestsByFailureFirst( List> testsToRun ) - { - List prioritizedTests = getPrioritizedTests( testsToRun, new LeastFailureComparator() ); - return transformToClasses( prioritizedTests ); + public List> getPrioritizedTestsByFailureFirst(List> testsToRun) { + List prioritizedTests = getPrioritizedTests(testsToRun, new LeastFailureComparator()); + return transformToClasses(prioritizedTests); } - private List getPrioritizedTests( List> testsToRun, - Comparator priorityComparator ) - { - Map classPriorities = getPriorities( priorityComparator ); + private List getPrioritizedTests( + List> testsToRun, Comparator priorityComparator) { + Map classPriorities = getPriorities(priorityComparator); List tests = new ArrayList<>(); - for ( Class clazz : testsToRun ) - { - Priority pri = classPriorities.get( clazz.getName() ); - if ( pri == null ) - { - pri = Priority.newTestClassPriority( clazz.getName() ); + for (Class clazz : testsToRun) { + Priority pri = classPriorities.get(clazz.getName()); + if (pri == null) { + pri = Priority.newTestClassPriority(clazz.getName()); } - PrioritizedTest prioritizedTest = new PrioritizedTest( clazz, pri ); - tests.add( prioritizedTest ); + PrioritizedTest prioritizedTest = new PrioritizedTest(clazz, pri); + tests.add(prioritizedTest); } - sort( tests, new PrioritizedTestComparator() ); + sort(tests, new PrioritizedTestComparator()); return tests; } - private static List> transformToClasses( List tests ) - { + private static List> transformToClasses(List tests) { List> result = new ArrayList<>(); - for ( PrioritizedTest test : tests ) - { - result.add( test.getClazz() ); + for (PrioritizedTest test : tests) { + result.add(test.getClazz()); } return result; } - private Map getPriorities( Comparator priorityComparator ) - { + private Map getPriorities(Comparator priorityComparator) { Map priorities = new HashMap<>(); - for ( Entry testNames : runEntryStatistics.entrySet() ) - { + for (Entry testNames : runEntryStatistics.entrySet()) { String clazzName = testNames.getKey().getClazz(); - Priority priority = priorities.get( clazzName ); - if ( priority == null ) - { - priority = new Priority( clazzName ); - priorities.put( clazzName, priority ); + Priority priority = priorities.get(clazzName); + if (priority == null) { + priority = new Priority(clazzName); + priorities.put(clazzName, priority); } - priority.addItem( testNames.getValue() ); + priority.addItem(testNames.getValue()); } - List items = new ArrayList<>( priorities.values() ); - sort( items, priorityComparator ); + List items = new ArrayList<>(priorities.values()); + sort(items, priorityComparator); Map result = new HashMap<>(); int i = 0; - for ( Priority pri : items ) - { - pri.setPriority( i++ ); - result.put( pri.getClassName(), pri ); + for (Priority pri : items) { + pri.setPriority(i++); + result.put(pri.getClassName(), pri); } return result; } - static final class PrioritizedTestComparator - implements Comparator - { + static final class PrioritizedTestComparator implements Comparator { @Override - public int compare( PrioritizedTest o, PrioritizedTest o1 ) - { + public int compare(PrioritizedTest o, PrioritizedTest o1) { return o.getPriority() - o1.getPriority(); } } - static final class TestRuntimeComparator - implements Comparator - { + static final class TestRuntimeComparator implements Comparator { @Override - public int compare( Priority o, Priority o1 ) - { + public int compare(Priority o, Priority o1) { return o1.getTotalRuntime() - o.getTotalRuntime(); } } - static final class LeastFailureComparator - implements Comparator - { + static final class LeastFailureComparator implements Comparator { @Override - public int compare( Priority o, Priority o1 ) - { + public int compare(Priority o, Priority o1) { return o.getMinSuccessRate() - o1.getMinSuccessRate(); } } diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/api/runorder/ThreadedExecutionScheduler.java b/surefire-api/src/main/java/org/apache/maven/surefire/api/runorder/ThreadedExecutionScheduler.java index b713e2146e..6668a56365 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/api/runorder/ThreadedExecutionScheduler.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/api/runorder/ThreadedExecutionScheduler.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.api.runorder; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,72 +16,60 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.api.runorder; import java.util.ArrayList; import java.util.List; - /** * @author Kristian Rosenvold */ -public class ThreadedExecutionScheduler -{ +public class ThreadedExecutionScheduler { private final int numThreads; private final int runTime[]; private final List>[] lists; - @SuppressWarnings( "unchecked" ) - public ThreadedExecutionScheduler( int numThreads ) - { + @SuppressWarnings("unchecked") + public ThreadedExecutionScheduler(int numThreads) { this.numThreads = numThreads; runTime = new int[numThreads]; lists = new List[numThreads]; - for ( int i = 0; i < numThreads; i++ ) - { + for (int i = 0; i < numThreads; i++) { lists[i] = new ArrayList<>(); } } - public void addTest( PrioritizedTest prioritizedTest ) - { + public void addTest(PrioritizedTest prioritizedTest) { final int leastBusySlot = findLeastBusySlot(); runTime[leastBusySlot] += prioritizedTest.getTotalRuntime(); //noinspection unchecked - lists[leastBusySlot].add( prioritizedTest.getClazz() ); + lists[leastBusySlot].add(prioritizedTest.getClazz()); } - public List> getResult() - { + public List> getResult() { List> result = new ArrayList<>(); int index = 0; boolean added; - do - { + do { added = false; - for ( int i = 0; i < numThreads; i++ ) - { - if ( lists[i].size() > index ) - { - result.add( lists[i].get( index ) ); + for (int i = 0; i < numThreads; i++) { + if (lists[i].size() > index) { + result.add(lists[i].get(index)); added = true; } } index++; - } - while ( added ); + } while (added); return result; } - private int findLeastBusySlot() - { + private int findLeastBusySlot() { int leastBusy = 0; int minRuntime = runTime[0]; - for ( int i = 1; i < numThreads; i++ ) - { - if ( runTime[i] < minRuntime ) - { + for (int i = 1; i < numThreads; i++) { + if (runTime[i] < minRuntime) { leastBusy = i; minRuntime = runTime[i]; } diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/api/stream/AbstractStreamDecoder.java b/surefire-api/src/main/java/org/apache/maven/surefire/api/stream/AbstractStreamDecoder.java index 1912ccb5dc..400f74f6c0 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/api/stream/AbstractStreamDecoder.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/api/stream/AbstractStreamDecoder.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.api.stream; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,12 +16,11 @@ * specific language governing permissions and limitations * under the License. */ - -import org.apache.maven.plugin.surefire.log.api.ConsoleLogger; -import org.apache.maven.surefire.api.fork.ForkNodeArguments; +package org.apache.maven.surefire.api.stream; import javax.annotation.Nonnegative; import javax.annotation.Nonnull; + import java.io.EOFException; import java.io.File; import java.io.IOException; @@ -38,6 +35,9 @@ import java.util.List; import java.util.Map; +import org.apache.maven.plugin.surefire.log.api.ConsoleLogger; +import org.apache.maven.surefire.api.fork.ForkNodeArguments; + import static java.lang.Math.max; import static java.lang.Math.min; import static java.nio.charset.CodingErrorAction.REPLACE; @@ -53,20 +53,23 @@ * @param enum describing the meaning of the message * @param enum for segment type */ -public abstract class AbstractStreamDecoder, ST extends Enum> implements AutoCloseable -{ +public abstract class AbstractStreamDecoder, ST extends Enum> implements AutoCloseable { public static final int BUFFER_SIZE = 1024; private static final String PRINTABLE_JVM_NATIVE_STREAM = "Listening for transport dt_socket at address:"; private static final String[] JVM_ERROR_PATTERNS = { - "could not create the java virtual machine", "error occurred during initialization", // of VM, of boot layer + "could not create the java virtual machine", + "error occurred during initialization", // of VM, of boot layer "error:", // general errors - "could not reserve enough space", "could not allocate", "unable to allocate", // memory errors + "could not reserve enough space", + "could not allocate", + "unable to allocate", // memory errors "java.lang.module.findexception" // JPMS errors }; - private static final byte[] DEFAULT_STREAM_ENCODING_BYTES = DEFAULT_STREAM_ENCODING.name().getBytes( US_ASCII ); + private static final byte[] DEFAULT_STREAM_ENCODING_BYTES = + DEFAULT_STREAM_ENCODING.name().getBytes(US_ASCII); private static final int NO_POSITION = -1; private static final int DELIMITER_LENGTH = 1; @@ -79,304 +82,265 @@ public abstract class AbstractStreamDecoder, ST extends E private final Map messageTypes; private final ConsoleLogger logger; - protected AbstractStreamDecoder( @Nonnull ReadableByteChannel channel, - @Nonnull ForkNodeArguments arguments, - @Nonnull Map messageTypes ) - { + protected AbstractStreamDecoder( + @Nonnull ReadableByteChannel channel, + @Nonnull ForkNodeArguments arguments, + @Nonnull Map messageTypes) { this.channel = channel; this.arguments = arguments; this.messageTypes = messageTypes; logger = arguments.getConsoleLogger(); } - public abstract M decode( @Nonnull Memento memento ) throws MalformedChannelException, IOException; + public abstract M decode(@Nonnull Memento memento) throws MalformedChannelException, IOException; @Nonnull protected abstract byte[] getEncodedMagicNumber(); @Nonnull - protected abstract ST[] nextSegmentType( @Nonnull MT messageType ); + protected abstract ST[] nextSegmentType(@Nonnull MT messageType); @Nonnull - protected abstract M toMessage( @Nonnull MT messageType, @Nonnull Memento memento ) - throws MalformedFrameException; + protected abstract M toMessage(@Nonnull MT messageType, @Nonnull Memento memento) throws MalformedFrameException; @Nonnull - protected final ForkNodeArguments getArguments() - { + protected final ForkNodeArguments getArguments() { return arguments; } - protected void debugStream( byte[] array, int position, int remaining ) - { - } + protected void debugStream(byte[] array, int position, int remaining) {} - protected MT readMessageType( @Nonnull Memento memento ) throws IOException, MalformedFrameException - { + protected MT readMessageType(@Nonnull Memento memento) throws IOException, MalformedFrameException { byte[] header = getEncodedMagicNumber(); int readCount = DELIMITER_LENGTH + header.length + DELIMITER_LENGTH + BYTE_LENGTH + DELIMITER_LENGTH; - read( memento, readCount ); - checkHeader( memento ); - return messageTypes.get( readSegment( memento ) ); + read(memento, readCount); + checkHeader(memento); + return messageTypes.get(readSegment(memento)); } @Nonnull - @SuppressWarnings( "checkstyle:magicnumber" ) - protected Segment readSegment( @Nonnull Memento memento ) throws IOException, MalformedFrameException - { - int readCount = readByte( memento ) & 0xff; - read( memento, readCount + DELIMITER_LENGTH ); + @SuppressWarnings("checkstyle:magicnumber") + protected Segment readSegment(@Nonnull Memento memento) throws IOException, MalformedFrameException { + int readCount = readByte(memento) & 0xff; + read(memento, readCount + DELIMITER_LENGTH); ByteBuffer bb = memento.getByteBuffer(); - Segment segment = new Segment( bb.array(), bb.arrayOffset() + ( (Buffer) bb ).position(), readCount ); - ( (Buffer) bb ).position( ( (Buffer) bb ).position() + readCount ); - checkDelimiter( memento ); + Segment segment = new Segment(bb.array(), bb.arrayOffset() + ((Buffer) bb).position(), readCount); + ((Buffer) bb).position(((Buffer) bb).position() + readCount); + checkDelimiter(memento); return segment; } @Nonnull - @SuppressWarnings( "checkstyle:magicnumber" ) - protected Charset readCharset( @Nonnull Memento memento ) throws IOException, MalformedFrameException - { - int length = readByte( memento ) & 0xff; - read( memento, length + DELIMITER_LENGTH ); + @SuppressWarnings("checkstyle:magicnumber") + protected Charset readCharset(@Nonnull Memento memento) throws IOException, MalformedFrameException { + int length = readByte(memento) & 0xff; + read(memento, length + DELIMITER_LENGTH); ByteBuffer bb = memento.getByteBuffer(); byte[] array = bb.array(); - int offset = bb.arrayOffset() + ( (Buffer) bb ).position(); - ( (Buffer) bb ).position( ( (Buffer) bb ).position() + length ); + int offset = bb.arrayOffset() + ((Buffer) bb).position(); + ((Buffer) bb).position(((Buffer) bb).position() + length); boolean isDefaultEncoding = false; - if ( length == DEFAULT_STREAM_ENCODING_BYTES.length ) - { + if (length == DEFAULT_STREAM_ENCODING_BYTES.length) { isDefaultEncoding = true; - for ( int i = 0; i < length; i++ ) - { + for (int i = 0; i < length; i++) { isDefaultEncoding &= DEFAULT_STREAM_ENCODING_BYTES[i] == array[offset + i]; } } - try - { - Charset charset = - isDefaultEncoding + try { + Charset charset = isDefaultEncoding ? DEFAULT_STREAM_ENCODING - : Charset.forName( new String( array, offset, length, US_ASCII ) ); + : Charset.forName(new String(array, offset, length, US_ASCII)); - checkDelimiter( memento ); + checkDelimiter(memento); return charset; - } - catch ( IllegalArgumentException e ) - { - throw new MalformedFrameException( memento.getLine().getPositionByteBuffer(), ( (Buffer) bb ).position() ); + } catch (IllegalArgumentException e) { + throw new MalformedFrameException(memento.getLine().getPositionByteBuffer(), ((Buffer) bb).position()); } } - protected String readString( @Nonnull Memento memento ) throws IOException, MalformedFrameException - { - ( (Buffer) memento.getCharBuffer() ).clear(); - int readCount = readInt( memento ); - if ( readCount < 0 ) - { - throw new MalformedFrameException( memento.getLine().getPositionByteBuffer(), - ( (Buffer) memento.getByteBuffer() ).position() ); + protected String readString(@Nonnull Memento memento) throws IOException, MalformedFrameException { + ((Buffer) memento.getCharBuffer()).clear(); + int readCount = readInt(memento); + if (readCount < 0) { + throw new MalformedFrameException( + memento.getLine().getPositionByteBuffer(), ((Buffer) memento.getByteBuffer()).position()); } - read( memento, readCount + DELIMITER_LENGTH ); + read(memento, readCount + DELIMITER_LENGTH); final String string; - if ( readCount == 0 ) - { + if (readCount == 0) { string = ""; - } - else if ( readCount == 1 ) - { - read( memento, 1 ); + } else if (readCount == 1) { + read(memento, 1); byte oneChar = memento.getByteBuffer().get(); - string = oneChar == 0 ? null : String.valueOf( (char) oneChar ); + string = oneChar == 0 ? null : String.valueOf((char) oneChar); + } else { + string = readString(memento, readCount); } - else - { - string = readString( memento, readCount ); - } - read( memento, 1 ); - checkDelimiter( memento ); + read(memento, 1); + checkDelimiter(memento); return string; } - protected Integer readInteger( @Nonnull Memento memento ) throws IOException, MalformedFrameException - { - read( memento, BYTE_LENGTH ); + protected Integer readInteger(@Nonnull Memento memento) throws IOException, MalformedFrameException { + read(memento, BYTE_LENGTH); boolean isNullObject = memento.getByteBuffer().get() == 0; - if ( isNullObject ) - { - read( memento, DELIMITER_LENGTH ); - checkDelimiter( memento ); + if (isNullObject) { + read(memento, DELIMITER_LENGTH); + checkDelimiter(memento); return null; } - return readInt( memento ); + return readInt(memento); } - protected byte readByte( @Nonnull Memento memento ) throws IOException, MalformedFrameException - { - read( memento, BYTE_LENGTH + DELIMITER_LENGTH ); + protected byte readByte(@Nonnull Memento memento) throws IOException, MalformedFrameException { + read(memento, BYTE_LENGTH + DELIMITER_LENGTH); byte b = memento.getByteBuffer().get(); - checkDelimiter( memento ); + checkDelimiter(memento); return b; } - protected int readInt( @Nonnull Memento memento ) throws IOException, MalformedFrameException - { - read( memento, INT_LENGTH + DELIMITER_LENGTH ); + protected int readInt(@Nonnull Memento memento) throws IOException, MalformedFrameException { + read(memento, INT_LENGTH + DELIMITER_LENGTH); int i = memento.getByteBuffer().getInt(); - checkDelimiter( memento ); + checkDelimiter(memento); return i; } - protected Long readLong( @Nonnull Memento memento ) throws IOException, MalformedFrameException - { - read( memento, BYTE_LENGTH ); + protected Long readLong(@Nonnull Memento memento) throws IOException, MalformedFrameException { + read(memento, BYTE_LENGTH); boolean isNullObject = memento.getByteBuffer().get() == 0; - if ( isNullObject ) - { - read( memento, DELIMITER_LENGTH ); - checkDelimiter( memento ); + if (isNullObject) { + read(memento, DELIMITER_LENGTH); + checkDelimiter(memento); return null; } - return readLongPrivate( memento ); + return readLongPrivate(memento); } - protected long readLongPrivate( @Nonnull Memento memento ) throws IOException, MalformedFrameException - { - read( memento, LONG_LENGTH + DELIMITER_LENGTH ); + protected long readLongPrivate(@Nonnull Memento memento) throws IOException, MalformedFrameException { + read(memento, LONG_LENGTH + DELIMITER_LENGTH); long num = memento.getByteBuffer().getLong(); - checkDelimiter( memento ); + checkDelimiter(memento); return num; } - @SuppressWarnings( "checkstyle:magicnumber" ) - protected final void checkDelimiter( Memento memento ) throws MalformedFrameException - { + @SuppressWarnings("checkstyle:magicnumber") + protected final void checkDelimiter(Memento memento) throws MalformedFrameException { ByteBuffer bb = memento.bb; - if ( ( 0xff & bb.get() ) != ':' ) - { - throw new MalformedFrameException( memento.getLine().getPositionByteBuffer(), ( (Buffer) bb ).position() ); + if ((0xff & bb.get()) != ':') { + throw new MalformedFrameException(memento.getLine().getPositionByteBuffer(), ((Buffer) bb).position()); } } - protected final void checkHeader( Memento memento ) throws MalformedFrameException - { + protected final void checkHeader(Memento memento) throws MalformedFrameException { ByteBuffer bb = memento.bb; - checkDelimiter( memento ); + checkDelimiter(memento); int shift = 0; - try - { + try { byte[] header = getEncodedMagicNumber(); byte[] bbArray = bb.array(); - for ( int start = bb.arrayOffset() + ( (Buffer) bb ).position(), length = header.length; - shift < length; shift++ ) - { - if ( bbArray[shift + start] != header[shift] ) - { - throw new MalformedFrameException( memento.getLine().getPositionByteBuffer(), - ( (Buffer) bb ).position() + shift ); + for (int start = bb.arrayOffset() + ((Buffer) bb).position(), length = header.length; + shift < length; + shift++) { + if (bbArray[shift + start] != header[shift]) { + throw new MalformedFrameException( + memento.getLine().getPositionByteBuffer(), ((Buffer) bb).position() + shift); } } - } - finally - { - ( (Buffer) bb ).position( ( (Buffer) bb ).position() + shift ); + } finally { + ((Buffer) bb).position(((Buffer) bb).position() + shift); } - checkDelimiter( memento ); + checkDelimiter(memento); } - protected void checkArguments( Memento memento, int expectedDataElements ) - throws MalformedFrameException - { - if ( memento.getData().size() != expectedDataElements ) - { - throw new MalformedFrameException( memento.getLine().getPositionByteBuffer(), - ( (Buffer) memento.getByteBuffer() ).position() ); + protected void checkArguments(Memento memento, int expectedDataElements) throws MalformedFrameException { + if (memento.getData().size() != expectedDataElements) { + throw new MalformedFrameException( + memento.getLine().getPositionByteBuffer(), ((Buffer) memento.getByteBuffer()).position()); } } - private String readString( @Nonnull final Memento memento, @Nonnegative final int totalBytes ) - throws IOException, MalformedFrameException - { + private String readString(@Nonnull final Memento memento, @Nonnegative final int totalBytes) + throws IOException, MalformedFrameException { memento.getDecoder().reset(); final CharBuffer output = memento.getCharBuffer(); - ( (Buffer) output ).clear(); + ((Buffer) output).clear(); final ByteBuffer input = memento.getByteBuffer(); final List strings = new ArrayList<>(); int countDecodedBytes = 0; - for ( boolean endOfInput = false; !endOfInput; ) - { + for (boolean endOfInput = false; !endOfInput; ) { final int bytesToRead = totalBytes - countDecodedBytes; - read( memento, bytesToRead ); - int bytesToDecode = min( input.remaining(), bytesToRead ); + read(memento, bytesToRead); + int bytesToDecode = min(input.remaining(), bytesToRead); final boolean isLastChunk = bytesToDecode == bytesToRead; endOfInput = countDecodedBytes + bytesToDecode >= totalBytes; - do - { + do { boolean endOfChunk = output.remaining() >= bytesToRead; boolean endOfOutput = isLastChunk && endOfChunk; - int readInputBytes = decodeString( memento.getDecoder(), input, output, bytesToDecode, endOfOutput, - memento.getLine().getPositionByteBuffer() ); + int readInputBytes = decodeString( + memento.getDecoder(), + input, + output, + bytesToDecode, + endOfOutput, + memento.getLine().getPositionByteBuffer()); bytesToDecode -= readInputBytes; countDecodedBytes += readInputBytes; - } - while ( isLastChunk && bytesToDecode > 0 && output.hasRemaining() ); + } while (isLastChunk && bytesToDecode > 0 && output.hasRemaining()); - strings.add( ( (Buffer) output ).flip().toString() ); - ( (Buffer) output ).clear(); + strings.add(((Buffer) output).flip().toString()); + ((Buffer) output).clear(); } memento.getDecoder().reset(); - ( (Buffer) output ).clear(); + ((Buffer) output).clear(); - return toString( strings ); + return toString(strings); } - private static int decodeString( @Nonnull CharsetDecoder decoder, @Nonnull ByteBuffer input, - @Nonnull CharBuffer output, @Nonnegative int bytesToDecode, - boolean endOfInput, @Nonnegative int errorStreamFrom ) - throws MalformedFrameException - { - int limit = ( (Buffer) input ).limit(); - ( (Buffer) input ).limit( ( (Buffer) input ).position() + bytesToDecode ); + private static int decodeString( + @Nonnull CharsetDecoder decoder, + @Nonnull ByteBuffer input, + @Nonnull CharBuffer output, + @Nonnegative int bytesToDecode, + boolean endOfInput, + @Nonnegative int errorStreamFrom) + throws MalformedFrameException { + int limit = ((Buffer) input).limit(); + ((Buffer) input).limit(((Buffer) input).position() + bytesToDecode); - CoderResult result = decoder.decode( input, output, endOfInput ); - if ( result.isError() || result.isMalformed() ) - { - throw new MalformedFrameException( errorStreamFrom, ( (Buffer) input ).position() ); + CoderResult result = decoder.decode(input, output, endOfInput); + if (result.isError() || result.isMalformed()) { + throw new MalformedFrameException(errorStreamFrom, ((Buffer) input).position()); } int decodedBytes = bytesToDecode - input.remaining(); - ( (Buffer) input ).limit( limit ); + ((Buffer) input).limit(limit); return decodedBytes; } - private static String toString( List strings ) - { - if ( strings.size() == 1 ) - { - return strings.get( 0 ); + private static String toString(List strings) { + if (strings.size() == 1) { + return strings.get(0); } - StringBuilder concatenated = new StringBuilder( strings.size() * BUFFER_SIZE ); - for ( String s : strings ) - { - concatenated.append( s ); + StringBuilder concatenated = new StringBuilder(strings.size() * BUFFER_SIZE); + for (String s : strings) { + concatenated.append(s); } return concatenated.toString(); } - private void printCorruptedStream( Memento memento ) - { + private void printCorruptedStream(Memento memento) { ByteBuffer bb = memento.getByteBuffer(); - if ( bb.hasRemaining() ) - { + if (bb.hasRemaining()) { int bytesToWrite = bb.remaining(); - memento.getLine().write( bb, ( (Buffer) bb ).position(), bytesToWrite ); - ( (Buffer) bb ).position( ( (Buffer) bb ).position() + bytesToWrite ); + memento.getLine().write(bb, ((Buffer) bb).position(), bytesToWrite); + ((Buffer) bb).position(((Buffer) bb).position() + bytesToWrite); } } @@ -385,9 +349,8 @@ private void printCorruptedStream( Memento memento ) * * @param memento current memento object */ - protected final void printRemainingStream( Memento memento ) - { - printCorruptedStream( memento ); + protected final void printRemainingStream(Memento memento) { + printCorruptedStream(memento); memento.getLine().printExistingLine(); memento.getLine().clear(); } @@ -395,23 +358,20 @@ protected final void printRemainingStream( Memento memento ) /** * */ - public static final class Segment - { + public static final class Segment { private final byte[] array; private final int fromIndex; private final int length; private final int hashCode; - public Segment( byte[] array, int fromIndex, int length ) - { + public Segment(byte[] array, int fromIndex, int length) { this.array = array; this.fromIndex = fromIndex; this.length = length; int hashCode = 0; int i = fromIndex; - for ( int loops = length >> 1; loops-- != 0; ) - { + for (int loops = length >> 1; loops-- != 0; ) { hashCode = 31 * hashCode + array[i++]; hashCode = 31 * hashCode + array[i++]; } @@ -419,29 +379,23 @@ public Segment( byte[] array, int fromIndex, int length ) } @Override - public int hashCode() - { + public int hashCode() { return hashCode; } @Override - public boolean equals( Object obj ) - { - if ( !( obj instanceof Segment ) ) - { + public boolean equals(Object obj) { + if (!(obj instanceof Segment)) { return false; } Segment that = (Segment) obj; - if ( that.length != length ) - { + if (that.length != length) { return false; } - for ( int i = 0; i < length; i++ ) - { - if ( that.array[that.fromIndex + i] != array[fromIndex + i] ) - { + for (int i = 0; i < length; i++) { + if (that.array[that.fromIndex + i] != array[fromIndex + i]) { return false; } } @@ -449,61 +403,46 @@ public boolean equals( Object obj ) } } - protected @Nonnull StreamReadStatus read( @Nonnull Memento memento, int recommendedCount ) throws IOException - { + protected @Nonnull StreamReadStatus read(@Nonnull Memento memento, int recommendedCount) throws IOException { ByteBuffer buffer = memento.getByteBuffer(); - if ( buffer.remaining() >= recommendedCount && ( (Buffer) buffer ).limit() != 0 ) - { + if (buffer.remaining() >= recommendedCount && ((Buffer) buffer).limit() != 0) { return OVERFLOW; - } - else - { - if ( ( (Buffer) buffer ).position() != 0 - && recommendedCount > buffer.capacity() - ( (Buffer) buffer ).position() ) - { - ( (Buffer) buffer.compact() ).flip(); - memento.getLine().setPositionByteBuffer( 0 ); + } else { + if (((Buffer) buffer).position() != 0 + && recommendedCount > buffer.capacity() - ((Buffer) buffer).position()) { + ((Buffer) buffer.compact()).flip(); + memento.getLine().setPositionByteBuffer(0); } - int mark = ( (Buffer) buffer ).position(); - ( (Buffer) buffer ).position( ( (Buffer) buffer ).limit() ); - ( (Buffer) buffer ).limit( min( ( (Buffer) buffer ).position() + recommendedCount, buffer.capacity() ) ); - return read( buffer, mark, recommendedCount ); + int mark = ((Buffer) buffer).position(); + ((Buffer) buffer).position(((Buffer) buffer).limit()); + ((Buffer) buffer).limit(min(((Buffer) buffer).position() + recommendedCount, buffer.capacity())); + return read(buffer, mark, recommendedCount); } } - private StreamReadStatus read( ByteBuffer buffer, int oldPosition, int recommendedCount ) - throws IOException - { + private StreamReadStatus read(ByteBuffer buffer, int oldPosition, int recommendedCount) throws IOException { StreamReadStatus readStatus = null; boolean isEnd = false; - try - { - while ( !isEnd && ( (Buffer) buffer ).position() - oldPosition < recommendedCount - && ( (Buffer) buffer ).position() < ( (Buffer) buffer ).limit() ) - { - isEnd = channel.read( buffer ) == -1; + try { + while (!isEnd + && ((Buffer) buffer).position() - oldPosition < recommendedCount + && ((Buffer) buffer).position() < ((Buffer) buffer).limit()) { + isEnd = channel.read(buffer) == -1; } - } - finally - { - ( (Buffer) buffer ).limit( ( (Buffer) buffer ).position() ); - ( (Buffer) buffer ).position( oldPosition ); + } finally { + ((Buffer) buffer).limit(((Buffer) buffer).position()); + ((Buffer) buffer).position(oldPosition); int readBytes = buffer.remaining(); boolean readComplete = readBytes >= recommendedCount; - if ( !isEnd || readComplete ) - { - debugStream( buffer.array(), - buffer.arrayOffset() + ( (Buffer) buffer ).position(), buffer.remaining() ); + if (!isEnd || readComplete) { + debugStream(buffer.array(), buffer.arrayOffset() + ((Buffer) buffer).position(), buffer.remaining()); readStatus = readComplete ? OVERFLOW : UNDERFLOW; } } - if ( readStatus == null ) - { + if (readStatus == null) { throw new EOFException(); - } - else - { + } else { return readStatus; } } @@ -511,71 +450,57 @@ private StreamReadStatus read( ByteBuffer buffer, int oldPosition, int recommend /** * */ - public final class Memento - { + public final class Memento { private CharsetDecoder currentDecoder; private final CharsetDecoder defaultDecoder; - private final BufferedStream line = new BufferedStream( 32 ); + private final BufferedStream line = new BufferedStream(32); private final List data = new ArrayList<>(); - private final CharBuffer cb = CharBuffer.allocate( BUFFER_SIZE ); - private final ByteBuffer bb = ByteBuffer.allocate( BUFFER_SIZE ); + private final CharBuffer cb = CharBuffer.allocate(BUFFER_SIZE); + private final ByteBuffer bb = ByteBuffer.allocate(BUFFER_SIZE); - public Memento() - { - defaultDecoder = DEFAULT_STREAM_ENCODING.newDecoder() - .onMalformedInput( REPLACE ) - .onUnmappableCharacter( REPLACE ); - ( (Buffer) bb ).limit( 0 ); + public Memento() { + defaultDecoder = DEFAULT_STREAM_ENCODING + .newDecoder() + .onMalformedInput(REPLACE) + .onUnmappableCharacter(REPLACE); + ((Buffer) bb).limit(0); } - public void reset() - { + public void reset() { currentDecoder = null; data.clear(); } - public CharsetDecoder getDecoder() - { + public CharsetDecoder getDecoder() { return currentDecoder == null ? defaultDecoder : currentDecoder; } - public void setCharset( Charset charset ) - { - if ( charset.name().equals( defaultDecoder.charset().name() ) ) - { + public void setCharset(Charset charset) { + if (charset.name().equals(defaultDecoder.charset().name())) { currentDecoder = defaultDecoder; - } - else - { - currentDecoder = charset.newDecoder() - .onMalformedInput( REPLACE ) - .onUnmappableCharacter( REPLACE ); + } else { + currentDecoder = charset.newDecoder().onMalformedInput(REPLACE).onUnmappableCharacter(REPLACE); } } - public BufferedStream getLine() - { + public BufferedStream getLine() { return line; } - public List getData() - { + public List getData() { return data; } - public T ofDataAt( int indexOfData ) - { + public T ofDataAt(int indexOfData) { //noinspection unchecked - return (T) data.get( indexOfData ); + return (T) data.get(indexOfData); } - public CharBuffer getCharBuffer() - { + public CharBuffer getCharBuffer() { return cb; } - public ByteBuffer getByteBuffer() - { + public ByteBuffer getByteBuffer() { return bb; } } @@ -583,141 +508,108 @@ public ByteBuffer getByteBuffer() /** * This class avoids locking which gains the performance of this decoder. */ - public final class BufferedStream - { + public final class BufferedStream { private byte[] buffer; private int count; private int positionByteBuffer; private boolean isNewLine; - BufferedStream( int capacity ) - { + BufferedStream(int capacity) { this.buffer = new byte[capacity]; } - public int getPositionByteBuffer() - { + public int getPositionByteBuffer() { return positionByteBuffer; } - public void setPositionByteBuffer( int positionByteBuffer ) - { + public void setPositionByteBuffer(int positionByteBuffer) { this.positionByteBuffer = positionByteBuffer; } - public void write( ByteBuffer bb, int position, int length ) - { - ensureCapacity( length ); + public void write(ByteBuffer bb, int position, int length) { + ensureCapacity(length); byte[] array = bb.array(); int pos = bb.arrayOffset() + position; - while ( length-- > 0 ) - { + while (length-- > 0) { positionByteBuffer++; byte b = array[pos++]; - if ( b == '\r' || b == '\n' ) - { - if ( !isNewLine ) - { + if (b == '\r' || b == '\n') { + if (!isNewLine) { printExistingLine(); count = 0; } isNewLine = true; - } - else - { + } else { buffer[count++] = b; isNewLine = false; } } } - public void clear() - { + public void clear() { count = 0; } @Override - public String toString() - { - return new String( buffer, 0, count, DEFAULT_STREAM_ENCODING ); + public String toString() { + return new String(buffer, 0, count, DEFAULT_STREAM_ENCODING); } - private boolean isEmpty() - { + private boolean isEmpty() { return count == 0; } - private void ensureCapacity( int addCapacity ) - { + private void ensureCapacity(int addCapacity) { int oldCapacity = buffer.length; int exactCapacity = count + addCapacity; - if ( exactCapacity < 0 ) - { + if (exactCapacity < 0) { throw new OutOfMemoryError(); } - if ( oldCapacity < exactCapacity ) - { + if (oldCapacity < exactCapacity) { int newCapacity = oldCapacity << 1; - buffer = copyOf( buffer, max( newCapacity, exactCapacity ) ); + buffer = copyOf(buffer, max(newCapacity, exactCapacity)); } } - void printExistingLine() - { - if ( isEmpty() ) - { + void printExistingLine() { + if (isEmpty()) { return; } String s = toString(); - if ( isBlank( s ) ) - { + if (isBlank(s)) { return; } - if ( s.contains( PRINTABLE_JVM_NATIVE_STREAM ) ) - { - if ( logger.isDebugEnabled() ) - { - logger.debug( s ); - } - else if ( logger.isInfoEnabled() ) - { - logger.info( s ); - } - else - { + if (s.contains(PRINTABLE_JVM_NATIVE_STREAM)) { + if (logger.isDebugEnabled()) { + logger.debug(s); + } else if (logger.isInfoEnabled()) { + logger.info(s); + } else { // In case of debugging forked JVM, see PRINTABLE_JVM_NATIVE_STREAM. - System.out.println( s ); - } - } - else - { - if ( isJvmError( s ) ) - { - logger.error( s ); + System.out.println(s); } - else if ( logger.isDebugEnabled() ) - { - logger.debug( s ); + } else { + if (isJvmError(s)) { + logger.error(s); + } else if (logger.isDebugEnabled()) { + logger.debug(s); } String msg = "Corrupted channel by directly writing to native stream in forked JVM " - + arguments.getForkChannelId() + "."; - File dumpFile = arguments.dumpStreamText( msg + " Stream '" + s + "'." ); + + arguments.getForkChannelId() + "."; + File dumpFile = arguments.dumpStreamText(msg + " Stream '" + s + "'."); String dumpPath = dumpFile.getAbsolutePath(); - arguments.logWarningAtEnd( msg + " See FAQ web page and the dump file " + dumpPath ); + arguments.logWarningAtEnd(msg + " See FAQ web page and the dump file " + dumpPath); } } - private boolean isJvmError( String line ) - { + private boolean isJvmError(String line) { String lineLower = line.toLowerCase(); - for ( String errorPattern : JVM_ERROR_PATTERNS ) - { - if ( lineLower.contains( errorPattern ) ) - { + for (String errorPattern : JVM_ERROR_PATTERNS) { + if (lineLower.contains(errorPattern)) { return true; } } @@ -728,29 +620,24 @@ private boolean isJvmError( String line ) /** * */ - public static final class MalformedFrameException extends Exception - { + public static final class MalformedFrameException extends Exception { private final int readFrom; private final int readTo; - public MalformedFrameException( int readFrom, int readTo ) - { + public MalformedFrameException(int readFrom, int readTo) { this.readFrom = readFrom; this.readTo = readTo; } - public int readFrom() - { + public int readFrom() { return readFrom; } - public int readTo() - { + public int readTo() { return readTo; } - public boolean hasValidPositions() - { + public boolean hasValidPositions() { return readFrom != NO_POSITION && readTo != NO_POSITION && readTo - readFrom > 0; } } @@ -762,8 +649,7 @@ public boolean hasValidPositions() *
    * EOF - end of stream */ - public enum StreamReadStatus - { + public enum StreamReadStatus { UNDERFLOW, OVERFLOW, EOF diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/api/stream/AbstractStreamEncoder.java b/surefire-api/src/main/java/org/apache/maven/surefire/api/stream/AbstractStreamEncoder.java index 0bde0e55bc..eba5246fa8 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/api/stream/AbstractStreamEncoder.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/api/stream/AbstractStreamEncoder.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.api.stream; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,11 +16,10 @@ * specific language governing permissions and limitations * under the License. */ - -import org.apache.maven.surefire.api.report.RunMode; -import org.apache.maven.surefire.api.util.internal.WritableBufferedByteChannel; +package org.apache.maven.surefire.api.stream; import javax.annotation.Nonnull; + import java.io.IOException; import java.nio.Buffer; import java.nio.ByteBuffer; @@ -30,6 +27,9 @@ import java.nio.charset.Charset; import java.nio.charset.CharsetEncoder; +import org.apache.maven.surefire.api.report.RunMode; +import org.apache.maven.surefire.api.util.internal.WritableBufferedByteChannel; + import static java.lang.Math.ceil; import static java.nio.CharBuffer.wrap; @@ -38,16 +38,14 @@ * The type of message is expressed by opcode where the opcode object is described by the generic type {@link E}. * @param type of the message */ -public abstract class AbstractStreamEncoder> -{ +public abstract class AbstractStreamEncoder> { private static final byte BOOLEAN_NON_NULL_OBJECT = (byte) 0xff; private static final byte BOOLEAN_NULL_OBJECT = (byte) 0; private static final byte[] INT_BINARY = new byte[] {0, 0, 0, 0}; private final WritableByteChannel out; - public AbstractStreamEncoder( WritableByteChannel out ) - { + public AbstractStreamEncoder(WritableByteChannel out) { this.out = out; } @@ -55,7 +53,7 @@ public AbstractStreamEncoder( WritableByteChannel out ) protected abstract byte[] getEncodedMagicNumber(); @Nonnull - protected abstract byte[] enumToByteArray( E e ); + protected abstract byte[] enumToByteArray(E e); @Nonnull protected abstract byte[] getEncodedCharsetName(); @@ -66,148 +64,136 @@ public AbstractStreamEncoder( WritableByteChannel out ) @Nonnull protected abstract CharsetEncoder newCharsetEncoder(); - protected void write( ByteBuffer frame, boolean sendImmediately ) - throws IOException - { - if ( !sendImmediately && out instanceof WritableBufferedByteChannel ) - { - ( (WritableBufferedByteChannel) out ).writeBuffered( frame ); - } - else - { - out.write( frame ); + protected void write(ByteBuffer frame, boolean sendImmediately) throws IOException { + if (!sendImmediately && out instanceof WritableBufferedByteChannel) { + ((WritableBufferedByteChannel) out).writeBuffered(frame); + } else { + out.write(frame); } } - public void encodeHeader( ByteBuffer result, E operation, RunMode runMode, Long testRunId ) - { - encodeHeader( result, operation ); + public void encodeHeader(ByteBuffer result, E operation, RunMode runMode, Long testRunId) { + encodeHeader(result, operation); byte[] runmode = runMode == null ? new byte[0] : runMode.getRunmodeBinary(); - result.put( (byte) runmode.length ); - result.put( (byte) ':' ); - result.put( runmode ); - result.put( (byte) ':' ); - - result.put( (byte) ( testRunId == null ? 0 : 1 ) ); - if ( testRunId != null ) - { - result.putLong( testRunId ); + result.put((byte) runmode.length); + result.put((byte) ':'); + result.put(runmode); + result.put((byte) ':'); + + result.put((byte) (testRunId == null ? 0 : 1)); + if (testRunId != null) { + result.putLong(testRunId); } - result.put( (byte) ':' ); + result.put((byte) ':'); } - public void encodeHeader( ByteBuffer result, E operation ) - { - result.put( (byte) ':' ); - result.put( getEncodedMagicNumber() ); - result.put( (byte) ':' ); - byte[] opcode = enumToByteArray( operation ); - result.put( (byte) opcode.length ); - result.put( (byte) ':' ); - result.put( opcode ); - result.put( (byte) ':' ); + public void encodeHeader(ByteBuffer result, E operation) { + result.put((byte) ':'); + result.put(getEncodedMagicNumber()); + result.put((byte) ':'); + byte[] opcode = enumToByteArray(operation); + result.put((byte) opcode.length); + result.put((byte) ':'); + result.put(opcode); + result.put((byte) ':'); } - public void encodeCharset( ByteBuffer result ) - { + public void encodeCharset(ByteBuffer result) { byte[] charsetNameBinary = getEncodedCharsetName(); - result.put( (byte) charsetNameBinary.length ); - result.put( (byte) ':' ); - result.put( charsetNameBinary ); - result.put( (byte) ':' ); + result.put((byte) charsetNameBinary.length); + result.put((byte) ':'); + result.put(charsetNameBinary); + result.put((byte) ':'); } - public void encodeString( CharsetEncoder encoder, ByteBuffer result, String string ) - { - String nonNullString = nonNull( string ); + public void encodeString(CharsetEncoder encoder, ByteBuffer result, String string) { + String nonNullString = nonNull(string); - int counterPosition = ( (Buffer) result ).position(); + int counterPosition = ((Buffer) result).position(); - result.put( INT_BINARY ).put( (byte) ':' ); + result.put(INT_BINARY).put((byte) ':'); - int msgStart = ( (Buffer) result ).position(); - encoder.encode( wrap( nonNullString ), result, true ); - int msgEnd = ( (Buffer) result ).position(); + int msgStart = ((Buffer) result).position(); + encoder.encode(wrap(nonNullString), result, true); + int msgEnd = ((Buffer) result).position(); int encodedMsgSize = msgEnd - msgStart; - result.putInt( counterPosition, encodedMsgSize ); + result.putInt(counterPosition, encodedMsgSize); - ( (Buffer) result ).position( msgEnd ); + ((Buffer) result).position(msgEnd); - result.put( (byte) ':' ); + result.put((byte) ':'); } - public void encodeInteger( ByteBuffer result, Integer i ) - { - if ( i == null ) - { - result.put( BOOLEAN_NULL_OBJECT ); - } - else - { - result.put( BOOLEAN_NON_NULL_OBJECT ).putInt( i ); + public void encodeInteger(ByteBuffer result, Integer i) { + if (i == null) { + result.put(BOOLEAN_NULL_OBJECT); + } else { + result.put(BOOLEAN_NON_NULL_OBJECT).putInt(i); } - result.put( (byte) ':' ); + result.put((byte) ':'); } - public void encode( CharsetEncoder encoder, ByteBuffer result, E operation, RunMode runMode, Long testRunId, - String... messages ) - { - encodeHeader( result, operation, runMode, testRunId ); - encodeStringData( result, encoder, messages ); + public void encode( + CharsetEncoder encoder, + ByteBuffer result, + E operation, + RunMode runMode, + Long testRunId, + String... messages) { + encodeHeader(result, operation, runMode, testRunId); + encodeStringData(result, encoder, messages); } - public void encode( CharsetEncoder encoder, ByteBuffer result, E operation, String... messages ) - { - encodeHeader( result, operation ); - encodeStringData( result, encoder, messages ); + public void encode(CharsetEncoder encoder, ByteBuffer result, E operation, String... messages) { + encodeHeader(result, operation); + encodeStringData(result, encoder, messages); } - private void encodeStringData( ByteBuffer result, CharsetEncoder encoder, String... messages ) - { - encodeCharset( result ); - for ( String message : messages ) - { - encodeString( encoder, result, message ); + private void encodeStringData(ByteBuffer result, CharsetEncoder encoder, String... messages) { + encodeCharset(result); + for (String message : messages) { + encodeString(encoder, result, message); } } - public int estimateBufferLength( int opcodeLength, RunMode runMode, CharsetEncoder encoder, - int integersCounter, int longsCounter, String... strings ) - { - assert !( encoder == null && strings.length != 0 ); + public int estimateBufferLength( + int opcodeLength, + RunMode runMode, + CharsetEncoder encoder, + int integersCounter, + int longsCounter, + String... strings) { + assert !(encoder == null && strings.length != 0); // one delimiter character ':' + + one delimiter character ':' + // one byte + one delimiter character ':' + + one delimiter character ':' int lengthOfMetadata = 1 + getEncodedMagicNumber().length + 1 + 1 + 1 + opcodeLength + 1; // one byte of length + one delimiter character ':' + + one delimiter character ':' - lengthOfMetadata += 1 + 1 + ( runMode == null ? 0 : runMode.getRunmodeBinary().length ) + 1; + lengthOfMetadata += 1 + 1 + (runMode == null ? 0 : runMode.getRunmodeBinary().length) + 1; - if ( encoder != null ) - { + if (encoder != null) { // one byte of length + one delimiter character ':' + + one delimiter character ':' lengthOfMetadata += 1 + 1 + encoder.charset().name().length() + 1; } // one byte (0x00 if NULL) + 4 bytes for integer + one delimiter character ':' - int lengthOfData = ( 1 + 4 + 1 ) * integersCounter; + int lengthOfData = (1 + 4 + 1) * integersCounter; // one byte (0x00 if NULL) + 8 bytes for long + one delimiter character ':' - lengthOfData += ( 1 + 8 + 1 ) * longsCounter; + lengthOfData += (1 + 8 + 1) * longsCounter; - for ( String string : strings ) - { - String s = nonNull( string ); + for (String string : strings) { + String s = nonNull(string); // 4 bytes of length of the string + one delimiter character ':' + + one delimiter character ':' - lengthOfData += 4 + 1 + (int) ceil( encoder.maxBytesPerChar() * s.length() ) + 1; + lengthOfData += 4 + 1 + (int) ceil(encoder.maxBytesPerChar() * s.length()) + 1; } return lengthOfMetadata + lengthOfData; } - private static String nonNull( String msg ) - { + private static String nonNull(String msg) { return msg == null ? "\u0000" : msg; } } diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/api/stream/MalformedChannelException.java b/surefire-api/src/main/java/org/apache/maven/surefire/api/stream/MalformedChannelException.java index cf4468ffce..dfe4ffee7f 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/api/stream/MalformedChannelException.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/api/stream/MalformedChannelException.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.api.stream; /* @@ -22,6 +40,4 @@ /** * */ -public class MalformedChannelException extends Exception -{ -} +public class MalformedChannelException extends Exception {} diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/api/stream/SegmentType.java b/surefire-api/src/main/java/org/apache/maven/surefire/api/stream/SegmentType.java index 97932f1aa8..e857040099 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/api/stream/SegmentType.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/api/stream/SegmentType.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.api.stream; /* @@ -22,8 +40,7 @@ /** * */ -public enum SegmentType -{ +public enum SegmentType { RUN_MODE, TEST_RUN_ID, STRING_ENCODING, diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/api/suite/RunResult.java b/surefire-api/src/main/java/org/apache/maven/surefire/api/suite/RunResult.java index 4abe775c63..ceb182aee6 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/api/suite/RunResult.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/api/suite/RunResult.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.api.suite; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.api.suite; import java.io.ByteArrayOutputStream; import java.io.PrintWriter; @@ -30,8 +29,7 @@ * * @author Kristian Rosenvold */ -public class RunResult -{ +public class RunResult { private final int completedCount; private final int errors; @@ -52,40 +50,38 @@ public class RunResult private static final int NO_TESTS = 254; - public static RunResult timeout( RunResult accumulatedAtTimeout ) - { - return errorCode( accumulatedAtTimeout, accumulatedAtTimeout.getFailure(), true ); + public static RunResult timeout(RunResult accumulatedAtTimeout) { + return errorCode(accumulatedAtTimeout, accumulatedAtTimeout.getFailure(), true); } - public static RunResult failure( RunResult accumulatedAtTimeout, Exception cause ) - { - return errorCode( accumulatedAtTimeout, getStackTrace( cause ), accumulatedAtTimeout.isTimeout() ); + public static RunResult failure(RunResult accumulatedAtTimeout, Exception cause) { + return errorCode(accumulatedAtTimeout, getStackTrace(cause), accumulatedAtTimeout.isTimeout()); } - private static RunResult errorCode( RunResult other, String failure, boolean timeout ) - { - return new RunResult( other.getCompletedCount(), other.getErrors(), other.getFailures(), other.getSkipped(), - failure, timeout ); + private static RunResult errorCode(RunResult other, String failure, boolean timeout) { + return new RunResult( + other.getCompletedCount(), + other.getErrors(), + other.getFailures(), + other.getSkipped(), + failure, + timeout); } - public RunResult( int completedCount, int errors, int failures, int skipped ) - { - this( completedCount, errors, failures, skipped, null, false ); + public RunResult(int completedCount, int errors, int failures, int skipped) { + this(completedCount, errors, failures, skipped, null, false); } - public RunResult( int completedCount, int errors, int failures, int skipped, int flakes ) - { - this( completedCount, errors, failures, skipped, flakes, null, false ); + public RunResult(int completedCount, int errors, int failures, int skipped, int flakes) { + this(completedCount, errors, failures, skipped, flakes, null, false); } - public RunResult( int completedCount, int errors, int failures, int skipped, String failure, boolean timeout ) - { - this( completedCount, errors, failures, skipped, 0, failure, timeout ); + public RunResult(int completedCount, int errors, int failures, int skipped, String failure, boolean timeout) { + this(completedCount, errors, failures, skipped, 0, failure, timeout); } - public RunResult( int completedCount, int errors, int failures, int skipped, int flakes, String failure, - boolean timeout ) - { + public RunResult( + int completedCount, int errors, int failures, int skipped, int flakes, String failure, boolean timeout) { this.completedCount = completedCount; this.errors = errors; this.failures = failures; @@ -95,92 +91,75 @@ public RunResult( int completedCount, int errors, int failures, int skipped, int this.flakes = flakes; } - private static String getStackTrace( Exception e ) - { - if ( e == null ) - { + private static String getStackTrace(Exception e) { + if (e == null) { return null; } ByteArrayOutputStream out = new ByteArrayOutputStream(); - try ( PrintWriter pw = new PrintWriter( out ) ) - { - e.printStackTrace( pw ); + try (PrintWriter pw = new PrintWriter(out)) { + e.printStackTrace(pw); } - return new String( out.toByteArray() ); + return new String(out.toByteArray()); } - public int getCompletedCount() - { + public int getCompletedCount() { return completedCount; } - public int getErrors() - { + public int getErrors() { return errors; } - public int getFlakes() - { + public int getFlakes() { return flakes; } - public int getFailures() - { + public int getFailures() { return failures; } - public int getSkipped() - { + public int getSkipped() { return skipped; } - public Integer getFailsafeCode() // Only used for compatibility reasons. - { - if ( completedCount == 0 ) - { + public Integer getFailsafeCode() // Only used for compatibility reasons. + { + if (completedCount == 0) { return NO_TESTS; } - if ( !isErrorFree() ) - { + if (!isErrorFree()) { return FAILURE; } return null; } /* Indicates if the tests are error free */ - public boolean isErrorFree() - { + public boolean isErrorFree() { return getFailures() == 0 && getErrors() == 0 && !isFailure(); } - public boolean isInternalError() - { + public boolean isInternalError() { return getFailures() == 0 && getErrors() == 0 && isFailure(); } /* Indicates test timeout or technical failure */ - public boolean isFailureOrTimeout() - { + public boolean isFailureOrTimeout() { return isTimeout() || isFailure(); } - public boolean isFailure() - { + public boolean isFailure() { return failure != null; } - public String getFailure() - { + public String getFailure() { return failure; } - public boolean isTimeout() - { + public boolean isTimeout() { return timeout; } - public RunResult aggregate( RunResult other ) - { + public RunResult aggregate(RunResult other) { String failureMessage = getFailure() != null ? getFailure() : other.getFailure(); boolean timeout = isTimeout() || other.isTimeout(); int completed = getCompletedCount() + other.getCompletedCount(); @@ -188,51 +167,41 @@ public RunResult aggregate( RunResult other ) int ign = getSkipped() + other.getSkipped(); int err = getErrors() + other.getErrors(); int flakes = getFlakes() + other.getFlakes(); - return new RunResult( completed, err, fail, ign, flakes, failureMessage, timeout ); + return new RunResult(completed, err, fail, ign, flakes, failureMessage, timeout); } - public static RunResult noTestsRun() - { - return new RunResult( 0, 0, 0, 0 ); + public static RunResult noTestsRun() { + return new RunResult(0, 0, 0, 0); } @Override - @SuppressWarnings( "RedundantIfStatement" ) - public boolean equals( Object o ) - { - if ( this == o ) - { + @SuppressWarnings("RedundantIfStatement") + public boolean equals(Object o) { + if (this == o) { return true; } - if ( o == null || getClass() != o.getClass() ) - { + if (o == null || getClass() != o.getClass()) { return false; } RunResult runResult = (RunResult) o; - if ( completedCount != runResult.completedCount ) - { + if (completedCount != runResult.completedCount) { return false; } - if ( errors != runResult.errors ) - { + if (errors != runResult.errors) { return false; } - if ( failures != runResult.failures ) - { + if (failures != runResult.failures) { return false; } - if ( skipped != runResult.skipped ) - { + if (skipped != runResult.skipped) { return false; } - if ( timeout != runResult.timeout ) - { + if (timeout != runResult.timeout) { return false; } - if ( failure != null ? !failure.equals( runResult.failure ) : runResult.failure != null ) - { + if (failure != null ? !failure.equals(runResult.failure) : runResult.failure != null) { return false; } @@ -240,14 +209,13 @@ public boolean equals( Object o ) } @Override - public int hashCode() - { + public int hashCode() { int result = completedCount; result = 31 * result + errors; result = 31 * result + failures; result = 31 * result + skipped; - result = 31 * result + ( failure != null ? failure.hashCode() : 0 ); - result = 31 * result + ( timeout ? 1 : 0 ); + result = 31 * result + (failure != null ? failure.hashCode() : 0); + result = 31 * result + (timeout ? 1 : 0); return result; } } diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/api/testset/DirectoryScannerParameters.java b/surefire-api/src/main/java/org/apache/maven/surefire/api/testset/DirectoryScannerParameters.java index 4c1eae2f3c..afff641acc 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/api/testset/DirectoryScannerParameters.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/api/testset/DirectoryScannerParameters.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.api.testset; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,16 +16,17 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.api.testset; import java.io.File; import java.util.List; + import org.apache.maven.surefire.api.util.RunOrder; /** * @author Kristian Rosenvold */ -public class DirectoryScannerParameters -{ +public class DirectoryScannerParameters { private final File testClassesDirectory; @Deprecated @@ -41,9 +40,12 @@ public class DirectoryScannerParameters private final RunOrder[] runOrder; - private DirectoryScannerParameters( File testClassesDirectory, List includes, List excludes, - List specificTests, RunOrder[] runOrder ) - { + private DirectoryScannerParameters( + File testClassesDirectory, + List includes, + List excludes, + List specificTests, + RunOrder[] runOrder) { this.testClassesDirectory = testClassesDirectory; this.includes = includes; this.excludes = excludes; @@ -51,17 +53,22 @@ private DirectoryScannerParameters( File testClassesDirectory, List incl this.runOrder = runOrder; } - public DirectoryScannerParameters( File testClassesDirectory, @Deprecated List includes, - @Deprecated List excludes, @Deprecated List specificTests, - String runOrder ) - { - this( testClassesDirectory, includes, excludes, specificTests, - runOrder == null ? RunOrder.DEFAULT : RunOrder.valueOfMulti( runOrder ) ); + public DirectoryScannerParameters( + File testClassesDirectory, + @Deprecated List includes, + @Deprecated List excludes, + @Deprecated List specificTests, + String runOrder) { + this( + testClassesDirectory, + includes, + excludes, + specificTests, + runOrder == null ? RunOrder.DEFAULT : RunOrder.valueOfMulti(runOrder)); } @Deprecated - public List getSpecificTests() - { + public List getSpecificTests() { return specificTests; } @@ -70,8 +77,7 @@ public List getSpecificTests() * * @return A directory that can be scanned for .class files */ - public File getTestClassesDirectory() - { + public File getTestClassesDirectory() { return testClassesDirectory; } @@ -81,8 +87,7 @@ public File getTestClassesDirectory() * @return A list of patterns. May contain both source file designators and .class extensions. */ @Deprecated - public List getIncludes() - { + public List getIncludes() { return includes; } @@ -92,13 +97,11 @@ public List getIncludes() * @return A list of patterns. May contain both source file designators and .class extensions. */ @Deprecated - public List getExcludes() - { + public List getExcludes() { return excludes; } - public RunOrder[] getRunOrder() - { + public RunOrder[] getRunOrder() { return runOrder; } } diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/api/testset/GenericTestPattern.java b/surefire-api/src/main/java/org/apache/maven/surefire/api/testset/GenericTestPattern.java index 754da63b65..b7681a4cc5 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/api/testset/GenericTestPattern.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/api/testset/GenericTestPattern.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.api.testset; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.api.testset; import java.util.Set; @@ -28,9 +27,7 @@ * @param test class, or null if not mandatory * @param test method, or null if not mandatory */ -public interface GenericTestPattern - extends TestFilter -{ +public interface GenericTestPattern extends TestFilter { boolean hasIncludedMethodPatterns(); boolean hasExcludedMethodPatterns(); diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/api/testset/IncludedExcludedPatterns.java b/surefire-api/src/main/java/org/apache/maven/surefire/api/testset/IncludedExcludedPatterns.java index ef558356d9..405a2e55e0 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/api/testset/IncludedExcludedPatterns.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/api/testset/IncludedExcludedPatterns.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.api.testset; /* @@ -19,8 +37,7 @@ * under the License. */ -final class IncludedExcludedPatterns -{ +final class IncludedExcludedPatterns { boolean hasExcludedMethodPatterns; boolean hasIncludedMethodPatterns; diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/api/testset/ResolvedTest.java b/surefire-api/src/main/java/org/apache/maven/surefire/api/testset/ResolvedTest.java index 24503581c0..9e976c2915 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/api/testset/ResolvedTest.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/api/testset/ResolvedTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.api.testset; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,12 +16,13 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.api.testset; + +import java.util.regex.Pattern; import org.apache.maven.surefire.shared.utils.StringUtils; import org.apache.maven.surefire.shared.utils.io.MatchPatterns; -import java.util.regex.Pattern; - import static java.io.File.separatorChar; import static java.util.regex.Pattern.compile; import static org.apache.maven.surefire.shared.utils.StringUtils.isBlank; @@ -38,14 +37,13 @@ */ // will be renamed to ResolvedTestPattern @Deprecated -public final class ResolvedTest -{ +public final class ResolvedTest { /** * Type of patterns in ResolvedTest constructor. */ - public enum Type - { - CLASS, METHOD + public enum Type { + CLASS, + METHOD } private static final String CLASS_FILE_EXTENSION = ".class"; @@ -80,23 +78,20 @@ public enum Type * @param methodPattern test method * @param isRegex {@code true} if pattern is regex */ - public ResolvedTest( String classPattern, String methodPattern, boolean isRegex ) - { - classPattern = tryBlank( classPattern ); - methodPattern = tryBlank( methodPattern ); - description = description( classPattern, methodPattern, isRegex ); - - if ( isRegex && classPattern != null ) - { - classPattern = wrapRegex( classPattern ); + public ResolvedTest(String classPattern, String methodPattern, boolean isRegex) { + classPattern = tryBlank(classPattern); + methodPattern = tryBlank(methodPattern); + description = description(classPattern, methodPattern, isRegex); + + if (isRegex && classPattern != null) { + classPattern = wrapRegex(classPattern); } - if ( isRegex && methodPattern != null ) - { - methodPattern = wrapRegex( methodPattern ); + if (isRegex && methodPattern != null) { + methodPattern = wrapRegex(methodPattern); } - this.classPattern = reformatClassPattern( classPattern, isRegex ); + this.classPattern = reformatClassPattern(classPattern, isRegex); this.methodPattern = methodPattern; isRegexTestClassPattern = isRegex; isRegexTestMethodPattern = isRegex; @@ -110,16 +105,14 @@ public ResolvedTest( String classPattern, String methodPattern, boolean isRegex * @param pattern pattern or regex * @param isRegex {@code true} if pattern is regex */ - public ResolvedTest( Type type, String pattern, boolean isRegex ) - { - pattern = tryBlank( pattern ); + public ResolvedTest(Type type, String pattern, boolean isRegex) { + pattern = tryBlank(pattern); final boolean isClass = type == Type.CLASS; - description = description( isClass ? pattern : null, !isClass ? pattern : null, isRegex ); - if ( isRegex && pattern != null ) - { - pattern = wrapRegex( pattern ); + description = description(isClass ? pattern : null, !isClass ? pattern : null, isRegex); + if (isRegex && pattern != null) { + pattern = wrapRegex(pattern); } - classPattern = isClass ? reformatClassPattern( pattern, isRegex ) : null; + classPattern = isClass ? reformatClassPattern(pattern, isRegex) : null; methodPattern = !isClass ? pattern : null; isRegexTestClassPattern = isRegex && isClass; isRegexTestMethodPattern = isRegex && !isClass; @@ -136,13 +129,11 @@ public ResolvedTest( Type type, String pattern, boolean isRegex ) * * @return class pattern or regex */ - public String getTestClassPattern() - { + public String getTestClassPattern() { return classPattern; } - public boolean hasTestClassPattern() - { + public boolean hasTestClassPattern() { return classPattern != null; } @@ -155,121 +146,97 @@ public boolean hasTestClassPattern() * * @return method pattern or regex */ - public String getTestMethodPattern() - { + public String getTestMethodPattern() { return methodPattern; } - public boolean hasTestMethodPattern() - { + public boolean hasTestMethodPattern() { return methodPattern != null; } - public boolean isRegexTestClassPattern() - { + public boolean isRegexTestClassPattern() { return isRegexTestClassPattern; } - public boolean isRegexTestMethodPattern() - { + public boolean isRegexTestMethodPattern() { return isRegexTestMethodPattern; } - public boolean isEmpty() - { + public boolean isEmpty() { return classPattern == null && methodPattern == null; } - public boolean matchAsInclusive( String testClassFile, String methodName ) - { - testClassFile = tryBlank( testClassFile ); - methodName = tryBlank( methodName ); + public boolean matchAsInclusive(String testClassFile, String methodName) { + testClassFile = tryBlank(testClassFile); + methodName = tryBlank(methodName); - return isEmpty() || alwaysInclusiveQuietly( testClassFile ) || match( testClassFile, methodName ); + return isEmpty() || alwaysInclusiveQuietly(testClassFile) || match(testClassFile, methodName); } - public boolean matchAsExclusive( String testClassFile, String methodName ) - { - testClassFile = tryBlank( testClassFile ); - methodName = tryBlank( methodName ); + public boolean matchAsExclusive(String testClassFile, String methodName) { + testClassFile = tryBlank(testClassFile); + methodName = tryBlank(methodName); - return !isEmpty() && canMatchExclusive( testClassFile, methodName ) && match( testClassFile, methodName ); + return !isEmpty() && canMatchExclusive(testClassFile, methodName) && match(testClassFile, methodName); } @Override - public boolean equals( Object o ) - { - if ( this == o ) - { + public boolean equals(Object o) { + if (this == o) { return true; } - if ( o == null || getClass() != o.getClass() ) - { + if (o == null || getClass() != o.getClass()) { return false; } ResolvedTest that = (ResolvedTest) o; - return ( classPattern == null ? that.classPattern == null : classPattern.equals( that.classPattern ) ) - && ( methodPattern == null ? that.methodPattern == null : methodPattern.equals( that.methodPattern ) ); + return (classPattern == null ? that.classPattern == null : classPattern.equals(that.classPattern)) + && (methodPattern == null ? that.methodPattern == null : methodPattern.equals(that.methodPattern)); } @Override - public int hashCode() - { + public int hashCode() { int result = classPattern != null ? classPattern.hashCode() : 0; - result = 31 * result + ( methodPattern != null ? methodPattern.hashCode() : 0 ); + result = 31 * result + (methodPattern != null ? methodPattern.hashCode() : 0); return result; } @Override - public String toString() - { + public String toString() { return isEmpty() ? "" : description; } - private static String description( String clazz, String method, boolean isRegex ) - { + private static String description(String clazz, String method, boolean isRegex) { String description; - if ( clazz == null && method == null ) - { + if (clazz == null && method == null) { description = null; - } - else if ( clazz == null ) - { + } else if (clazz == null) { description = "#" + method; - } - else if ( method == null ) - { + } else if (method == null) { description = clazz; - } - else - { + } else { description = clazz + "#" + method; } - return isRegex && description != null ? wrapRegex( description ) : description; + return isRegex && description != null ? wrapRegex(description) : description; } - private boolean canMatchExclusive( String testClassFile, String methodName ) - { - return canMatchExclusiveMethods( testClassFile, methodName ) - || canMatchExclusiveClasses( testClassFile, methodName ) - || canMatchExclusiveAll( testClassFile, methodName ); + private boolean canMatchExclusive(String testClassFile, String methodName) { + return canMatchExclusiveMethods(testClassFile, methodName) + || canMatchExclusiveClasses(testClassFile, methodName) + || canMatchExclusiveAll(testClassFile, methodName); } - private boolean canMatchExclusiveMethods( String testClassFile, String methodName ) - { + private boolean canMatchExclusiveMethods(String testClassFile, String methodName) { return testClassFile == null && methodName != null && classPattern == null && methodPattern != null; } - private boolean canMatchExclusiveClasses( String testClassFile, String methodName ) - { + private boolean canMatchExclusiveClasses(String testClassFile, String methodName) { return testClassFile != null && methodName == null && classPattern != null && methodPattern == null; } - private boolean canMatchExclusiveAll( String testClassFile, String methodName ) - { - return testClassFile != null && methodName != null && ( classPattern != null || methodPattern != null ); + private boolean canMatchExclusiveAll(String testClassFile, String methodName) { + return testClassFile != null && methodName != null && (classPattern != null || methodPattern != null); } /** @@ -278,223 +245,168 @@ private boolean canMatchExclusiveAll( String testClassFile, String methodName ) * @param testClassFile path to class file * @return {@code true} if examined class in null and class pattern exists */ - private boolean alwaysInclusiveQuietly( String testClassFile ) - { + private boolean alwaysInclusiveQuietly(String testClassFile) { return testClassFile == null && classPattern != null; } - private boolean match( String testClassFile, String methodName ) - { - return matchClass( testClassFile ) && matchMethod( methodName ); + private boolean match(String testClassFile, String methodName) { + return matchClass(testClassFile) && matchMethod(methodName); } - private boolean matchClass( String testClassFile ) - { - return classPattern == null || classMatcher.matchTestClassFile( testClassFile ); + private boolean matchClass(String testClassFile) { + return classPattern == null || classMatcher.matchTestClassFile(testClassFile); } - private boolean matchMethod( String methodName ) - { - return methodPattern == null || methodName == null || methodMatcher.matchMethodName( methodName ); + private boolean matchMethod(String methodName) { + return methodPattern == null || methodName == null || methodMatcher.matchMethodName(methodName); } - private static String tryBlank( String s ) - { - if ( s == null ) - { + private static String tryBlank(String s) { + if (s == null) { return null; - } - else - { + } else { String trimmed = s.trim(); - return StringUtils.isEmpty( trimmed ) ? null : trimmed; + return StringUtils.isEmpty(trimmed) ? null : trimmed; } } - private static String reformatClassPattern( String s, boolean isRegex ) - { - if ( s != null && !isRegex ) - { - String path = convertToPath( s ); - path = fromFullyQualifiedClass( path ); - if ( path != null && !path.startsWith( WILDCARD_PATH_PREFIX ) ) - { + private static String reformatClassPattern(String s, boolean isRegex) { + if (s != null && !isRegex) { + String path = convertToPath(s); + path = fromFullyQualifiedClass(path); + if (path != null && !path.startsWith(WILDCARD_PATH_PREFIX)) { path = WILDCARD_PATH_PREFIX + path; } return path; - } - else - { + } else { return s; } } - private static String convertToPath( String className ) - { - if ( isBlank( className ) ) - { + private static String convertToPath(String className) { + if (isBlank(className)) { return null; - } - else - { - if ( className.endsWith( JAVA_FILE_EXTENSION ) ) - { - className = className.substring( 0, className.length() - JAVA_FILE_EXTENSION.length() ) - + CLASS_FILE_EXTENSION; + } else { + if (className.endsWith(JAVA_FILE_EXTENSION)) { + className = className.substring(0, className.length() - JAVA_FILE_EXTENSION.length()) + + CLASS_FILE_EXTENSION; } return className; } } - static String wrapRegex( String unwrapped ) - { + static String wrapRegex(String unwrapped) { return REGEX_HANDLER_PREFIX + unwrapped + PATTERN_HANDLER_SUFFIX; } - static String fromFullyQualifiedClass( String cls ) - { - if ( cls.endsWith( CLASS_FILE_EXTENSION ) ) - { - String className = cls.substring( 0, cls.length() - CLASS_FILE_EXTENSION.length() ); - return className.replace( '.', '/' ) + CLASS_FILE_EXTENSION; - } - else if ( !cls.contains( "/" ) ) - { - if ( cls.endsWith( WILDCARD_FILENAME_POSTFIX ) ) - { - String clsName = cls.substring( 0, cls.length() - WILDCARD_FILENAME_POSTFIX.length() ); - return clsName.contains( "." ) ? clsName.replace( '.', '/' ) + WILDCARD_FILENAME_POSTFIX : cls; - } - else - { - return cls.replace( '.', '/' ); + static String fromFullyQualifiedClass(String cls) { + if (cls.endsWith(CLASS_FILE_EXTENSION)) { + String className = cls.substring(0, cls.length() - CLASS_FILE_EXTENSION.length()); + return className.replace('.', '/') + CLASS_FILE_EXTENSION; + } else if (!cls.contains("/")) { + if (cls.endsWith(WILDCARD_FILENAME_POSTFIX)) { + String clsName = cls.substring(0, cls.length() - WILDCARD_FILENAME_POSTFIX.length()); + return clsName.contains(".") ? clsName.replace('.', '/') + WILDCARD_FILENAME_POSTFIX : cls; + } else { + return cls.replace('.', '/'); } - } - else - { + } else { return cls; } } - private final class ClassMatcher - { + private final class ClassMatcher { private volatile MatchPatterns cache; - boolean matchTestClassFile( String testClassFile ) - { + boolean matchTestClassFile(String testClassFile) { return ResolvedTest.this.isRegexTestClassPattern() - ? matchClassRegexPatter( testClassFile ) - : matchClassPatter( testClassFile ); + ? matchClassRegexPatter(testClassFile) + : matchClassPatter(testClassFile); } - private MatchPatterns of( String... sources ) - { - if ( cache == null ) - { - try - { - checkIllegalCharacters( sources ); - cache = from( sources ); - } - catch ( IllegalArgumentException e ) - { - throwSanityError( e ); + private MatchPatterns of(String... sources) { + if (cache == null) { + try { + checkIllegalCharacters(sources); + cache = from(sources); + } catch (IllegalArgumentException e) { + throwSanityError(e); } } return cache; } - private boolean matchClassPatter( String testClassFile ) - { - //@todo We have to use File.separator only because the MatchPatterns is using it internally - cannot override. + private boolean matchClassPatter(String testClassFile) { + // @todo We have to use File.separator only because the MatchPatterns is using it internally - cannot + // override. String classPattern = ResolvedTest.this.classPattern; - if ( separatorChar != '/' ) - { - testClassFile = testClassFile.replace( '/', separatorChar ); - classPattern = classPattern.replace( '/', separatorChar ); + if (separatorChar != '/') { + testClassFile = testClassFile.replace('/', separatorChar); + classPattern = classPattern.replace('/', separatorChar); } - if ( classPattern.endsWith( WILDCARD_FILENAME_POSTFIX ) || classPattern.endsWith( CLASS_FILE_EXTENSION ) ) - { - return of( classPattern ).matches( testClassFile, true ); - } - else - { - String[] classPatterns = { classPattern + CLASS_FILE_EXTENSION, classPattern }; - return of( classPatterns ).matches( testClassFile, true ); + if (classPattern.endsWith(WILDCARD_FILENAME_POSTFIX) || classPattern.endsWith(CLASS_FILE_EXTENSION)) { + return of(classPattern).matches(testClassFile, true); + } else { + String[] classPatterns = {classPattern + CLASS_FILE_EXTENSION, classPattern}; + return of(classPatterns).matches(testClassFile, true); } } - private boolean matchClassRegexPatter( String testClassFile ) - { - String realFile = separatorChar == '/' ? testClassFile : testClassFile.replace( '/', separatorChar ); - return of( classPattern ).matches( realFile, true ); + private boolean matchClassRegexPatter(String testClassFile) { + String realFile = separatorChar == '/' ? testClassFile : testClassFile.replace('/', separatorChar); + return of(classPattern).matches(realFile, true); } } - private final class MethodMatcher - { + private final class MethodMatcher { private volatile Pattern cache; - boolean matchMethodName( String methodName ) - { - if ( ResolvedTest.this.isRegexTestMethodPattern() ) - { + boolean matchMethodName(String methodName) { + if (ResolvedTest.this.isRegexTestMethodPattern()) { fetchCache(); - return cache.matcher( methodName ) - .matches(); - } - else - { - return matchPath( ResolvedTest.this.methodPattern, methodName ); + return cache.matcher(methodName).matches(); + } else { + return matchPath(ResolvedTest.this.methodPattern, methodName); } } - void sanityCheck() - { - if ( ResolvedTest.this.isRegexTestMethodPattern() && ResolvedTest.this.hasTestMethodPattern() ) - { - try - { - checkIllegalCharacters( ResolvedTest.this.methodPattern ); + void sanityCheck() { + if (ResolvedTest.this.isRegexTestMethodPattern() && ResolvedTest.this.hasTestMethodPattern()) { + try { + checkIllegalCharacters(ResolvedTest.this.methodPattern); fetchCache(); - } - catch ( IllegalArgumentException e ) - { - throwSanityError( e ); + } catch (IllegalArgumentException e) { + throwSanityError(e); } } } - private void fetchCache() - { - if ( cache == null ) - { + private void fetchCache() { + if (cache == null) { int from = REGEX_HANDLER_PREFIX.length(); int to = ResolvedTest.this.methodPattern.length() - PATTERN_HANDLER_SUFFIX.length(); - String pattern = ResolvedTest.this.methodPattern.substring( from, to ); - cache = compile( pattern ); + String pattern = ResolvedTest.this.methodPattern.substring(from, to); + cache = compile(pattern); } } } - private static void checkIllegalCharacters( String... expressions ) - { - for ( String expression : expressions ) - { - if ( expression.contains( "#" ) ) - { - throw new IllegalArgumentException( "Extra '#' in regex: " + expression ); + private static void checkIllegalCharacters(String... expressions) { + for (String expression : expressions) { + if (expression.contains("#")) { + throw new IllegalArgumentException("Extra '#' in regex: " + expression); } } } - private static void throwSanityError( IllegalArgumentException e ) - { - throw new IllegalArgumentException( "%regex[] usage rule violation, valid regex rules:\n" - + " * # - " - + "where both regex can be individually evaluated as a regex\n" - + " * you may use at most 1 '#' to in one regex filter. " - + e.getLocalizedMessage(), e ); + private static void throwSanityError(IllegalArgumentException e) { + throw new IllegalArgumentException( + "%regex[] usage rule violation, valid regex rules:\n" + + " * # - " + + "where both regex can be individually evaluated as a regex\n" + + " * you may use at most 1 '#' to in one regex filter. " + + e.getLocalizedMessage(), + e); } } diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/api/testset/RunOrderParameters.java b/surefire-api/src/main/java/org/apache/maven/surefire/api/testset/RunOrderParameters.java index d7f55a6523..f07cffc8dc 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/api/testset/RunOrderParameters.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/api/testset/RunOrderParameters.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.api.testset; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,8 +16,10 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.api.testset; import java.io.File; + import org.apache.maven.surefire.api.util.RunOrder; import static org.apache.maven.surefire.api.util.RunOrder.ALPHABETICAL; @@ -28,53 +28,44 @@ /** * @author Kristian Rosenvold */ -public final class RunOrderParameters -{ +public final class RunOrderParameters { private final RunOrder[] runOrder; private final File runStatisticsFile; private final Long runOrderRandomSeed; - public RunOrderParameters( RunOrder[] runOrder, File runStatisticsFile ) - { - this( runOrder, runStatisticsFile, null ); + public RunOrderParameters(RunOrder[] runOrder, File runStatisticsFile) { + this(runOrder, runStatisticsFile, null); } - public RunOrderParameters( String runOrder, File runStatisticsFile ) - { - this( runOrder, runStatisticsFile, null ); + public RunOrderParameters(String runOrder, File runStatisticsFile) { + this(runOrder, runStatisticsFile, null); } - public RunOrderParameters( String runOrder, File runStatisticsFile, Long runOrderRandomSeed ) - { - this( runOrder == null ? DEFAULT : RunOrder.valueOfMulti( runOrder ), runStatisticsFile, runOrderRandomSeed ); + public RunOrderParameters(String runOrder, File runStatisticsFile, Long runOrderRandomSeed) { + this(runOrder == null ? DEFAULT : RunOrder.valueOfMulti(runOrder), runStatisticsFile, runOrderRandomSeed); } - public RunOrderParameters( RunOrder[] runOrder, File runStatisticsFile, Long runOrderRandomSeed ) - { + public RunOrderParameters(RunOrder[] runOrder, File runStatisticsFile, Long runOrderRandomSeed) { this.runOrder = runOrder; this.runStatisticsFile = runStatisticsFile; this.runOrderRandomSeed = runOrderRandomSeed; } - public static RunOrderParameters alphabetical() - { - return new RunOrderParameters( new RunOrder[]{ ALPHABETICAL }, null ); + public static RunOrderParameters alphabetical() { + return new RunOrderParameters(new RunOrder[] {ALPHABETICAL}, null); } - public RunOrder[] getRunOrder() - { + public RunOrder[] getRunOrder() { return runOrder; } - public Long getRunOrderRandomSeed() - { + public Long getRunOrderRandomSeed() { return runOrderRandomSeed; } - public File getRunStatisticsFile() - { + public File getRunStatisticsFile() { return runStatisticsFile; } } diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/api/testset/TestArtifactInfo.java b/surefire-api/src/main/java/org/apache/maven/surefire/api/testset/TestArtifactInfo.java index 3669c4a031..e5a01edb75 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/api/testset/TestArtifactInfo.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/api/testset/TestArtifactInfo.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.api.testset; /* @@ -24,25 +42,21 @@ * * @author Kristian Rosenvold */ -public class TestArtifactInfo -{ +public class TestArtifactInfo { private final String version; private final String classifier; - public TestArtifactInfo( String version, String classifier ) - { + public TestArtifactInfo(String version, String classifier) { this.version = version; this.classifier = classifier; } - public String getVersion() - { + public String getVersion() { return version; } - public String getClassifier() - { + public String getClassifier() { return classifier; } } diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/api/testset/TestFilter.java b/surefire-api/src/main/java/org/apache/maven/surefire/api/testset/TestFilter.java index 4db00036b6..f0c8d5020d 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/api/testset/TestFilter.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/api/testset/TestFilter.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.api.testset; /* @@ -25,7 +43,6 @@ * @param test class, or null if not mandatory * @param test method, or null if not mandatory */ -public interface TestFilter -{ - boolean shouldRun( C testClass, M methodName ); +public interface TestFilter { + boolean shouldRun(C testClass, M methodName); } diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/api/testset/TestListResolver.java b/surefire-api/src/main/java/org/apache/maven/surefire/api/testset/TestListResolver.java index bae7c2924d..ab8938dc2e 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/api/testset/TestListResolver.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/api/testset/TestListResolver.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.api.testset; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.api.testset; import java.util.ArrayList; import java.util.Collection; @@ -25,15 +24,15 @@ import java.util.LinkedHashSet; import java.util.Set; +import static java.util.Collections.singleton; import static java.util.Collections.unmodifiableSet; +import static org.apache.maven.surefire.api.testset.ResolvedTest.Type.CLASS; +import static org.apache.maven.surefire.api.testset.ResolvedTest.Type.METHOD; import static org.apache.maven.surefire.shared.utils.StringUtils.isBlank; import static org.apache.maven.surefire.shared.utils.StringUtils.isNotBlank; import static org.apache.maven.surefire.shared.utils.StringUtils.split; import static org.apache.maven.surefire.shared.utils.io.SelectorUtils.PATTERN_HANDLER_SUFFIX; import static org.apache.maven.surefire.shared.utils.io.SelectorUtils.REGEX_HANDLER_PREFIX; -import static java.util.Collections.singleton; -import static org.apache.maven.surefire.api.testset.ResolvedTest.Type.CLASS; -import static org.apache.maven.surefire.api.testset.ResolvedTest.Type.METHOD; // TODO In Surefire 3.0 see SUREFIRE-1309 and use normal fully qualified class name regex instead. /** @@ -44,14 +43,12 @@ * It is accessed by Java Reflection API in {@code org.apache.maven.surefire.booter.SurefireReflector} * using specific ClassLoader. */ -public class TestListResolver - implements GenericTestPattern -{ +public class TestListResolver implements GenericTestPattern { private static final String JAVA_CLASS_FILE_EXTENSION = ".class"; - private static final TestListResolver WILDCARD = new TestListResolver( "*" + JAVA_CLASS_FILE_EXTENSION ); + private static final TestListResolver WILDCARD = new TestListResolver("*" + JAVA_CLASS_FILE_EXTENSION); - private static final TestListResolver EMPTY = new TestListResolver( "" ); + private static final TestListResolver EMPTY = new TestListResolver(""); private final Set includedPatterns; @@ -61,77 +58,71 @@ public class TestListResolver private final boolean hasExcludedMethodPatterns; - public TestListResolver( Collection tests ) - { + public TestListResolver(Collection tests) { final IncludedExcludedPatterns patterns = new IncludedExcludedPatterns(); - final Set includedFilters = new LinkedHashSet<>( 0 ); - final Set excludedFilters = new LinkedHashSet<>( 0 ); - - for ( final String csvTests : tests ) - { - if ( isNotBlank( csvTests ) ) - { - for ( String request : split( csvTests, "," ) ) - { + final Set includedFilters = new LinkedHashSet<>(0); + final Set excludedFilters = new LinkedHashSet<>(0); + + for (final String csvTests : tests) { + if (isNotBlank(csvTests)) { + for (String request : split(csvTests, ",")) { request = request.trim(); - if ( !request.isEmpty() && !request.equals( "!" ) ) - { - resolveTestRequest( request, patterns, includedFilters, excludedFilters ); + if (!request.isEmpty() && !request.equals("!")) { + resolveTestRequest(request, patterns, includedFilters, excludedFilters); } } } } - this.includedPatterns = unmodifiableSet( includedFilters ); - this.excludedPatterns = unmodifiableSet( excludedFilters ); + this.includedPatterns = unmodifiableSet(includedFilters); + this.excludedPatterns = unmodifiableSet(excludedFilters); this.hasIncludedMethodPatterns = patterns.hasIncludedMethodPatterns; this.hasExcludedMethodPatterns = patterns.hasExcludedMethodPatterns; } - public TestListResolver( String csvTests ) - { - this( csvTests == null ? Collections.emptySet() : singleton( csvTests ) ); + public TestListResolver(String csvTests) { + this(csvTests == null ? Collections.emptySet() : singleton(csvTests)); } - public TestListResolver( Collection included, Collection excluded ) - { - this( mergeIncludedAndExcludedTests( included, excluded ) ); + public TestListResolver(Collection included, Collection excluded) { + this(mergeIncludedAndExcludedTests(included, excluded)); } /** * Used only in method filter. */ - private TestListResolver( boolean hasIncludedMethodPatterns, boolean hasExcludedMethodPatterns, - Set includedPatterns, Set excludedPatterns ) - { + private TestListResolver( + boolean hasIncludedMethodPatterns, + boolean hasExcludedMethodPatterns, + Set includedPatterns, + Set excludedPatterns) { this.includedPatterns = includedPatterns; this.excludedPatterns = excludedPatterns; this.hasIncludedMethodPatterns = hasIncludedMethodPatterns; this.hasExcludedMethodPatterns = hasExcludedMethodPatterns; } - public static TestListResolver newTestListResolver( Set includedPatterns, - Set excludedPatterns ) - { - return new TestListResolver( haveMethodPatterns( includedPatterns ), haveMethodPatterns( excludedPatterns ), - includedPatterns, excludedPatterns ); + public static TestListResolver newTestListResolver( + Set includedPatterns, Set excludedPatterns) { + return new TestListResolver( + haveMethodPatterns(includedPatterns), + haveMethodPatterns(excludedPatterns), + includedPatterns, + excludedPatterns); } @Override - public boolean hasIncludedMethodPatterns() - { + public boolean hasIncludedMethodPatterns() { return hasIncludedMethodPatterns; } @Override - public boolean hasExcludedMethodPatterns() - { + public boolean hasExcludedMethodPatterns() { return hasExcludedMethodPatterns; } @Override - public boolean hasMethodPatterns() - { + public boolean hasMethodPatterns() { return hasIncludedMethodPatterns() || hasExcludedMethodPatterns(); } @@ -141,50 +132,40 @@ public boolean hasMethodPatterns() * @return {@code resolver} if {@link TestListResolver#hasMethodPatterns() resolver.hasMethodPatterns()} * returns {@code true}; Otherwise wildcard filter {@code *.class} is returned. */ - public static TestListResolver optionallyWildcardFilter( TestListResolver resolver ) - { + public static TestListResolver optionallyWildcardFilter(TestListResolver resolver) { return resolver.hasMethodPatterns() ? resolver : WILDCARD; } - public static TestListResolver getEmptyTestListResolver() - { + public static TestListResolver getEmptyTestListResolver() { return EMPTY; } - public final boolean isWildcard() - { - return equals( WILDCARD ); + public final boolean isWildcard() { + return equals(WILDCARD); } - public TestFilter and( final TestListResolver another ) - { - return new TestFilter() - { + public TestFilter and(final TestListResolver another) { + return new TestFilter() { @Override - public boolean shouldRun( String testClass, String methodName ) - { - return TestListResolver.this.shouldRun( testClass, methodName ) - && another.shouldRun( testClass, methodName ); + public boolean shouldRun(String testClass, String methodName) { + return TestListResolver.this.shouldRun(testClass, methodName) + && another.shouldRun(testClass, methodName); } }; } - public TestFilter or( final TestListResolver another ) - { - return new TestFilter() - { + public TestFilter or(final TestListResolver another) { + return new TestFilter() { @Override - public boolean shouldRun( String testClass, String methodName ) - { - return TestListResolver.this.shouldRun( testClass, methodName ) - || another.shouldRun( testClass, methodName ); + public boolean shouldRun(String testClass, String methodName) { + return TestListResolver.this.shouldRun(testClass, methodName) + || another.shouldRun(testClass, methodName); } }; } - public boolean shouldRun( Class testClass, String methodName ) - { - return shouldRun( toClassFileName( testClass ), methodName ); + public boolean shouldRun(Class testClass, String methodName) { + return shouldRun(toClassFileName(testClass), methodName); } /** @@ -194,38 +175,26 @@ public boolean shouldRun( Class testClass, String methodName ) * @param methodName real test-method name; or null */ @Override - public boolean shouldRun( String testClassFile, String methodName ) - { - if ( isEmpty() || isBlank( testClassFile ) && isBlank( methodName ) ) - { + public boolean shouldRun(String testClassFile, String methodName) { + if (isEmpty() || isBlank(testClassFile) && isBlank(methodName)) { return true; - } - else - { + } else { boolean shouldRun = false; - if ( getIncludedPatterns().isEmpty() ) - { + if (getIncludedPatterns().isEmpty()) { shouldRun = true; - } - else - { - for ( ResolvedTest filter : getIncludedPatterns() ) - { - if ( filter.matchAsInclusive( testClassFile, methodName ) ) - { + } else { + for (ResolvedTest filter : getIncludedPatterns()) { + if (filter.matchAsInclusive(testClassFile, methodName)) { shouldRun = true; break; } } } - if ( shouldRun ) - { - for ( ResolvedTest filter : getExcludedPatterns() ) - { - if ( filter.matchAsExclusive( testClassFile, methodName ) ) - { + if (shouldRun) { + for (ResolvedTest filter : getExcludedPatterns()) { + if (filter.matchAsExclusive(testClassFile, methodName)) { shouldRun = false; break; } @@ -236,216 +205,179 @@ public boolean shouldRun( String testClassFile, String methodName ) } @Override - public boolean isEmpty() - { - return equals( EMPTY ); + public boolean isEmpty() { + return equals(EMPTY); } @Override - public String getPluginParameterTest() - { - String aggregatedTest = aggregatedTest( "", getIncludedPatterns() ); + public String getPluginParameterTest() { + String aggregatedTest = aggregatedTest("", getIncludedPatterns()); - if ( isNotBlank( aggregatedTest ) && !getExcludedPatterns().isEmpty() ) - { + if (isNotBlank(aggregatedTest) && !getExcludedPatterns().isEmpty()) { aggregatedTest += ", "; } - aggregatedTest += aggregatedTest( "!", getExcludedPatterns() ); + aggregatedTest += aggregatedTest("!", getExcludedPatterns()); return aggregatedTest.isEmpty() ? "" : aggregatedTest; } @Override - public Set getIncludedPatterns() - { + public Set getIncludedPatterns() { return includedPatterns; } @Override - public Set getExcludedPatterns() - { + public Set getExcludedPatterns() { return excludedPatterns; } @Override - public boolean equals( Object o ) - { - if ( this == o ) - { + public boolean equals(Object o) { + if (this == o) { return true; } - if ( o == null || getClass() != o.getClass() ) - { + if (o == null || getClass() != o.getClass()) { return false; } TestListResolver that = (TestListResolver) o; - return getIncludedPatterns().equals( that.getIncludedPatterns() ) - && getExcludedPatterns().equals( that.getExcludedPatterns() ); - + return getIncludedPatterns().equals(that.getIncludedPatterns()) + && getExcludedPatterns().equals(that.getExcludedPatterns()); } @Override - public int hashCode() - { + public int hashCode() { int result = getIncludedPatterns().hashCode(); result = 31 * result + getExcludedPatterns().hashCode(); return result; } @Override - public String toString() - { + public String toString() { return getPluginParameterTest(); } - public static String toClassFileName( Class test ) - { - return test == null ? null : toClassFileName( test.getName() ); + public static String toClassFileName(Class test) { + return test == null ? null : toClassFileName(test.getName()); } - public static String toClassFileName( String fullyQualifiedTestClass ) - { + public static String toClassFileName(String fullyQualifiedTestClass) { return fullyQualifiedTestClass == null - ? null - : fullyQualifiedTestClass.replace( '.', '/' ) + JAVA_CLASS_FILE_EXTENSION; + ? null + : fullyQualifiedTestClass.replace('.', '/') + JAVA_CLASS_FILE_EXTENSION; } - static String removeExclamationMark( String s ) - { - return !s.isEmpty() && s.charAt( 0 ) == '!' ? s.substring( 1 ) : s; + static String removeExclamationMark(String s) { + return !s.isEmpty() && s.charAt(0) == '!' ? s.substring(1) : s; } - private static void updatedFilters( boolean isExcluded, ResolvedTest test, IncludedExcludedPatterns patterns, - Collection includedFilters, - Collection excludedFilters ) - { - if ( isExcluded ) - { - excludedFilters.add( test ); + private static void updatedFilters( + boolean isExcluded, + ResolvedTest test, + IncludedExcludedPatterns patterns, + Collection includedFilters, + Collection excludedFilters) { + if (isExcluded) { + excludedFilters.add(test); patterns.hasExcludedMethodPatterns |= test.hasTestMethodPattern(); - } - else - { - includedFilters.add( test ); + } else { + includedFilters.add(test); patterns.hasIncludedMethodPatterns |= test.hasTestMethodPattern(); } } - private static String aggregatedTest( String testPrefix, Set tests ) - { + private static String aggregatedTest(String testPrefix, Set tests) { StringBuilder aggregatedTest = new StringBuilder(); - for ( ResolvedTest test : tests ) - { + for (ResolvedTest test : tests) { String readableTest = test.toString(); - if ( !readableTest.isEmpty() ) - { - if ( aggregatedTest.length() != 0 ) - { - aggregatedTest.append( ", " ); + if (!readableTest.isEmpty()) { + if (aggregatedTest.length() != 0) { + aggregatedTest.append(", "); } - aggregatedTest.append( testPrefix ) - .append( readableTest ); + aggregatedTest.append(testPrefix).append(readableTest); } } return aggregatedTest.toString(); } - private static Collection mergeIncludedAndExcludedTests( Collection included, - Collection excluded ) - { - ArrayList incExc = new ArrayList<>( included ); - incExc.removeAll( Collections.singleton( null ) ); - for ( String exc : excluded ) - { - if ( exc != null ) - { + private static Collection mergeIncludedAndExcludedTests( + Collection included, Collection excluded) { + ArrayList incExc = new ArrayList<>(included); + incExc.removeAll(Collections.singleton(null)); + for (String exc : excluded) { + if (exc != null) { exc = exc.trim(); - if ( !exc.isEmpty() ) - { - if ( exc.contains( "!" ) ) - { - throw new IllegalArgumentException( "Exclamation mark not expected in 'exclusion': " + exc ); + if (!exc.isEmpty()) { + if (exc.contains("!")) { + throw new IllegalArgumentException("Exclamation mark not expected in 'exclusion': " + exc); } - exc = exc.replace( ",", ",!" ); - if ( !exc.startsWith( "!" ) ) - { + exc = exc.replace(",", ",!"); + if (!exc.startsWith("!")) { exc = "!" + exc; } - incExc.add( exc ); + incExc.add(exc); } } } return incExc; } - static boolean isRegexPrefixedPattern( String pattern ) - { - int indexOfRegex = pattern.indexOf( REGEX_HANDLER_PREFIX ); + static boolean isRegexPrefixedPattern(String pattern) { + int indexOfRegex = pattern.indexOf(REGEX_HANDLER_PREFIX); int prefixLength = REGEX_HANDLER_PREFIX.length(); - if ( indexOfRegex != -1 ) - { - if ( indexOfRegex != 0 - || !pattern.endsWith( PATTERN_HANDLER_SUFFIX ) - || !isRegexMinLength( pattern ) - || pattern.indexOf( REGEX_HANDLER_PREFIX, prefixLength ) != -1 ) - { + if (indexOfRegex != -1) { + if (indexOfRegex != 0 + || !pattern.endsWith(PATTERN_HANDLER_SUFFIX) + || !isRegexMinLength(pattern) + || pattern.indexOf(REGEX_HANDLER_PREFIX, prefixLength) != -1) { String msg = "Illegal test|includes|excludes regex '%s'. Expected %%regex[class#method] " - + "or !%%regex[class#method] " + "with optional class or #method."; - throw new IllegalArgumentException( String.format( msg, pattern ) ); + + "or !%%regex[class#method] " + "with optional class or #method."; + throw new IllegalArgumentException(String.format(msg, pattern)); } return true; - } - else - { + } else { return false; } } - - static boolean isRegexMinLength( String pattern ) - { - //todo bug in maven-shared-utils: '+1' should not appear in the condition - //todo cannot reuse code from SelectorUtils.java because method isRegexPrefixedPattern is in private package. + static boolean isRegexMinLength(String pattern) { + // todo bug in maven-shared-utils: '+1' should not appear in the condition + // todo cannot reuse code from SelectorUtils.java because method isRegexPrefixedPattern is in private package. return pattern.length() > REGEX_HANDLER_PREFIX.length() + PATTERN_HANDLER_SUFFIX.length() + 1; } - static String[] unwrapRegex( String regex ) - { + static String[] unwrapRegex(String regex) { regex = regex.trim(); int from = REGEX_HANDLER_PREFIX.length(); int to = regex.length() - PATTERN_HANDLER_SUFFIX.length(); - return unwrap( regex.substring( from, to ) ); + return unwrap(regex.substring(from, to)); } - static String[] unwrap( final String request ) - { - final String[] classAndMethod = { "", "" }; - final int indexOfHash = request.indexOf( '#' ); - if ( indexOfHash == -1 ) - { + static String[] unwrap(final String request) { + final String[] classAndMethod = {"", ""}; + final int indexOfHash = request.indexOf('#'); + if (indexOfHash == -1) { classAndMethod[0] = request.trim(); - } - else - { - classAndMethod[0] = request.substring( 0, indexOfHash ).trim(); - classAndMethod[1] = request.substring( 1 + indexOfHash ).trim(); + } else { + classAndMethod[0] = request.substring(0, indexOfHash).trim(); + classAndMethod[1] = request.substring(1 + indexOfHash).trim(); } return classAndMethod; } - static void nonRegexClassAndMethods( String clazz, String methods, boolean isExcluded, - IncludedExcludedPatterns patterns, - Collection includedFilters, Collection excludedFilters ) - { - for ( String method : split( methods, "+" ) ) - { + static void nonRegexClassAndMethods( + String clazz, + String methods, + boolean isExcluded, + IncludedExcludedPatterns patterns, + Collection includedFilters, + Collection excludedFilters) { + for (String method : split(methods, "+")) { method = method.trim(); - ResolvedTest test = new ResolvedTest( clazz, method, false ); - if ( !test.isEmpty() ) - { - updatedFilters( isExcluded, test, patterns, includedFilters, excludedFilters ); + ResolvedTest test = new ResolvedTest(clazz, method, false); + if (!test.isEmpty()) { + updatedFilters(isExcluded, test, patterns, includedFilters, excludedFilters); } } } @@ -453,57 +385,44 @@ static void nonRegexClassAndMethods( String clazz, String methods, boolean isExc /** * Requires trimmed {@code request} been not equal to "!". */ - static void resolveTestRequest( String request, IncludedExcludedPatterns patterns, - Collection includedFilters, Collection excludedFilters ) - { - final boolean isExcluded = request.startsWith( "!" ); + static void resolveTestRequest( + String request, + IncludedExcludedPatterns patterns, + Collection includedFilters, + Collection excludedFilters) { + final boolean isExcluded = request.startsWith("!"); ResolvedTest test = null; - request = removeExclamationMark( request ); - if ( isRegexPrefixedPattern( request ) ) - { - final String[] unwrapped = unwrapRegex( request ); + request = removeExclamationMark(request); + if (isRegexPrefixedPattern(request)) { + final String[] unwrapped = unwrapRegex(request); final boolean hasClass = !unwrapped[0].isEmpty(); final boolean hasMethod = !unwrapped[1].isEmpty(); - if ( hasClass && hasMethod ) - { - test = new ResolvedTest( unwrapped[0], unwrapped[1], true ); - } - else if ( hasClass ) - { - test = new ResolvedTest( CLASS, unwrapped[0], true ); - } - else if ( hasMethod ) - { - test = new ResolvedTest( METHOD, unwrapped[1], true ); - } - } - else - { - final int indexOfMethodSeparator = request.indexOf( '#' ); - if ( indexOfMethodSeparator == -1 ) - { - test = new ResolvedTest( CLASS, request, false ); + if (hasClass && hasMethod) { + test = new ResolvedTest(unwrapped[0], unwrapped[1], true); + } else if (hasClass) { + test = new ResolvedTest(CLASS, unwrapped[0], true); + } else if (hasMethod) { + test = new ResolvedTest(METHOD, unwrapped[1], true); } - else - { - String clazz = request.substring( 0, indexOfMethodSeparator ); - String methods = request.substring( 1 + indexOfMethodSeparator ); - nonRegexClassAndMethods( clazz, methods, isExcluded, patterns, includedFilters, excludedFilters ); + } else { + final int indexOfMethodSeparator = request.indexOf('#'); + if (indexOfMethodSeparator == -1) { + test = new ResolvedTest(CLASS, request, false); + } else { + String clazz = request.substring(0, indexOfMethodSeparator); + String methods = request.substring(1 + indexOfMethodSeparator); + nonRegexClassAndMethods(clazz, methods, isExcluded, patterns, includedFilters, excludedFilters); } } - if ( test != null && !test.isEmpty() ) - { - updatedFilters( isExcluded, test, patterns, includedFilters, excludedFilters ); + if (test != null && !test.isEmpty()) { + updatedFilters(isExcluded, test, patterns, includedFilters, excludedFilters); } } - private static boolean haveMethodPatterns( Set patterns ) - { - for ( ResolvedTest pattern : patterns ) - { - if ( pattern.hasTestMethodPattern() ) - { + private static boolean haveMethodPatterns(Set patterns) { + for (ResolvedTest pattern : patterns) { + if (pattern.hasTestMethodPattern()) { return true; } } diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/api/testset/TestRequest.java b/surefire-api/src/main/java/org/apache/maven/surefire/api/testset/TestRequest.java index 80631f4ba1..e5fe6814cf 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/api/testset/TestRequest.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/api/testset/TestRequest.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.api.testset; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.api.testset; import java.io.File; import java.util.ArrayList; @@ -28,8 +27,7 @@ * * @author Kristian Rosenvold */ -public class TestRequest -{ +public class TestRequest { private final List suiteXmlFiles; private final File testSourceDirectory; @@ -38,15 +36,13 @@ public class TestRequest private final int rerunFailingTestsCount; - public TestRequest( List suiteXmlFiles, File testSourceDirectory, TestListResolver requestedTests ) - { - this( createFiles( suiteXmlFiles ), testSourceDirectory, requestedTests, 0 ); + public TestRequest(List suiteXmlFiles, File testSourceDirectory, TestListResolver requestedTests) { + this(createFiles(suiteXmlFiles), testSourceDirectory, requestedTests, 0); } - public TestRequest( List suiteXmlFiles, File testSourceDirectory, TestListResolver requestedTests, - int rerunFailingTestsCount ) - { - this.suiteXmlFiles = createFiles( suiteXmlFiles ); + public TestRequest( + List suiteXmlFiles, File testSourceDirectory, TestListResolver requestedTests, int rerunFailingTestsCount) { + this.suiteXmlFiles = createFiles(suiteXmlFiles); this.testSourceDirectory = testSourceDirectory; this.requestedTests = requestedTests; this.rerunFailingTestsCount = rerunFailingTestsCount; @@ -57,8 +53,7 @@ public TestRequest( List suiteXmlFiles, File testSourceDirectory, TestListResolv * * @return A list of java.io.File objects. */ - public List getSuiteXmlFiles() - { + public List getSuiteXmlFiles() { return suiteXmlFiles; } @@ -67,8 +62,7 @@ public List getSuiteXmlFiles() * * @return A file pointing to test sources */ - public File getTestSourceDirectory() - { + public File getTestSourceDirectory() { return testSourceDirectory; } @@ -77,8 +71,7 @@ public File getTestSourceDirectory() * * @return filter */ - public TestListResolver getTestListResolver() - { + public TestListResolver getTestListResolver() { return requestedTests; } @@ -87,25 +80,20 @@ public TestListResolver getTestListResolver() * * @return The int parameter to indicate how many times to rerun failing tests */ - public int getRerunFailingTestsCount() - { + public int getRerunFailingTestsCount() { return rerunFailingTestsCount; } - private static List createFiles( List suiteXmlFiles ) - { - if ( suiteXmlFiles != null ) - { + private static List createFiles(List suiteXmlFiles) { + if (suiteXmlFiles != null) { List files = new ArrayList<>(); Object element; - for ( Object suiteXmlFile : suiteXmlFiles ) - { + for (Object suiteXmlFile : suiteXmlFiles) { element = suiteXmlFile; - files.add( element instanceof String ? new File( (String) element ) : (File) element ); + files.add(element instanceof String ? new File((String) element) : (File) element); } return files; } return null; } - } diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/api/testset/TestSetFailedException.java b/surefire-api/src/main/java/org/apache/maven/surefire/api/testset/TestSetFailedException.java index 0005eb6c21..a49df73a75 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/api/testset/TestSetFailedException.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/api/testset/TestSetFailedException.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.api.testset; /* @@ -19,15 +37,12 @@ * under the License. */ - /** * Exception that indicates a test failed. * * @author Bill Venners */ -public class TestSetFailedException - extends Exception -{ +public class TestSetFailedException extends Exception { /** * Creates {@code TestSetFailedException} with a detail message. @@ -36,9 +51,8 @@ public class TestSetFailedException * {@code null}. If {@code null} is passed, the {@link #getMessage} * method will return an empty {@link String string}. */ - public TestSetFailedException( String message ) - { - super( message ); + public TestSetFailedException(String message) { + super(message); } /** @@ -53,9 +67,8 @@ public TestSetFailedException( String message ) * @param cause the cause, which is saved for later retrieval by the {@link #getCause} method. * (A null value is permitted, and indicates that the cause is nonexistent or unknown.) */ - public TestSetFailedException( String message, Throwable cause ) - { - super( message, cause ); + public TestSetFailedException(String message, Throwable cause) { + super(message, cause); } /** @@ -64,8 +77,7 @@ public TestSetFailedException( String message, Throwable cause ) * * @param cause The cause */ - public TestSetFailedException( Throwable cause ) - { - super( cause == null ? "" : cause.toString(), cause ); + public TestSetFailedException(Throwable cause) { + super(cause == null ? "" : cause.toString(), cause); } } diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/api/util/CloseableIterator.java b/surefire-api/src/main/java/org/apache/maven/surefire/api/util/CloseableIterator.java index 6328d6c331..c197461522 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/api/util/CloseableIterator.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/api/util/CloseableIterator.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.api.util; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.api.util; import java.util.Iterator; import java.util.NoSuchElementException; @@ -34,53 +33,43 @@ * @author Tibor Digana (tibor17) * @since 2.19.1 */ -public abstract class CloseableIterator - implements Iterator -{ +public abstract class CloseableIterator implements Iterator { private Boolean finishCurrentIteration; protected abstract boolean isClosed(); + protected abstract boolean doHasNext(); + protected abstract T doNext(); + protected abstract void doRemove(); @Override - public boolean hasNext() - { + public boolean hasNext() { popMarker(); return !finishCurrentIteration && doHasNext(); } @Override - public T next() - { - try - { - if ( popMarker() && finishCurrentIteration ) - { - throw new NoSuchElementException( "iterator closed" ); + public T next() { + try { + if (popMarker() && finishCurrentIteration) { + throw new NoSuchElementException("iterator closed"); } return doNext(); - } - finally - { + } finally { finishCurrentIteration = null; } } @Override - public void remove() - { - try - { - if ( popMarker() && finishCurrentIteration ) - { - throw new IllegalStateException( "iterator closed" ); + public void remove() { + try { + if (popMarker() && finishCurrentIteration) { + throw new IllegalStateException("iterator closed"); } doRemove(); - } - finally - { + } finally { finishCurrentIteration = null; } } @@ -88,10 +77,8 @@ public void remove() /** * @return {@code true} if marker changed from NULL to anything */ - private boolean popMarker() - { - if ( finishCurrentIteration == null ) - { + private boolean popMarker() { + if (finishCurrentIteration == null) { finishCurrentIteration = isClosed(); return true; } diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/api/util/DefaultDirectoryScanner.java b/surefire-api/src/main/java/org/apache/maven/surefire/api/util/DefaultDirectoryScanner.java index fcdba6bd76..c4d4bb3427 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/api/util/DefaultDirectoryScanner.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/api/util/DefaultDirectoryScanner.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.api.util; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,8 +16,7 @@ * specific language governing permissions and limitations * under the License. */ - -import org.apache.maven.surefire.api.filter.SpecificTestClassFilter; +package org.apache.maven.surefire.api.util; import java.io.File; import java.util.ArrayList; @@ -28,6 +25,8 @@ import java.util.List; import java.util.Set; +import org.apache.maven.surefire.api.filter.SpecificTestClassFilter; + /** * Scans directories looking for tests. * @@ -35,11 +34,9 @@ * @author Kristian Rosenvold */ @Deprecated -public class DefaultDirectoryScanner - implements DirectoryScanner -{ +public class DefaultDirectoryScanner implements DirectoryScanner { - private static final String FS = System.getProperty( "file.separator" ); + private static final String FS = System.getProperty("file.separator"); private static final String[] EMPTY_STRING_ARRAY = new String[0]; @@ -55,9 +52,8 @@ public class DefaultDirectoryScanner private final List specificTests; - public DefaultDirectoryScanner( File basedir, List includes, List excludes, - List specificTests ) - { + public DefaultDirectoryScanner( + File basedir, List includes, List excludes, List specificTests) { this.basedir = basedir; this.includes = includes; this.excludes = excludes; @@ -65,100 +61,81 @@ public DefaultDirectoryScanner( File basedir, List includes, List> result = new LinkedHashSet<>(); - String[] specific = specificTests == null ? new String[0] : processIncludesExcludes( specificTests ); - SpecificTestClassFilter specificTestFilter = new SpecificTestClassFilter( specific ); + String[] specific = specificTests == null ? new String[0] : processIncludesExcludes(specificTests); + SpecificTestClassFilter specificTestFilter = new SpecificTestClassFilter(specific); - for ( String className : testClassNames ) - { - Class testClass = loadClass( classLoader, className ); + for (String className : testClassNames) { + Class testClass = loadClass(classLoader, className); - if ( !specificTestFilter.accept( testClass ) ) - { + if (!specificTestFilter.accept(testClass)) { // FIXME: Log this somehow! continue; } - if ( scannerFilter == null || scannerFilter.accept( testClass ) ) - { - result.add( testClass ); + if (scannerFilter == null || scannerFilter.accept(testClass)) { + result.add(testClass); } } - return new TestsToRun( result ); + return new TestsToRun(result); } - private static Class loadClass( ClassLoader classLoader, String className ) - { - try - { - return classLoader.loadClass( className ); - } - catch ( ClassNotFoundException e ) - { - throw new RuntimeException( "Unable to create test class '" + className + "'", e ); + private static Class loadClass(ClassLoader classLoader, String className) { + try { + return classLoader.loadClass(className); + } catch (ClassNotFoundException e) { + throw new RuntimeException("Unable to create test class '" + className + "'", e); } } - String[] collectTests() - { + String[] collectTests() { String[] tests = EMPTY_STRING_ARRAY; - if ( basedir.exists() ) - { + if (basedir.exists()) { org.apache.maven.surefire.shared.utils.io.DirectoryScanner scanner = - new org.apache.maven.surefire.shared.utils.io.DirectoryScanner(); + new org.apache.maven.surefire.shared.utils.io.DirectoryScanner(); - scanner.setBasedir( basedir ); + scanner.setBasedir(basedir); - if ( includes != null ) - { - scanner.setIncludes( processIncludesExcludes( includes ) ); + if (includes != null) { + scanner.setIncludes(processIncludesExcludes(includes)); } - if ( excludes != null ) - { - scanner.setExcludes( processIncludesExcludes( excludes ) ); + if (excludes != null) { + scanner.setExcludes(processIncludesExcludes(excludes)); } scanner.scan(); tests = scanner.getIncludedFiles(); - for ( int i = 0; i < tests.length; i++ ) - { + for (int i = 0; i < tests.length; i++) { String test = tests[i]; - test = test.substring( 0, test.indexOf( "." ) ); - tests[i] = test.replace( FS.charAt( 0 ), '.' ); + test = test.substring(0, test.indexOf(".")); + tests[i] = test.replace(FS.charAt(0), '.'); } } return tests; } - private static String[] processIncludesExcludes( List list ) - { + private static String[] processIncludesExcludes(List list) { List newList = new ArrayList<>(); - for ( String include : list ) - { - String[] includes = include.split( "," ); - Collections.addAll( newList, includes ); + for (String include : list) { + String[] includes = include.split(","); + Collections.addAll(newList, includes); } String[] incs = new String[newList.size()]; - for ( int i = 0; i < incs.length; i++ ) - { - String inc = newList.get( i ); - if ( inc.endsWith( JAVA_SOURCE_FILE_EXTENSION ) ) - { - inc = inc.substring( 0, inc.lastIndexOf( JAVA_SOURCE_FILE_EXTENSION ) ) + JAVA_CLASS_FILE_EXTENSION; + for (int i = 0; i < incs.length; i++) { + String inc = newList.get(i); + if (inc.endsWith(JAVA_SOURCE_FILE_EXTENSION)) { + inc = inc.substring(0, inc.lastIndexOf(JAVA_SOURCE_FILE_EXTENSION)) + JAVA_CLASS_FILE_EXTENSION; } incs[i] = inc; - } return incs; } - } diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/api/util/DefaultRunOrderCalculator.java b/surefire-api/src/main/java/org/apache/maven/surefire/api/util/DefaultRunOrderCalculator.java index 79a4618291..4e79468316 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/api/util/DefaultRunOrderCalculator.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/api/util/DefaultRunOrderCalculator.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.api.util; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,9 +16,7 @@ * specific language governing permissions and limitations * under the License. */ - -import org.apache.maven.surefire.api.runorder.RunEntryStatisticsMap; -import org.apache.maven.surefire.api.testset.RunOrderParameters; +package org.apache.maven.surefire.api.util; import java.util.ArrayList; import java.util.Calendar; @@ -30,14 +26,15 @@ import java.util.List; import java.util.Random; +import org.apache.maven.surefire.api.runorder.RunEntryStatisticsMap; +import org.apache.maven.surefire.api.testset.RunOrderParameters; + /** * Applies the final runorder of the tests * * @author Kristian Rosenvold */ -public class DefaultRunOrderCalculator - implements RunOrderCalculator -{ +public class DefaultRunOrderCalculator implements RunOrderCalculator { private final Comparator> sortOrder; private final RunOrder[] runOrder; @@ -48,87 +45,66 @@ public class DefaultRunOrderCalculator private final Random random; - public DefaultRunOrderCalculator( RunOrderParameters runOrderParameters, int threadCount ) - { + public DefaultRunOrderCalculator(RunOrderParameters runOrderParameters, int threadCount) { this.runOrderParameters = runOrderParameters; this.threadCount = threadCount; this.runOrder = runOrderParameters.getRunOrder(); - this.sortOrder = this.runOrder.length > 0 ? getSortOrderComparator( this.runOrder[0] ) : null; + this.sortOrder = this.runOrder.length > 0 ? getSortOrderComparator(this.runOrder[0]) : null; Long runOrderRandomSeed = runOrderParameters.getRunOrderRandomSeed(); - random = new Random( runOrderRandomSeed == null ? System.nanoTime() : runOrderRandomSeed ); + random = new Random(runOrderRandomSeed == null ? System.nanoTime() : runOrderRandomSeed); } @Override - @SuppressWarnings( "checkstyle:magicnumber" ) - public TestsToRun orderTestClasses( TestsToRun scannedClasses ) - { - List> result = new ArrayList<>( 512 ); - - for ( Class scannedClass : scannedClasses ) - { - result.add( scannedClass ); + @SuppressWarnings("checkstyle:magicnumber") + public TestsToRun orderTestClasses(TestsToRun scannedClasses) { + List> result = new ArrayList<>(512); + + for (Class scannedClass : scannedClasses) { + result.add(scannedClass); } - orderTestClasses( result, runOrder.length != 0 ? runOrder[0] : null ); - return new TestsToRun( new LinkedHashSet<>( result ) ); + orderTestClasses(result, runOrder.length != 0 ? runOrder[0] : null); + return new TestsToRun(new LinkedHashSet<>(result)); } - private void orderTestClasses( List> testClasses, RunOrder runOrder ) - { - if ( RunOrder.RANDOM.equals( runOrder ) ) - { - Collections.shuffle( testClasses, random ); - } - else if ( RunOrder.FAILEDFIRST.equals( runOrder ) ) - { - RunEntryStatisticsMap stat = RunEntryStatisticsMap.fromFile( runOrderParameters.getRunStatisticsFile() ); - List> prioritized = stat.getPrioritizedTestsByFailureFirst( testClasses ); + private void orderTestClasses(List> testClasses, RunOrder runOrder) { + if (RunOrder.RANDOM.equals(runOrder)) { + Collections.shuffle(testClasses, random); + } else if (RunOrder.FAILEDFIRST.equals(runOrder)) { + RunEntryStatisticsMap stat = RunEntryStatisticsMap.fromFile(runOrderParameters.getRunStatisticsFile()); + List> prioritized = stat.getPrioritizedTestsByFailureFirst(testClasses); testClasses.clear(); - testClasses.addAll( prioritized ); + testClasses.addAll(prioritized); - } - else if ( RunOrder.BALANCED.equals( runOrder ) ) - { - RunEntryStatisticsMap stat = RunEntryStatisticsMap.fromFile( runOrderParameters.getRunStatisticsFile() ); - List> prioritized = stat.getPrioritizedTestsClassRunTime( testClasses, threadCount ); + } else if (RunOrder.BALANCED.equals(runOrder)) { + RunEntryStatisticsMap stat = RunEntryStatisticsMap.fromFile(runOrderParameters.getRunStatisticsFile()); + List> prioritized = stat.getPrioritizedTestsClassRunTime(testClasses, threadCount); testClasses.clear(); - testClasses.addAll( prioritized ); + testClasses.addAll(prioritized); - } - else if ( sortOrder != null ) - { - testClasses.sort( sortOrder ); + } else if (sortOrder != null) { + testClasses.sort(sortOrder); } } - private static Comparator> getSortOrderComparator( RunOrder runOrder ) - { - if ( RunOrder.ALPHABETICAL.equals( runOrder ) ) - { + private static Comparator> getSortOrderComparator(RunOrder runOrder) { + if (RunOrder.ALPHABETICAL.equals(runOrder)) { return getAlphabeticalComparator(); - } - else if ( RunOrder.REVERSE_ALPHABETICAL.equals( runOrder ) ) - { + } else if (RunOrder.REVERSE_ALPHABETICAL.equals(runOrder)) { return getReverseAlphabeticalComparator(); - } - else if ( RunOrder.HOURLY.equals( runOrder ) ) - { - final int hour = Calendar.getInstance().get( Calendar.HOUR_OF_DAY ); - return ( ( hour % 2 ) == 0 ) ? getAlphabeticalComparator() : getReverseAlphabeticalComparator(); - } - else - { + } else if (RunOrder.HOURLY.equals(runOrder)) { + final int hour = Calendar.getInstance().get(Calendar.HOUR_OF_DAY); + return ((hour % 2) == 0) ? getAlphabeticalComparator() : getReverseAlphabeticalComparator(); + } else { return null; } } - private static Comparator> getReverseAlphabeticalComparator() - { - return ( o1, o2 ) -> o2.getName().compareTo( o1.getName() ); + private static Comparator> getReverseAlphabeticalComparator() { + return (o1, o2) -> o2.getName().compareTo(o1.getName()); } - private static Comparator> getAlphabeticalComparator() - { - return Comparator.comparing( Class::getName ); + private static Comparator> getAlphabeticalComparator() { + return Comparator.comparing(Class::getName); } } diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/api/util/DefaultScanResult.java b/surefire-api/src/main/java/org/apache/maven/surefire/api/util/DefaultScanResult.java index bfa41fd064..4ac600596f 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/api/util/DefaultScanResult.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/api/util/DefaultScanResult.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.api.util; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.api.util; import java.util.ArrayList; import java.util.Collections; @@ -29,130 +28,103 @@ /** * @author Kristian Rosenvold */ -public class DefaultScanResult - implements ScanResult -{ +public class DefaultScanResult implements ScanResult { private final List classes; private static final String SCAN_RESULT_NUMBER = "tc."; - public DefaultScanResult( List classes ) - { - this.classes = Collections.unmodifiableList( classes ); + public DefaultScanResult(List classes) { + this.classes = Collections.unmodifiableList(classes); } @Override - public int size() - { + public int size() { return classes.size(); } @Override - public String getClassName( int index ) - { - return classes.get( index ); + public String getClassName(int index) { + return classes.get(index); } @Override - public void writeTo( Map properties ) - { - for ( int i = 0, size = classes.size(); i < size; i++ ) - { - properties.put( SCAN_RESULT_NUMBER + i, classes.get( i ) ); + public void writeTo(Map properties) { + for (int i = 0, size = classes.size(); i < size; i++) { + properties.put(SCAN_RESULT_NUMBER + i, classes.get(i)); } } - public static DefaultScanResult from( Map properties ) - { + public static DefaultScanResult from(Map properties) { List result = new ArrayList<>(); int i = 0; - while ( true ) - { - String item = properties.get( SCAN_RESULT_NUMBER + ( i++ ) ); - if ( item == null ) - { - return new DefaultScanResult( result ); + while (true) { + String item = properties.get(SCAN_RESULT_NUMBER + (i++)); + if (item == null) { + return new DefaultScanResult(result); } - result.add( item ); + result.add(item); } } - public boolean isEmpty() - { + public boolean isEmpty() { return classes.isEmpty(); } - public List getClasses() - { + public List getClasses() { return classes; } @Override - public TestsToRun applyFilter( ScannerFilter scannerFilter, ClassLoader testClassLoader ) - { + public TestsToRun applyFilter(ScannerFilter scannerFilter, ClassLoader testClassLoader) { Set> result = new LinkedHashSet<>(); int size = size(); - for ( int i = 0; i < size; i++ ) - { - String className = getClassName( i ); + for (int i = 0; i < size; i++) { + String className = getClassName(i); - Class testClass = loadClass( testClassLoader, className ); + Class testClass = loadClass(testClassLoader, className); - if ( scannerFilter == null || scannerFilter.accept( testClass ) ) - { - result.add( testClass ); + if (scannerFilter == null || scannerFilter.accept(testClass)) { + result.add(testClass); } } - return new TestsToRun( result ); + return new TestsToRun(result); } @Override - public List> getClassesSkippedByValidation( ScannerFilter scannerFilter, ClassLoader testClassLoader ) - { + public List> getClassesSkippedByValidation(ScannerFilter scannerFilter, ClassLoader testClassLoader) { List> result = new ArrayList<>(); int size = size(); - for ( int i = 0; i < size; i++ ) - { - String className = getClassName( i ); + for (int i = 0; i < size; i++) { + String className = getClassName(i); - Class testClass = loadClass( testClassLoader, className ); + Class testClass = loadClass(testClassLoader, className); - if ( scannerFilter != null && !scannerFilter.accept( testClass ) ) - { - result.add( testClass ); + if (scannerFilter != null && !scannerFilter.accept(testClass)) { + result.add(testClass); } } return result; } - private static Class loadClass( ClassLoader classLoader, String className ) - { - try - { - return classLoader.loadClass( className ); - } - catch ( ClassNotFoundException e ) - { - throw new RuntimeException( "Unable to create test class '" + className + "'", e ); + private static Class loadClass(ClassLoader classLoader, String className) { + try { + return classLoader.loadClass(className); + } catch (ClassNotFoundException e) { + throw new RuntimeException("Unable to create test class '" + className + "'", e); } } - public DefaultScanResult append( DefaultScanResult other ) - { - if ( other != null ) - { - List src = new ArrayList<>( classes ); - src.addAll( other.classes ); - return new DefaultScanResult( src ); - } - else - { + public DefaultScanResult append(DefaultScanResult other) { + if (other != null) { + List src = new ArrayList<>(classes); + src.addAll(other.classes); + return new DefaultScanResult(src); + } else { return this; } } - } diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/api/util/DirectoryScanner.java b/surefire-api/src/main/java/org/apache/maven/surefire/api/util/DirectoryScanner.java index 627a17aa04..0d16b62413 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/api/util/DirectoryScanner.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/api/util/DirectoryScanner.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.api.util; /* @@ -23,8 +41,7 @@ * @author Kristian Rosenvold */ @Deprecated -public interface DirectoryScanner -{ +public interface DirectoryScanner { /** * Locates tests based on scanning directories * @@ -32,5 +49,5 @@ public interface DirectoryScanner * @param scannerFilter The filter to include/exclude test classes * @return The found classes that match the filter */ - TestsToRun locateTestClasses( ClassLoader classLoader, ScannerFilter scannerFilter ); + TestsToRun locateTestClasses(ClassLoader classLoader, ScannerFilter scannerFilter); } diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/api/util/ReflectionUtils.java b/surefire-api/src/main/java/org/apache/maven/surefire/api/util/ReflectionUtils.java index 27821d7e87..34544587b8 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/api/util/ReflectionUtils.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/api/util/ReflectionUtils.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.api.util; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.api.util; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; @@ -26,204 +25,146 @@ /** * @author Kristian Rosenvold */ -public final class ReflectionUtils -{ +public final class ReflectionUtils { private static final Class[] EMPTY_CLASS_ARRAY = new Class[0]; private static final Object[] EMPTY_OBJECT_ARRAY = new Object[0]; - private ReflectionUtils() - { - throw new IllegalStateException( "no instantiable constructor" ); + private ReflectionUtils() { + throw new IllegalStateException("no instantiable constructor"); } - public static Method getMethod( Object instance, String methodName, Class... parameters ) - { - return getMethod( instance.getClass(), methodName, parameters ); + public static Method getMethod(Object instance, String methodName, Class... parameters) { + return getMethod(instance.getClass(), methodName, parameters); } - public static Method getMethod( Class clazz, String methodName, Class... parameters ) - { - try - { - return clazz.getMethod( methodName, parameters ); - } - catch ( NoSuchMethodException e ) - { - throw new RuntimeException( "When finding method " + methodName, e ); + public static Method getMethod(Class clazz, String methodName, Class... parameters) { + try { + return clazz.getMethod(methodName, parameters); + } catch (NoSuchMethodException e) { + throw new RuntimeException("When finding method " + methodName, e); } } - public static Method tryGetMethod( Class clazz, String methodName, Class... parameters ) - { - try - { - return clazz.getMethod( methodName, parameters ); - } - catch ( NoSuchMethodException e ) - { + public static Method tryGetMethod(Class clazz, String methodName, Class... parameters) { + try { + return clazz.getMethod(methodName, parameters); + } catch (NoSuchMethodException e) { return null; } } - public static T invokeGetter( Object instance, String methodName ) - { - return invokeGetter( instance.getClass(), instance, methodName ); + public static T invokeGetter(Object instance, String methodName) { + return invokeGetter(instance.getClass(), instance, methodName); } - public static T invokeGetter( Class instanceType, Object instance, String methodName ) - { - Method method = getMethod( instanceType, methodName ); - return invokeMethodWithArray( instance, method ); + public static T invokeGetter(Class instanceType, Object instance, String methodName) { + Method method = getMethod(instanceType, methodName); + return invokeMethodWithArray(instance, method); } - public static Constructor getConstructor( Class clazz, Class... arguments ) - { - try - { - return clazz.getConstructor( arguments ); - } - catch ( NoSuchMethodException e ) - { - throw new SurefireReflectionException( e ); + public static Constructor getConstructor(Class clazz, Class... arguments) { + try { + return clazz.getConstructor(arguments); + } catch (NoSuchMethodException e) { + throw new SurefireReflectionException(e); } } - public static Constructor tryGetConstructor( Class clazz, Class... arguments ) - { - try - { - return clazz.getConstructor( arguments ); - } - catch ( NoSuchMethodException e ) - { + public static Constructor tryGetConstructor(Class clazz, Class... arguments) { + try { + return clazz.getConstructor(arguments); + } catch (NoSuchMethodException e) { return null; } } - public static T newInstance( Constructor constructor, Object... params ) - { - try - { + public static T newInstance(Constructor constructor, Object... params) { + try { //noinspection unchecked - return (T) constructor.newInstance( params ); - } - catch ( ReflectiveOperationException e ) - { - throw new SurefireReflectionException( e ); + return (T) constructor.newInstance(params); + } catch (ReflectiveOperationException e) { + throw new SurefireReflectionException(e); } } - public static T instantiate( ClassLoader classLoader, String classname, Class returnType ) - { - try - { - Class clazz = loadClass( classLoader, classname ); - return returnType.cast( clazz.newInstance() ); - } - catch ( ReflectiveOperationException e ) - { - throw new SurefireReflectionException( e ); + public static T instantiate(ClassLoader classLoader, String classname, Class returnType) { + try { + Class clazz = loadClass(classLoader, classname); + return returnType.cast(clazz.newInstance()); + } catch (ReflectiveOperationException e) { + throw new SurefireReflectionException(e); } } - public static T instantiateOneArg( ClassLoader classLoader, String className, Class param1Class, - Object param1 ) - { - try - { - Class aClass = loadClass( classLoader, className ); - Constructor constructor = getConstructor( aClass, param1Class ); + public static T instantiateOneArg( + ClassLoader classLoader, String className, Class param1Class, Object param1) { + try { + Class aClass = loadClass(classLoader, className); + Constructor constructor = getConstructor(aClass, param1Class); //noinspection unchecked - return (T) constructor.newInstance( param1 ); - } - catch ( InvocationTargetException e ) - { - throw new SurefireReflectionException( e.getTargetException() ); - } - catch ( ReflectiveOperationException e ) - { - throw new SurefireReflectionException( e ); + return (T) constructor.newInstance(param1); + } catch (InvocationTargetException e) { + throw new SurefireReflectionException(e.getTargetException()); + } catch (ReflectiveOperationException e) { + throw new SurefireReflectionException(e); } } - public static void invokeSetter( Object o, String name, Class value1clazz, Object value ) - { - Method setter = getMethod( o, name, value1clazz ); - invokeSetter( o, setter, value ); + public static void invokeSetter(Object o, String name, Class value1clazz, Object value) { + Method setter = getMethod(o, name, value1clazz); + invokeSetter(o, setter, value); } - public static T invokeSetter( Object target, Method method, Object value ) - { - return invokeMethodWithArray( target, method, value ); + public static T invokeSetter(Object target, Method method, Object value) { + return invokeMethodWithArray(target, method, value); } - public static T invokeMethodWithArray( Object target, Method method, Object... args ) - { - try - { + public static T invokeMethodWithArray(Object target, Method method, Object... args) { + try { //noinspection unchecked - return (T) method.invoke( target, args ); - } - catch ( IllegalAccessException e ) - { - throw new SurefireReflectionException( e ); - } - catch ( InvocationTargetException e ) - { - throw new SurefireReflectionException( e.getTargetException() ); + return (T) method.invoke(target, args); + } catch (IllegalAccessException e) { + throw new SurefireReflectionException(e); + } catch (InvocationTargetException e) { + throw new SurefireReflectionException(e.getTargetException()); } } - public static T invokeMethodWithArray2( Object target, Method method, Object... args ) - throws InvocationTargetException - { - try - { + public static T invokeMethodWithArray2(Object target, Method method, Object... args) + throws InvocationTargetException { + try { //noinspection unchecked - return (T) method.invoke( target, args ); - } - catch ( IllegalAccessException e ) - { - throw new SurefireReflectionException( e ); + return (T) method.invoke(target, args); + } catch (IllegalAccessException e) { + throw new SurefireReflectionException(e); } } - public static T instantiateObject( String className, Class[] types, Object[] params, ClassLoader cl ) - { - Class clazz = loadClass( cl, className ); - final Constructor constructor = getConstructor( clazz, types ); - return newInstance( constructor, params ); + public static T instantiateObject(String className, Class[] types, Object[] params, ClassLoader cl) { + Class clazz = loadClass(cl, className); + final Constructor constructor = getConstructor(clazz, types); + return newInstance(constructor, params); } - @SuppressWarnings( "checkstyle:emptyblock" ) - public static Class tryLoadClass( ClassLoader classLoader, String className ) - { - try - { - return classLoader.loadClass( className ); - } - catch ( NoClassDefFoundError | ClassNotFoundException ignore ) - { + @SuppressWarnings("checkstyle:emptyblock") + public static Class tryLoadClass(ClassLoader classLoader, String className) { + try { + return classLoader.loadClass(className); + } catch (NoClassDefFoundError | ClassNotFoundException ignore) { } return null; } - public static Class loadClass( ClassLoader classLoader, String className ) - { - try - { - return classLoader.loadClass( className ); - } - catch ( NoClassDefFoundError | ClassNotFoundException e ) - { - throw new SurefireReflectionException( e ); + public static Class loadClass(ClassLoader classLoader, String className) { + try { + return classLoader.loadClass(className); + } catch (NoClassDefFoundError | ClassNotFoundException e) { + throw new SurefireReflectionException(e); } } - public static Class reloadClass( ClassLoader classLoader, Object source ) - throws ReflectiveOperationException - { - return classLoader.loadClass( source.getClass().getName() ); + public static Class reloadClass(ClassLoader classLoader, Object source) throws ReflectiveOperationException { + return classLoader.loadClass(source.getClass().getName()); } /** @@ -238,15 +179,13 @@ public static Class reloadClass( ClassLoader classLoader, Object source ) * @throws SurefireReflectionException if the method could not be called or threw an exception. * It has original cause Exception. */ - public static T invokeStaticMethod( Class clazz, String methodName, - Class[] parameterTypes, Object[] parameters ) - { - if ( parameterTypes.length != parameters.length ) - { - throw new IllegalArgumentException( "arguments length do not match" ); + public static T invokeStaticMethod( + Class clazz, String methodName, Class[] parameterTypes, Object[] parameters) { + if (parameterTypes.length != parameters.length) { + throw new IllegalArgumentException("arguments length do not match"); } - Method method = getMethod( clazz, methodName, parameterTypes ); - return invokeMethodWithArray( null, method, parameters ); + Method method = getMethod(clazz, methodName, parameterTypes); + return invokeMethodWithArray(null, method, parameters); } /** @@ -258,33 +197,24 @@ public static T invokeStaticMethod( Class clazz, String methodName, * @return successfully returned value from the last method call; {@code fallback} otherwise * @throws IllegalArgumentException if {@code classes} and {@code noArgMethodNames} have different array length */ - public static T invokeMethodChain( Class[] classesChain, String[] noArgMethodNames, Object fallback ) - { - if ( classesChain.length != noArgMethodNames.length ) - { - throw new IllegalArgumentException( "arrays must have the same length" ); + public static T invokeMethodChain(Class[] classesChain, String[] noArgMethodNames, Object fallback) { + if (classesChain.length != noArgMethodNames.length) { + throw new IllegalArgumentException("arrays must have the same length"); } Object obj = null; - try - { - for ( int i = 0, len = noArgMethodNames.length; i < len; i++ ) - { - if ( i == 0 ) - { - obj = invokeStaticMethod( classesChain[i], noArgMethodNames[i], - EMPTY_CLASS_ARRAY, EMPTY_OBJECT_ARRAY ); - } - else - { - Method method = getMethod( classesChain[i], noArgMethodNames[i] ); - obj = invokeMethodWithArray( obj, method ); + try { + for (int i = 0, len = noArgMethodNames.length; i < len; i++) { + if (i == 0) { + obj = invokeStaticMethod( + classesChain[i], noArgMethodNames[i], EMPTY_CLASS_ARRAY, EMPTY_OBJECT_ARRAY); + } else { + Method method = getMethod(classesChain[i], noArgMethodNames[i]); + obj = invokeMethodWithArray(obj, method); } } //noinspection unchecked return (T) obj; - } - catch ( RuntimeException e ) - { + } catch (RuntimeException e) { //noinspection unchecked return (T) fallback; } diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/api/util/RunOrder.java b/surefire-api/src/main/java/org/apache/maven/surefire/api/util/RunOrder.java index b0d938266a..28334c3a09 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/api/util/RunOrder.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/api/util/RunOrder.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.api.util; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.api.util; import java.util.ArrayList; import java.util.List; @@ -28,23 +27,22 @@ * * @author Stefan Birkner */ -public class RunOrder -{ - public static final RunOrder ALPHABETICAL = new RunOrder( "alphabetical" ); +public class RunOrder { + public static final RunOrder ALPHABETICAL = new RunOrder("alphabetical"); - public static final RunOrder FILESYSTEM = new RunOrder( "filesystem" ); + public static final RunOrder FILESYSTEM = new RunOrder("filesystem"); - public static final RunOrder HOURLY = new RunOrder( "hourly" ); + public static final RunOrder HOURLY = new RunOrder("hourly"); - public static final RunOrder RANDOM = new RunOrder( "random" ); + public static final RunOrder RANDOM = new RunOrder("random"); - public static final RunOrder REVERSE_ALPHABETICAL = new RunOrder( "reversealphabetical" ); + public static final RunOrder REVERSE_ALPHABETICAL = new RunOrder("reversealphabetical"); - public static final RunOrder BALANCED = new RunOrder( "balanced" ); + public static final RunOrder BALANCED = new RunOrder("balanced"); - public static final RunOrder FAILEDFIRST = new RunOrder( "failedfirst" ); + public static final RunOrder FAILEDFIRST = new RunOrder("failedfirst"); - public static final RunOrder[] DEFAULT = new RunOrder[]{ FILESYSTEM }; + public static final RunOrder[] DEFAULT = new RunOrder[] {FILESYSTEM}; /** * Returns the specified RunOrder @@ -52,100 +50,79 @@ public class RunOrder * @param values The runorder string value * @return An array of RunOrder objects, never null */ - public static RunOrder[] valueOfMulti( String values ) - { + public static RunOrder[] valueOfMulti(String values) { List result = new ArrayList<>(); - if ( values != null ) - { - StringTokenizer stringTokenizer = new StringTokenizer( values, "," ); - while ( stringTokenizer.hasMoreTokens() ) - { - result.add( valueOf( stringTokenizer.nextToken() ) ); + if (values != null) { + StringTokenizer stringTokenizer = new StringTokenizer(values, ","); + while (stringTokenizer.hasMoreTokens()) { + result.add(valueOf(stringTokenizer.nextToken())); } } - return result.toArray( new RunOrder[result.size()] ); + return result.toArray(new RunOrder[result.size()]); } - public static RunOrder valueOf( String name ) - { - if ( name == null ) - { + public static RunOrder valueOf(String name) { + if (name == null) { return null; - } - else - { + } else { RunOrder[] runOrders = values(); - for ( RunOrder runOrder : runOrders ) - { - if ( runOrder.matches( name ) ) - { + for (RunOrder runOrder : runOrders) { + if (runOrder.matches(name)) { return runOrder; } } - String errorMessage = createMessageForMissingRunOrder( name ); - throw new IllegalArgumentException( errorMessage ); + String errorMessage = createMessageForMissingRunOrder(name); + throw new IllegalArgumentException(errorMessage); } } - private static String createMessageForMissingRunOrder( String name ) - { + private static String createMessageForMissingRunOrder(String name) { RunOrder[] runOrders = values(); - StringBuilder message = new StringBuilder( "There's no RunOrder with the name " ); - message.append( name ); - message.append( ". Please use one of the following RunOrders: " ); - for ( int i = 0; i < runOrders.length; i++ ) - { - if ( i != 0 ) - { - message.append( ", " ); + StringBuilder message = new StringBuilder("There's no RunOrder with the name "); + message.append(name); + message.append(". Please use one of the following RunOrders: "); + for (int i = 0; i < runOrders.length; i++) { + if (i != 0) { + message.append(", "); } - message.append( runOrders[i] ); + message.append(runOrders[i]); } - message.append( '.' ); + message.append('.'); return message.toString(); } - private static RunOrder[] values() - { - return new RunOrder[]{ ALPHABETICAL, FILESYSTEM, HOURLY, RANDOM, REVERSE_ALPHABETICAL, BALANCED, FAILEDFIRST }; + private static RunOrder[] values() { + return new RunOrder[] {ALPHABETICAL, FILESYSTEM, HOURLY, RANDOM, REVERSE_ALPHABETICAL, BALANCED, FAILEDFIRST}; } - public static String asString( RunOrder[] runOrder ) - { + public static String asString(RunOrder[] runOrder) { StringBuilder stringBuffer = new StringBuilder(); - for ( int i = 0; i < runOrder.length; i++ ) - { - stringBuffer.append( runOrder[i].name ); - if ( i < ( runOrder.length - 1 ) ) - { - stringBuffer.append( "," ); + for (int i = 0; i < runOrder.length; i++) { + stringBuffer.append(runOrder[i].name); + if (i < (runOrder.length - 1)) { + stringBuffer.append(","); } } return stringBuffer.toString(); - } private final String name; - private RunOrder( String name ) - { + private RunOrder(String name) { this.name = name; } - private boolean matches( String anotherName ) - { - return name.equalsIgnoreCase( anotherName ); + private boolean matches(String anotherName) { + return name.equalsIgnoreCase(anotherName); } - public String name() - { + public String name() { return name; } @Override - public String toString() - { + public String toString() { return name; } } diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/api/util/RunOrderCalculator.java b/surefire-api/src/main/java/org/apache/maven/surefire/api/util/RunOrderCalculator.java index a9f99939ed..0c914ca89f 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/api/util/RunOrderCalculator.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/api/util/RunOrderCalculator.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.api.util; /* @@ -22,7 +40,6 @@ /** * @author Kristian Rosenvold */ -public interface RunOrderCalculator -{ - TestsToRun orderTestClasses( TestsToRun scannedClasses ); +public interface RunOrderCalculator { + TestsToRun orderTestClasses(TestsToRun scannedClasses); } diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/api/util/ScanResult.java b/surefire-api/src/main/java/org/apache/maven/surefire/api/util/ScanResult.java index f086a76f0b..bdacddcae6 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/api/util/ScanResult.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/api/util/ScanResult.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.api.util; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.api.util; import java.util.List; import java.util.Map; @@ -25,15 +24,14 @@ /** * @author Kristian Rosenvold */ -public interface ScanResult -{ +public interface ScanResult { int size(); - String getClassName( int index ); + String getClassName(int index); - TestsToRun applyFilter( ScannerFilter scannerFilter, ClassLoader testClassLoader ); + TestsToRun applyFilter(ScannerFilter scannerFilter, ClassLoader testClassLoader); - List> getClassesSkippedByValidation( ScannerFilter scannerFilter, ClassLoader testClassLoader ); + List> getClassesSkippedByValidation(ScannerFilter scannerFilter, ClassLoader testClassLoader); - void writeTo( Map properties ); + void writeTo(Map properties); } diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/api/util/ScannerFilter.java b/surefire-api/src/main/java/org/apache/maven/surefire/api/util/ScannerFilter.java index ec6f492ee9..e80c3538e9 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/api/util/ScannerFilter.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/api/util/ScannerFilter.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.api.util; /* @@ -22,13 +40,12 @@ /** * @author Kristian Rosenvold */ -public interface ScannerFilter -{ +public interface ScannerFilter { /** * Indicates if the class should be accepted by the directory scanner * * @param testClass The class in question * @return true if the class should be part of the directory scan result. */ - boolean accept( Class testClass ); + boolean accept(Class testClass); } diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/api/util/SureFireFileManager.java b/surefire-api/src/main/java/org/apache/maven/surefire/api/util/SureFireFileManager.java index 0f414593ad..ac236724a3 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/api/util/SureFireFileManager.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/api/util/SureFireFileManager.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.api.util; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.api.util; import java.io.File; import java.util.Objects; @@ -29,38 +28,33 @@ * * @author Markus Spann */ -public final class SureFireFileManager -{ +public final class SureFireFileManager { private static TempFileManager instance = create(); - private static TempFileManager create() - { + private static TempFileManager create() { String subDirName = "surefire"; // create directory name suffix from legal chars in the current user name // or a millisecond timestamp as fallback - String userSuffix = Stream.of( "user.name", "USER", "USERNAME" ) - .map( System::getProperty ) - .filter( Objects::nonNull ) - .findFirst() - .map( u -> u.replaceAll( "[^A-Za-z0-9\\-_]", "" ) ) - .map( u -> u.isEmpty() ? null : u ) - .orElse( Long.toString( System.currentTimeMillis() ) ); - - if ( userSuffix != null ) - { + String userSuffix = Stream.of("user.name", "USER", "USERNAME") + .map(System::getProperty) + .filter(Objects::nonNull) + .findFirst() + .map(u -> u.replaceAll("[^A-Za-z0-9\\-_]", "")) + .map(u -> u.isEmpty() ? null : u) + .orElse(Long.toString(System.currentTimeMillis())); + + if (userSuffix != null) { subDirName += "-" + userSuffix; } - TempFileManager tfm = TempFileManager.instance( subDirName ); - tfm.setDeleteOnExit( true ); + TempFileManager tfm = TempFileManager.instance(subDirName); + tfm.setDeleteOnExit(true); return tfm; } - public static File createTempFile( String prefix, String suffix ) - { - return instance.createTempFile( prefix, suffix ); + public static File createTempFile(String prefix, String suffix) { + return instance.createTempFile(prefix, suffix); } - } diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/api/util/SurefireReflectionException.java b/surefire-api/src/main/java/org/apache/maven/surefire/api/util/SurefireReflectionException.java index c29be45952..7bf134cc95 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/api/util/SurefireReflectionException.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/api/util/SurefireReflectionException.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.api.util; /* @@ -26,17 +44,14 @@ * * @author Kristian Rosenvold */ -public class SurefireReflectionException - extends RuntimeException -{ +public class SurefireReflectionException extends RuntimeException { /** * Create a {@link SurefireReflectionException} with the specified cause. The method {@link #getMessage} of this * exception object will return {@code cause == null ? "" : cause.toString()}. * * @param cause The cause of this exception */ - public SurefireReflectionException( Throwable cause ) - { - super( cause == null ? "" : cause.toString(), cause ); + public SurefireReflectionException(Throwable cause) { + super(cause == null ? "" : cause.toString(), cause); } } diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/api/util/TempFileManager.java b/surefire-api/src/main/java/org/apache/maven/surefire/api/util/TempFileManager.java index 63d3b7f3df..ddf98005b4 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/api/util/TempFileManager.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/api/util/TempFileManager.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.api.util; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.api.util; import java.io.File; import java.io.IOException; @@ -43,46 +42,42 @@ * * @author Markus Spann */ -public final class TempFileManager -{ +public final class TempFileManager { - private static final Map INSTANCES = new LinkedHashMap<>(); + private static final Map INSTANCES = new LinkedHashMap<>(); /** An id unique across all file managers used as part of the temporary file's base name. */ - private static final AtomicInteger FILE_ID = new AtomicInteger( 1 ); - private static final String SUFFIX_TMP = ".tmp"; + private static final AtomicInteger FILE_ID = new AtomicInteger(1); + + private static final String SUFFIX_TMP = ".tmp"; - private static Thread shutdownHook; + private static Thread shutdownHook; /** The temporary directory or sub-directory under which temporary files are created. */ - private final File tempDir; + private final File tempDir; /** The fixed base name used between prefix and suffix of temporary files created by this class. */ - private final String baseName; + private final String baseName; /** List of successfully created temporary files. */ - private final List tempFiles; + private final List tempFiles; /** Temporary files are delete on JVM exit if true. */ - private boolean deleteOnExit; + private boolean deleteOnExit; - private TempFileManager( File tempDir ) - { + private TempFileManager(File tempDir) { this.tempDir = tempDir; - this.baseName = DateTimeFormatter.ofPattern( "yyyyMMddHHmmssSSS" ).format( LocalDateTime.now() ); + this.baseName = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS").format(LocalDateTime.now()); this.tempFiles = new ArrayList<>(); } - private static File calcTempDir( String subDirName ) - { - String tempDirName = subDirName == null ? null - : subDirName.trim().isEmpty() ? null : subDirName.trim(); - File tempDirCandidate = tempDirName == null ? new File( getJavaIoTmpDir() ) - : new File( getJavaIoTmpDir(), tempDirName ); + private static File calcTempDir(String subDirName) { + String tempDirName = subDirName == null ? null : subDirName.trim().isEmpty() ? null : subDirName.trim(); + File tempDirCandidate = + tempDirName == null ? new File(getJavaIoTmpDir()) : new File(getJavaIoTmpDir(), tempDirName); return tempDirCandidate; } - public static TempFileManager instance( ) - { - return instance( ( File ) null ); + public static TempFileManager instance() { + return instance((File) null); } /** @@ -90,44 +85,34 @@ public static TempFileManager instance( ) * @param subDirName name of subdirectory * @return instance */ - public static TempFileManager instance( String subDirName ) - { - return instance( calcTempDir( subDirName ) ); + public static TempFileManager instance(String subDirName) { + return instance(calcTempDir(subDirName)); } - public static synchronized TempFileManager instance( File tempDir ) - { + public static synchronized TempFileManager instance(File tempDir) { // on creation of the first instance, register a shutdown hook to delete temporary files of all managers - if ( shutdownHook == null ) - { + if (shutdownHook == null) { ThreadGroup tg = Thread.currentThread().getThreadGroup(); - while ( tg.getParent() != null ) - { + while (tg.getParent() != null) { tg = tg.getParent(); } - shutdownHook = new Thread( tg, TempFileManager::shutdownAll, - TempFileManager.class.getSimpleName() + "-ShutdownHook" ); - Runtime.getRuntime().addShutdownHook( shutdownHook ); + shutdownHook = new Thread( + tg, TempFileManager::shutdownAll, TempFileManager.class.getSimpleName() + "-ShutdownHook"); + Runtime.getRuntime().addShutdownHook(shutdownHook); } - return INSTANCES.computeIfAbsent( - tempDir == null ? new File( getJavaIoTmpDir() ) : tempDir, - TempFileManager::new ); + return INSTANCES.computeIfAbsent(tempDir == null ? new File(getJavaIoTmpDir()) : tempDir, TempFileManager::new); } - public synchronized void deleteAll() - { - tempFiles.forEach( File::delete ); + public synchronized void deleteAll() { + tempFiles.forEach(File::delete); tempFiles.clear(); tempDir.delete(); } - static void shutdownAll() - { - INSTANCES.values().stream() - .filter( TempFileManager::isDeleteOnExit ) - .forEach( TempFileManager::deleteAll ); + static void shutdownAll() { + INSTANCES.values().stream().filter(TempFileManager::isDeleteOnExit).forEach(TempFileManager::deleteAll); } /** @@ -135,8 +120,7 @@ static void shutdownAll() * * @return temporary directory */ - public File getTempDir() - { + public File getTempDir() { return tempDir; } @@ -152,57 +136,45 @@ public File getTempDir() * @param suffix optional file name suffix * @return file object */ - public synchronized File createTempFile( String prefix, String suffix ) - { + public synchronized File createTempFile(String prefix, String suffix) { // use only the file name from the supplied prefix - prefix = prefix == null ? "" : ( new File( prefix ) ).getName(); + prefix = prefix == null ? "" : (new File(prefix)).getName(); suffix = suffix == null ? "" : suffix; - String name = String.join( "-", prefix, baseName + "_" + FILE_ID.getAndIncrement() ) + suffix; - File tempFile = new File( tempDir, name ); - if ( !name.equals( tempFile.getName() ) ) - { - throw new UncheckedIOException( new IOException( "Unable to create temporary file " + tempFile ) ); + String name = String.join("-", prefix, baseName + "_" + FILE_ID.getAndIncrement()) + suffix; + File tempFile = new File(tempDir, name); + if (!name.equals(tempFile.getName())) { + throw new UncheckedIOException(new IOException("Unable to create temporary file " + tempFile)); } - if ( tempFile.exists() || tempFiles.contains( tempFile ) ) - { + if (tempFile.exists() || tempFiles.contains(tempFile)) { // temporary file already exists? Try another name - return createTempFile( prefix, suffix ); - } - else - { + return createTempFile(prefix, suffix); + } else { // create temporary directory - if ( !tempDir.exists() ) - { - if ( !tempDir.mkdirs() ) - { - throw new UncheckedIOException( new IOException( - "Unable to create temporary directory " + tempDir.getAbsolutePath() ) ); + if (!tempDir.exists()) { + if (!tempDir.mkdirs()) { + throw new UncheckedIOException( + new IOException("Unable to create temporary directory " + tempDir.getAbsolutePath())); } } - try - { + try { tempFile.createNewFile(); - } - catch ( IOException ex ) - { - throw new UncheckedIOException( "Unable to create temporary file " + tempFile.getAbsolutePath(), ex ); + } catch (IOException ex) { + throw new UncheckedIOException("Unable to create temporary file " + tempFile.getAbsolutePath(), ex); } - tempFiles.add( tempFile ); + tempFiles.add(tempFile); return tempFile; } } - public File createTempFile( String prefix ) - { - return createTempFile( prefix, SUFFIX_TMP ); + public File createTempFile(String prefix) { + return createTempFile(prefix, SUFFIX_TMP); } - public boolean isDeleteOnExit() - { + public boolean isDeleteOnExit() { return deleteOnExit; } @@ -212,16 +184,15 @@ public boolean isDeleteOnExit() * * @param deleteOnExit delete the file in a shutdown hook on JVM exit */ - public void setDeleteOnExit( boolean deleteOnExit ) - { + public void setDeleteOnExit(boolean deleteOnExit) { this.deleteOnExit = deleteOnExit; } @Override - public String toString() - { - return String.format( "%s[tempDir=%s, deleteOnExit=%s, baseName=%s, tempFiles=%d]", - getClass().getSimpleName(), tempDir, deleteOnExit, baseName, tempFiles.size() ); + public String toString() { + return String.format( + "%s[tempDir=%s, deleteOnExit=%s, baseName=%s, tempFiles=%d]", + getClass().getSimpleName(), tempDir, deleteOnExit, baseName, tempFiles.size()); } /** @@ -229,14 +200,11 @@ public String toString() * * @return path to system temp directory */ - public static String getJavaIoTmpDir() - { - String tmpDir = System.getProperty( "java.io.tmpdir" ); - if ( !tmpDir.endsWith( File.separator ) ) - { + public static String getJavaIoTmpDir() { + String tmpDir = System.getProperty("java.io.tmpdir"); + if (!tmpDir.endsWith(File.separator)) { tmpDir += File.separatorChar; } return tmpDir; } - } diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/api/util/TestsToRun.java b/surefire-api/src/main/java/org/apache/maven/surefire/api/util/TestsToRun.java index 28736ef281..c6a9541b62 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/api/util/TestsToRun.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/api/util/TestsToRun.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.api.util; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.api.util; import java.util.ArrayList; import java.util.Collection; @@ -36,8 +35,7 @@ * * @author Kristian Rosenvold (junit core adaption) */ -public class TestsToRun implements Iterable> -{ +public class TestsToRun implements Iterable> { private final List> locatedClasses; private volatile boolean finished; @@ -49,22 +47,18 @@ public class TestsToRun implements Iterable> * * @param locatedClasses A set of java.lang.Class objects representing tests to run */ - public TestsToRun( Set> locatedClasses ) - { - this.locatedClasses = new ArrayList<>( locatedClasses ); + public TestsToRun(Set> locatedClasses) { + this.locatedClasses = new ArrayList<>(locatedClasses); } - public static TestsToRun fromClass( Class clazz ) - throws TestSetFailedException - { - return new TestsToRun( Collections.>singleton( clazz ) ); + public static TestsToRun fromClass(Class clazz) throws TestSetFailedException { + return new TestsToRun(Collections.>singleton(clazz)); } /** * @return test classes which have been retrieved by {@link TestsToRun#iterator()}. */ - public Iterator> iterated() - { + public Iterator> iterated() { return newWeakIterator(); } @@ -74,85 +68,67 @@ public Iterator> iterated() * @return an unmodifiable iterator */ @Override - public Iterator> iterator() - { + public Iterator> iterator() { return new ClassesIterator(); } - private final class ClassesIterator - extends CloseableIterator> - { + private final class ClassesIterator extends CloseableIterator> { private final Iterator> it = TestsToRun.this.locatedClasses.iterator(); private int iteratedCount; @Override - protected boolean isClosed() - { + protected boolean isClosed() { return TestsToRun.this.isFinished(); } @Override - protected boolean doHasNext() - { + protected boolean doHasNext() { return it.hasNext(); } @Override - protected Class doNext() - { + protected Class doNext() { Class nextTest = it.next(); - TestsToRun.this.iteratedCount = max( ++iteratedCount, TestsToRun.this.iteratedCount ); + TestsToRun.this.iteratedCount = max(++iteratedCount, TestsToRun.this.iteratedCount); return nextTest; } @Override - protected void doRemove() - { - } + protected void doRemove() {} @Override - public void remove() - { - throw new UnsupportedOperationException( "unsupported remove" ); + public void remove() { + throw new UnsupportedOperationException("unsupported remove"); } } - public final void markTestSetFinished() - { + public final void markTestSetFinished() { finished = true; } - public final boolean isFinished() - { + public final boolean isFinished() { return finished; } @Override - public String toString() - { - StringBuilder sb = new StringBuilder( "TestsToRun: [" ); - for ( Class clazz : this ) - { - sb.append( ' ' ) - .append( clazz.getName() ); + public String toString() { + StringBuilder sb = new StringBuilder("TestsToRun: ["); + for (Class clazz : this) { + sb.append(' ').append(clazz.getName()); } - sb.append( ']' ); + sb.append(']'); return sb.toString(); } - public boolean containsAtLeast( int atLeast ) - { - return containsAtLeast( iterator(), atLeast ); + public boolean containsAtLeast(int atLeast) { + return containsAtLeast(iterator(), atLeast); } - private boolean containsAtLeast( Iterator> it, int atLeast ) - { - for ( int i = 0; i < atLeast; i++ ) - { - if ( !it.hasNext() ) - { + private boolean containsAtLeast(Iterator> it, int atLeast) { + for (int i = 0; i < atLeast; i++) { + if (!it.hasNext()) { return false; } @@ -162,33 +138,28 @@ private boolean containsAtLeast( Iterator> it, int atLeast ) return true; } - public boolean containsExactly( int items ) - { + public boolean containsExactly(int items) { Iterator> it = iterator(); - return containsAtLeast( it, items ) && !it.hasNext(); + return containsAtLeast(it, items) && !it.hasNext(); } /** * @return {@code true}, if the classes may be read eagerly. {@code false}, * if the classes must only be read lazy. */ - public boolean allowEagerReading() - { + public boolean allowEagerReading() { return true; } - public Class[] getLocatedClasses() - { - if ( !allowEagerReading() ) - { - throw new IllegalStateException( "Cannot eagerly read" ); + public Class[] getLocatedClasses() { + if (!allowEagerReading()) { + throw new IllegalStateException("Cannot eagerly read"); } Collection> result = new ArrayList<>(); - for ( Class clazz : this ) - { - result.add( clazz ); + for (Class clazz : this) { + result.add(clazz); } - return result.toArray( new Class[result.size()] ); + return result.toArray(new Class[result.size()]); } /** @@ -197,12 +168,9 @@ public Class[] getLocatedClasses() * @param className string used to find the test class * @return Class object with the matching name, null if could not find a class with the matching name */ - public Class getClassByName( String className ) - { - for ( Class clazz : this ) - { - if ( clazz.getName().equals( className ) ) - { + public Class getClassByName(String className) { + for (Class clazz : this) { + if (clazz.getName().equals(className)) { return clazz; } } @@ -213,38 +181,30 @@ public Class getClassByName( String className ) * @return snapshot of tests upon constructs of internal iterator. * Therefore weakly consistent while {@link TestsToRun#iterator()} is being iterated. */ - private Iterator> newWeakIterator() - { - final Iterator> it = locatedClasses.subList( 0, iteratedCount ).iterator(); - return new CloseableIterator>() - { + private Iterator> newWeakIterator() { + final Iterator> it = locatedClasses.subList(0, iteratedCount).iterator(); + return new CloseableIterator>() { @Override - protected boolean isClosed() - { + protected boolean isClosed() { return TestsToRun.this.isFinished(); } @Override - protected boolean doHasNext() - { + protected boolean doHasNext() { return it.hasNext(); } @Override - protected Class doNext() - { + protected Class doNext() { return it.next(); } @Override - protected void doRemove() - { - } + protected void doRemove() {} @Override - public void remove() - { - throw new UnsupportedOperationException( "unsupported remove" ); + public void remove() { + throw new UnsupportedOperationException("unsupported remove"); } }; } diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/api/util/internal/AbstractNoninterruptibleReadableChannel.java b/surefire-api/src/main/java/org/apache/maven/surefire/api/util/internal/AbstractNoninterruptibleReadableChannel.java index 2b83e0f4a7..f1c65f0e31 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/api/util/internal/AbstractNoninterruptibleReadableChannel.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/api/util/internal/AbstractNoninterruptibleReadableChannel.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.api.util.internal; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.api.util.internal; import java.io.IOException; import java.nio.ByteBuffer; @@ -31,44 +30,36 @@ * * @since 3.0.0-M5 */ -abstract class AbstractNoninterruptibleReadableChannel implements ReadableByteChannel -{ +abstract class AbstractNoninterruptibleReadableChannel implements ReadableByteChannel { private volatile boolean open = true; - protected abstract int readImpl( ByteBuffer src ) throws IOException; + protected abstract int readImpl(ByteBuffer src) throws IOException; + protected abstract void closeImpl() throws IOException; @Override - public final int read( ByteBuffer src ) throws IOException - { - if ( !isOpen() ) - { + public final int read(ByteBuffer src) throws IOException { + if (!isOpen()) { throw new ClosedChannelException(); } - if ( !src.hasArray() || src.isReadOnly() ) - { + if (!src.hasArray() || src.isReadOnly()) { throw new NonReadableChannelException(); } - return src.hasRemaining() ? readImpl( src ) : 0; + return src.hasRemaining() ? readImpl(src) : 0; } @Override - public final boolean isOpen() - { + public final boolean isOpen() { return open; } @Override - public final void close() throws IOException - { - try - { + public final void close() throws IOException { + try { closeImpl(); - } - finally - { + } finally { open = false; } } diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/api/util/internal/AbstractNoninterruptibleWritableChannel.java b/surefire-api/src/main/java/org/apache/maven/surefire/api/util/internal/AbstractNoninterruptibleWritableChannel.java index bc16222e17..f7f568654a 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/api/util/internal/AbstractNoninterruptibleWritableChannel.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/api/util/internal/AbstractNoninterruptibleWritableChannel.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.api.util.internal; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.api.util.internal; import java.io.IOException; import java.nio.Buffer; @@ -31,62 +30,54 @@ * * @since 3.0.0-M5 */ -abstract class AbstractNoninterruptibleWritableChannel implements WritableBufferedByteChannel -{ +abstract class AbstractNoninterruptibleWritableChannel implements WritableBufferedByteChannel { private volatile boolean open = true; - protected abstract void writeImpl( ByteBuffer src ) throws IOException; + protected abstract void writeImpl(ByteBuffer src) throws IOException; + protected abstract void closeImpl() throws IOException; + protected abstract void flushImpl() throws IOException; @Override - public final int write( ByteBuffer src ) throws IOException - { - return write( src, true ); + public final int write(ByteBuffer src) throws IOException { + return write(src, true); } @Override - public final void writeBuffered( ByteBuffer src ) throws IOException - { - write( src, false ); + public final void writeBuffered(ByteBuffer src) throws IOException { + write(src, false); } - int write( ByteBuffer src, boolean flush ) throws IOException - { - if ( !isOpen() ) - { + int write(ByteBuffer src, boolean flush) throws IOException { + if (!isOpen()) { throw new ClosedChannelException(); } - if ( !src.hasArray() || src.isReadOnly() ) - { + if (!src.hasArray() || src.isReadOnly()) { throw new NonWritableChannelException(); } - if ( src.remaining() != src.capacity() ) - { - ( (Buffer) src ).flip(); + if (src.remaining() != src.capacity()) { + ((Buffer) src).flip(); } int countWrittenBytes = src.remaining(); - writeImpl( src ); - ( (Buffer) src ).position( ( (Buffer) src ).limit() ); - if ( flush ) - { + writeImpl(src); + ((Buffer) src).position(((Buffer) src).limit()); + if (flush) { flushImpl(); } return countWrittenBytes; } @Override - public final boolean isOpen() - { + public final boolean isOpen() { return open; } @Override - public final void close() throws IOException - { + public final void close() throws IOException { open = false; closeImpl(); } diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/api/util/internal/Channels.java b/surefire-api/src/main/java/org/apache/maven/surefire/api/util/internal/Channels.java index 12fd355692..047a14834d 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/api/util/internal/Channels.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/api/util/internal/Channels.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.api.util.internal; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,9 +16,11 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.api.util.internal; import javax.annotation.Nonnegative; import javax.annotation.Nonnull; + import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.IOException; @@ -49,88 +49,63 @@ * * @since 3.0.0-M5 */ -public final class Channels -{ +public final class Channels { private static final int BUFFER_SIZE = 64 * 1024; - private Channels() - { - throw new IllegalStateException( "no instantiable constructor" ); + private Channels() { + throw new IllegalStateException("no instantiable constructor"); } - public static WritableByteChannel newChannel( @Nonnull OutputStream out ) - { - return newChannel( out, 0 ); + public static WritableByteChannel newChannel(@Nonnull OutputStream out) { + return newChannel(out, 0); } - public static WritableBufferedByteChannel newBufferedChannel( @Nonnull OutputStream out ) - { - return newChannel( out, BUFFER_SIZE ); + public static WritableBufferedByteChannel newBufferedChannel(@Nonnull OutputStream out) { + return newChannel(out, BUFFER_SIZE); } - public static ReadableByteChannel newChannel( @Nonnull final InputStream is ) - { - return newChannel( is, 0 ); + public static ReadableByteChannel newChannel(@Nonnull final InputStream is) { + return newChannel(is, 0); } - public static ReadableByteChannel newBufferedChannel( @Nonnull final InputStream is ) - { - return newChannel( is, BUFFER_SIZE ); + public static ReadableByteChannel newBufferedChannel(@Nonnull final InputStream is) { + return newChannel(is, BUFFER_SIZE); } - public static OutputStream newOutputStream( final AsynchronousByteChannel channel ) - { - return new OutputStream() - { + public static OutputStream newOutputStream(final AsynchronousByteChannel channel) { + return new OutputStream() { @Override - public synchronized void write( byte[] b, int off, int len ) throws IOException - { - if ( off < 0 || off > b.length || len < 0 || off + len > b.length || off + len < 0 ) - { - throw new IndexOutOfBoundsException( - "b.length = " + b.length + ", off = " + off + ", len = " + len ); - } - else if ( len > 0 ) - { - ByteBuffer bb = ByteBuffer.wrap( b, off, len ); - while ( bb.hasRemaining() ) - { - try - { - channel.write( bb ).get(); - } - catch ( ExecutionException e ) - { + public synchronized void write(byte[] b, int off, int len) throws IOException { + if (off < 0 || off > b.length || len < 0 || off + len > b.length || off + len < 0) { + throw new IndexOutOfBoundsException("b.length = " + b.length + ", off = " + off + ", len = " + len); + } else if (len > 0) { + ByteBuffer bb = ByteBuffer.wrap(b, off, len); + while (bb.hasRemaining()) { + try { + channel.write(bb).get(); + } catch (ExecutionException e) { Throwable t = e.getCause(); throw t instanceof IOException - ? (IOException) t - : new IOException( ( t == null ? e : t ).getLocalizedMessage(), t ); - } - catch ( Exception e ) - { - throw new IOException( e.getLocalizedMessage(), e ); + ? (IOException) t + : new IOException((t == null ? e : t).getLocalizedMessage(), t); + } catch (Exception e) { + throw new IOException(e.getLocalizedMessage(), e); } } } } @Override - public void write( int b ) throws IOException - { - write( new byte[] {(byte) b} ); + public void write(int b) throws IOException { + write(new byte[] {(byte) b}); } @Override - public synchronized void close() throws IOException - { - if ( channel.isOpen() ) - { - try - { + public synchronized void close() throws IOException { + if (channel.isOpen()) { + try { channel.close(); - } - catch ( ClosedChannelException e ) - { + } catch (ClosedChannelException e) { // closed channel anyway } } @@ -138,65 +113,45 @@ public synchronized void close() throws IOException }; } - public static InputStream newInputStream( final AsynchronousByteChannel channel ) - { - return new InputStream() - { + public static InputStream newInputStream(final AsynchronousByteChannel channel) { + return new InputStream() { @Override - public synchronized int read( byte[] b, int off, int len ) throws IOException - { - if ( off < 0 || off > b.length || len < 0 || off + len > b.length || off + len < 0 ) - { - throw new IndexOutOfBoundsException( - "b.length = " + b.length + ", off = " + off + ", len = " + len ); - } - else if ( len == 0 ) - { + public synchronized int read(byte[] b, int off, int len) throws IOException { + if (off < 0 || off > b.length || len < 0 || off + len > b.length || off + len < 0) { + throw new IndexOutOfBoundsException("b.length = " + b.length + ", off = " + off + ", len = " + len); + } else if (len == 0) { return 0; } - ByteBuffer bb = ByteBuffer.wrap( b, off, len ); - try - { - return channel.read( bb ).get(); - } - catch ( ExecutionException e ) - { + ByteBuffer bb = ByteBuffer.wrap(b, off, len); + try { + return channel.read(bb).get(); + } catch (ExecutionException e) { Throwable t = e.getCause(); throw t instanceof IOException - ? (IOException) t - : new IOException( ( t == null ? e : t ).getLocalizedMessage(), t ); - } - catch ( Exception e ) - { - throw new IOException( e.getLocalizedMessage(), e ); + ? (IOException) t + : new IOException((t == null ? e : t).getLocalizedMessage(), t); + } catch (Exception e) { + throw new IOException(e.getLocalizedMessage(), e); } } @Override - public int read() throws IOException - { + public int read() throws IOException { int count; byte[] b = new byte[1]; - do - { - count = read( b, 0, 1 ); - } - while ( count == 0 ); + do { + count = read(b, 0, 1); + } while (count == 0); return count == -1 ? -1 : b[0]; } @Override - public synchronized void close() throws IOException - { - if ( channel.isOpen() ) - { - try - { + public synchronized void close() throws IOException { + if (channel.isOpen()) { + try { channel.close(); - } - catch ( ClosedChannelException e ) - { + } catch (ClosedChannelException e) { // closed channel anyway } } @@ -204,65 +159,54 @@ public synchronized void close() throws IOException }; } - private static ReadableByteChannel newChannel( @Nonnull InputStream is, @Nonnegative int bufferSize ) - { - requireNonNull( is, "the stream should not be null" ); - final InputStream bis = bufferSize == 0 ? is : new BufferedInputStream( is, bufferSize ); + private static ReadableByteChannel newChannel(@Nonnull InputStream is, @Nonnegative int bufferSize) { + requireNonNull(is, "the stream should not be null"); + final InputStream bis = bufferSize == 0 ? is : new BufferedInputStream(is, bufferSize); - return new AbstractNoninterruptibleReadableChannel() - { + return new AbstractNoninterruptibleReadableChannel() { @Override - protected int readImpl( ByteBuffer src ) throws IOException - { - int count = bis.read( src.array(), src.arrayOffset() + ( (Buffer) src ).position(), src.remaining() ); - if ( count > 0 ) - { - ( (Buffer) src ).position( count + ( (Buffer) src ).position() ); + protected int readImpl(ByteBuffer src) throws IOException { + int count = bis.read(src.array(), src.arrayOffset() + ((Buffer) src).position(), src.remaining()); + if (count > 0) { + ((Buffer) src).position(count + ((Buffer) src).position()); } return count; } @Override - protected void closeImpl() throws IOException - { + protected void closeImpl() throws IOException { bis.close(); } }; } - private static WritableBufferedByteChannel newChannel( @Nonnull OutputStream out, - @Nonnegative final int bufferSize ) - { - requireNonNull( out, "the stream should not be null" ); - final OutputStream bos = bufferSize == 0 ? out : new BufferedOutputStream( out, bufferSize ); + private static WritableBufferedByteChannel newChannel( + @Nonnull OutputStream out, @Nonnegative final int bufferSize) { + requireNonNull(out, "the stream should not be null"); + final OutputStream bos = bufferSize == 0 ? out : new BufferedOutputStream(out, bufferSize); - return new AbstractNoninterruptibleWritableChannel() - { + return new AbstractNoninterruptibleWritableChannel() { private final AtomicLong bytesCounter = new AtomicLong(); @Override - public long countBufferOverflows() - { - return bufferSize == 0 ? 0 : max( bytesCounter.get() - 1, 0 ) / bufferSize; + public long countBufferOverflows() { + return bufferSize == 0 ? 0 : max(bytesCounter.get() - 1, 0) / bufferSize; } @Override - protected void writeImpl( ByteBuffer src ) throws IOException - { + protected void writeImpl(ByteBuffer src) throws IOException { int count = src.remaining(); - bos.write( src.array(), src.arrayOffset() + ( (Buffer) src ).position(), count ); - bytesCounter.getAndAdd( count ); + bos.write(src.array(), src.arrayOffset() + ((Buffer) src).position(), count); + bytesCounter.getAndAdd(count); } @Override - protected void closeImpl() throws IOException - { + protected void closeImpl() throws IOException { bos.close(); } @Override - protected void flushImpl() throws IOException - { + protected void flushImpl() throws IOException { bos.flush(); } }; diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/api/util/internal/ClassMethod.java b/surefire-api/src/main/java/org/apache/maven/surefire/api/util/internal/ClassMethod.java index 03661d8256..a4436e7025 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/api/util/internal/ClassMethod.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/api/util/internal/ClassMethod.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.api.util.internal; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.api.util.internal; import java.util.Objects; @@ -26,52 +25,42 @@ /** * Data transfer object of class and method literals. */ -public final class ClassMethod -{ +public final class ClassMethod { private final String clazz; private final String method; - public ClassMethod( String clazz, String method ) - { + public ClassMethod(String clazz, String method) { this.clazz = clazz; this.method = method; } - public boolean isValidTest() - { - return !isBlank( clazz ) && !isBlank( method ); + public boolean isValidTest() { + return !isBlank(clazz) && !isBlank(method); } - public String getClazz() - { + public String getClazz() { return clazz; } - public String getMethod() - { + public String getMethod() { return method; } @Override - public boolean equals( Object o ) - { - if ( this == o ) - { + public boolean equals(Object o) { + if (this == o) { return true; } - if ( o == null || getClass() != o.getClass() ) - { + if (o == null || getClass() != o.getClass()) { return false; } - ClassMethod that = ( ClassMethod ) o; - return Objects.equals( clazz, that.clazz ) - && Objects.equals( method, that.method ); + ClassMethod that = (ClassMethod) o; + return Objects.equals(clazz, that.clazz) && Objects.equals(method, that.method); } @Override - public int hashCode() - { - return Objects.hash( clazz, method ); + public int hashCode() { + return Objects.hash(clazz, method); } } diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/api/util/internal/ConcurrencyUtils.java b/surefire-api/src/main/java/org/apache/maven/surefire/api/util/internal/ConcurrencyUtils.java index fd2c189b40..b199d96796 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/api/util/internal/ConcurrencyUtils.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/api/util/internal/ConcurrencyUtils.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.api.util.internal; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.api.util.internal; import java.util.concurrent.atomic.AtomicInteger; @@ -27,11 +26,9 @@ * @author Tibor Digana (tibor17) * @since 2.19 */ -public final class ConcurrencyUtils -{ - private ConcurrencyUtils() - { - throw new IllegalStateException( "not instantiable constructor" ); +public final class ConcurrencyUtils { + private ConcurrencyUtils() { + throw new IllegalStateException("not instantiable constructor"); } /** @@ -41,27 +38,20 @@ private ConcurrencyUtils() * @param runner run if this Thread has concurrently decremented the counter down to zero * @param counter atomic counter */ - @SuppressWarnings( "checkstyle:emptyforiteratorpad" ) - public static void runIfZeroCountDown( Runnable runner, AtomicInteger counter ) - { - for (;;) - { + @SuppressWarnings("checkstyle:emptyforiteratorpad") + public static void runIfZeroCountDown(Runnable runner, AtomicInteger counter) { + for (; ; ) { int c = counter.get(); - if ( c > 0 ) - { + if (c > 0) { int newCounter = c - 1; - if ( counter.compareAndSet( c, newCounter ) ) - { + if (counter.compareAndSet(c, newCounter)) { boolean isZero = newCounter == 0; - if ( isZero ) - { + if (isZero) { runner.run(); } break; } - } - else - { + } else { break; } } diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/api/util/internal/DaemonThreadFactory.java b/surefire-api/src/main/java/org/apache/maven/surefire/api/util/internal/DaemonThreadFactory.java index 28a5342201..90bec08d8c 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/api/util/internal/DaemonThreadFactory.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/api/util/internal/DaemonThreadFactory.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.api.util.internal; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.api.util.internal; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; @@ -26,28 +25,24 @@ /** * Creates new daemon Thread. */ -public final class DaemonThreadFactory - implements ThreadFactory -{ +public final class DaemonThreadFactory implements ThreadFactory { private static final ThreadFactory DEFAULT_THREAD_FACTORY = Executors.defaultThreadFactory(); - private static final AtomicInteger POOL_NUMBER = new AtomicInteger( 1 ); + private static final AtomicInteger POOL_NUMBER = new AtomicInteger(1); - private final AtomicInteger threadNumber = new AtomicInteger( 1 ); + private final AtomicInteger threadNumber = new AtomicInteger(1); private final String namePrefix; - private DaemonThreadFactory() - { + private DaemonThreadFactory() { namePrefix = "pool-" + POOL_NUMBER.getAndIncrement() + "-thread-"; } @Override - public Thread newThread( Runnable r ) - { - Thread t = DEFAULT_THREAD_FACTORY.newThread( r ); - t.setName( namePrefix + threadNumber.getAndIncrement() ); - t.setDaemon( true ); + public Thread newThread(Runnable r) { + Thread t = DEFAULT_THREAD_FACTORY.newThread(r); + t.setName(namePrefix + threadNumber.getAndIncrement()); + t.setDaemon(true); return t; } @@ -55,42 +50,34 @@ public Thread newThread( Runnable r ) * Should be used by thread pools. * @return new instance of {@link ThreadFactory} where each {@link Thread thread} is daemon */ - public static ThreadFactory newDaemonThreadFactory() - { + public static ThreadFactory newDaemonThreadFactory() { return new DaemonThreadFactory(); } - public static ThreadFactory newDaemonThreadFactory( String name ) - { - return new NamedThreadFactory( name ); + public static ThreadFactory newDaemonThreadFactory(String name) { + return new NamedThreadFactory(name); } - public static Thread newDaemonThread( Runnable r ) - { - return new DaemonThreadFactory().newThread( r ); + public static Thread newDaemonThread(Runnable r) { + return new DaemonThreadFactory().newThread(r); } - public static Thread newDaemonThread( Runnable r, String name ) - { - Thread t = new DaemonThreadFactory().newThread( r ); - t.setName( name ); + public static Thread newDaemonThread(Runnable r, String name) { + Thread t = new DaemonThreadFactory().newThread(r); + t.setName(name); return t; } - private static class NamedThreadFactory - implements ThreadFactory - { + private static class NamedThreadFactory implements ThreadFactory { private final String name; - private NamedThreadFactory( String name ) - { + private NamedThreadFactory(String name) { this.name = name; } @Override - public Thread newThread( Runnable r ) - { - return newDaemonThread( r, name ); + public Thread newThread(Runnable r) { + return newDaemonThread(r, name); } } } diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/api/util/internal/DumpFileUtils.java b/surefire-api/src/main/java/org/apache/maven/surefire/api/util/internal/DumpFileUtils.java index b552aa23f5..5fb720fc39 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/api/util/internal/DumpFileUtils.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/api/util/internal/DumpFileUtils.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.api.util.internal; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.api.util.internal; import java.io.File; import java.io.FileOutputStream; @@ -37,11 +36,9 @@ * @author Tibor Digana (tibor17) * @since 2.20 */ -public final class DumpFileUtils -{ - private DumpFileUtils() - { - throw new IllegalStateException( "no instantiable constructor" ); +public final class DumpFileUtils { + private DumpFileUtils() { + throw new IllegalStateException("no instantiable constructor"); } /** @@ -50,79 +47,57 @@ private DumpFileUtils() * @param reportsDir only report directory * @param dumpFileName dump file name */ - public static synchronized File newDumpFile( File reportsDir, String dumpFileName ) - { + public static synchronized File newDumpFile(File reportsDir, String dumpFileName) { reportsDir.mkdirs(); - return new File( reportsDir, dumpFileName ); + return new File(reportsDir, dumpFileName); } - public static void dumpException( Throwable t, File dumpFile ) - { - dumpException( t, null, dumpFile ); + public static void dumpException(Throwable t, File dumpFile) { + dumpException(t, null, dumpFile); } - public static void dumpException( Throwable t, String msg, File dumpFile ) - { - try - { - if ( t != null && dumpFile != null - && ( dumpFile.exists() || mkdirs( dumpFile ) && dumpFile.createNewFile() ) ) - { - try ( PrintWriter pw = new PrintWriter( createWriter( dumpFile ) ) ) - { - if ( msg != null ) - { - pw.append( msg ) - .append( StringUtils.NL ); + public static void dumpException(Throwable t, String msg, File dumpFile) { + try { + if (t != null && dumpFile != null && (dumpFile.exists() || mkdirs(dumpFile) && dumpFile.createNewFile())) { + try (PrintWriter pw = new PrintWriter(createWriter(dumpFile))) { + if (msg != null) { + pw.append(msg).append(StringUtils.NL); } - t.printStackTrace( pw ); - pw.append( StringUtils.NL ) - .append( StringUtils.NL ); + t.printStackTrace(pw); + pw.append(StringUtils.NL).append(StringUtils.NL); } } - } - catch ( Exception e ) - { + } catch (Exception e) { // do nothing } } - public static void dumpText( String msg, File dumpFile ) - { - try - { - if ( msg != null && dumpFile != null - && ( dumpFile.exists() || mkdirs( dumpFile ) && dumpFile.createNewFile() ) ) - { - try ( Writer writer = createWriter( dumpFile ) ) - { - writer.append( msg ) - .append( StringUtils.NL ) - .append( StringUtils.NL ); + public static void dumpText(String msg, File dumpFile) { + try { + if (msg != null + && dumpFile != null + && (dumpFile.exists() || mkdirs(dumpFile) && dumpFile.createNewFile())) { + try (Writer writer = createWriter(dumpFile)) { + writer.append(msg).append(StringUtils.NL).append(StringUtils.NL); } } - } - catch ( Exception e ) - { + } catch (Exception e) { // do nothing } } - public static String newFormattedDateFileName() - { - return new SimpleDateFormat( "yyyy-MM-dd'T'HH-mm-ss_SSS" ).format( new Date() ); + public static String newFormattedDateFileName() { + return new SimpleDateFormat("yyyy-MM-dd'T'HH-mm-ss_SSS").format(new Date()); } - private static Writer createWriter( File dumpFile ) throws IOException - { - return new OutputStreamWriter( new FileOutputStream( dumpFile, true ), UTF_8 ) - .append( "# Created at " ) - .append( new SimpleDateFormat( "yyyy-MM-dd'T'HH:mm:ss.SSS" ).format( new Date() ) ) - .append( StringUtils.NL ); + private static Writer createWriter(File dumpFile) throws IOException { + return new OutputStreamWriter(new FileOutputStream(dumpFile, true), UTF_8) + .append("# Created at ") + .append(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS").format(new Date())) + .append(StringUtils.NL); } - private static boolean mkdirs( File dumpFile ) - { + private static boolean mkdirs(File dumpFile) { File dir = dumpFile.getParentFile(); return dir.exists() || dir.mkdirs(); } diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/api/util/internal/ImmutableMap.java b/surefire-api/src/main/java/org/apache/maven/surefire/api/util/internal/ImmutableMap.java index 5b5422fcf5..4fbd0ff0fd 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/api/util/internal/ImmutableMap.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/api/util/internal/ImmutableMap.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.api.util.internal; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.api.util.internal; import java.util.AbstractMap; import java.util.LinkedHashSet; @@ -34,24 +33,17 @@ * @param value * @since 2.20 */ -public final class ImmutableMap - extends AbstractMap -{ +public final class ImmutableMap extends AbstractMap { private final Node first; - public ImmutableMap( Map map ) - { + public ImmutableMap(Map map) { Node first = null; Node previous = null; - for ( Entry e : map.entrySet() ) - { - Node node = new Node<>( e.getKey(), e.getValue() ); - if ( first == null ) - { + for (Entry e : map.entrySet()) { + Node node = new Node<>(e.getKey(), e.getValue()); + if (first == null) { first = node; - } - else - { + } else { previous.next = node; } previous = node; @@ -60,74 +52,64 @@ public ImmutableMap( Map map ) } @Override - public Set> entrySet() - { + public Set> entrySet() { Set> entries = new LinkedHashSet<>(); Node node = first; - while ( node != null ) - { - entries.add( node ); + while (node != null) { + entries.add(node); node = node.next; } - return unmodifiableSet( entries ); + return unmodifiableSet(entries); } - static final class Node - implements Entry - { + static final class Node implements Entry { final K key; final V value; volatile Node next; - Node( K key, V value ) - { + Node(K key, V value) { this.key = key; this.value = value; } @Override - public K getKey() - { + public K getKey() { return key; } @Override - public V getValue() - { + public V getValue() { return value; } @Override - public V setValue( V value ) - { + public V setValue(V value) { throw new UnsupportedOperationException(); } @Override - public boolean equals( Object o ) - { - if ( this == o ) - { + public boolean equals(Object o) { + if (this == o) { return true; } - if ( o == null || getClass() != o.getClass() ) - { + if (o == null || getClass() != o.getClass()) { return false; } Node node = (Node) o; - return getKey() != null ? getKey().equals( node.getKey() ) : node.getKey() == null - && getValue() != null ? getValue().equals( node.getValue() ) : node.getValue() == null; - + return getKey() != null + ? getKey().equals(node.getKey()) + : node.getKey() == null && getValue() != null + ? getValue().equals(node.getValue()) + : node.getValue() == null; } @Override - public int hashCode() - { + public int hashCode() { int result = getKey() != null ? getKey().hashCode() : 0; - result = 31 * result + ( getValue() != null ? getValue().hashCode() : 0 ); + result = 31 * result + (getValue() != null ? getValue().hashCode() : 0); return result; } } diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/api/util/internal/ObjectUtils.java b/surefire-api/src/main/java/org/apache/maven/surefire/api/util/internal/ObjectUtils.java index 9ee7571e43..4dda975833 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/api/util/internal/ObjectUtils.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/api/util/internal/ObjectUtils.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.api.util.internal; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.api.util.internal; import java.lang.management.ManagementFactory; import java.util.Map; @@ -31,28 +30,23 @@ * @author Tibor Digana (tibor17) * @since 2.20 */ -public final class ObjectUtils -{ - private ObjectUtils() - { - throw new IllegalStateException( "no instantiable constructor" ); +public final class ObjectUtils { + private ObjectUtils() { + throw new IllegalStateException("no instantiable constructor"); } - public static T useNonNull( T target, T fallback ) - { + public static T useNonNull(T target, T fallback) { return target == null ? fallback : target; } - public static Map systemProps() - { + public static Map systemProps() { return ManagementFactory.getRuntimeMXBean().getSystemProperties(); } /** * @return true if SecurityManager is supported (even if deprecated) in JDK (up to 17) */ - public static boolean isSecurityManagerSupported() - { - return JAVA_RECENT.atMost( JAVA_17 ); + public static boolean isSecurityManagerSupported() { + return JAVA_RECENT.atMost(JAVA_17); } } diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/api/util/internal/StringUtils.java b/surefire-api/src/main/java/org/apache/maven/surefire/api/util/internal/StringUtils.java index 136afba068..67265e20d7 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/api/util/internal/StringUtils.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/api/util/internal/StringUtils.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.api.util.internal; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.api.util.internal; import java.util.StringTokenizer; @@ -48,32 +47,25 @@ * @version $Id: StringUtils.java 8001 2009-01-03 13:17:09Z vsiveton $ * @since 1.0 */ -public final class StringUtils -{ +public final class StringUtils { public static final String NL = lineSeparator(); - private StringUtils() - { - throw new IllegalStateException( "no instantiable constructor" ); + private StringUtils() { + throw new IllegalStateException("no instantiable constructor"); } - public static String[] split( String text, String separator ) - { + public static String[] split(String text, String separator) { final StringTokenizer tok; - if ( separator == null ) - { + if (separator == null) { // Null separator means we're using StringTokenizer's default // delimiter, which comprises all whitespace characters. - tok = new StringTokenizer( text ); - } - else - { - tok = new StringTokenizer( text, separator ); + tok = new StringTokenizer(text); + } else { + tok = new StringTokenizer(text, separator); } String[] list = new String[tok.countTokens()]; - for ( int i = 0; tok.hasMoreTokens(); i++ ) - { + for (int i = 0; tok.hasMoreTokens(); i++) { list[i] = tok.nextToken(); } return list; @@ -86,18 +78,12 @@ public static String[] split( String text, String separator ) * @param pattern a pattern which should start in {@code buffer} * @return {@code true} if buffer's literal starts with given {@code pattern}, or both are empty. */ - public static boolean startsWith( StringBuffer buffer, String pattern ) - { - if ( buffer.length() < pattern.length() ) - { + public static boolean startsWith(StringBuffer buffer, String pattern) { + if (buffer.length() < pattern.length()) { return false; - } - else - { - for ( int i = 0, len = pattern.length(); i < len; i++ ) - { - if ( buffer.charAt( i ) != pattern.charAt( i ) ) - { + } else { + for (int i = 0, len = pattern.length(); i < len; i++) { + if (buffer.charAt(i) != pattern.charAt(i)) { return false; } } diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/api/util/internal/TestClassMethodNameUtils.java b/surefire-api/src/main/java/org/apache/maven/surefire/api/util/internal/TestClassMethodNameUtils.java index c24d88de8d..6eb879a376 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/api/util/internal/TestClassMethodNameUtils.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/api/util/internal/TestClassMethodNameUtils.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.api.util.internal; /* @@ -26,34 +44,27 @@ * @author Tibor Digana (tibor17) * @since 2.20 */ -public final class TestClassMethodNameUtils -{ - private TestClassMethodNameUtils() - { - throw new IllegalStateException( "no instantiable constructor" ); +public final class TestClassMethodNameUtils { + private TestClassMethodNameUtils() { + throw new IllegalStateException("no instantiable constructor"); } - public static String extractClassName( String displayName ) - { + public static String extractClassName(String displayName) { String clazz = displayName; - if ( displayName.endsWith( ")" ) ) - { - int paren = displayName.lastIndexOf( '(' ); - if ( paren != -1 ) - { - clazz = displayName.substring( paren + 1, displayName.length() - 1 ); + if (displayName.endsWith(")")) { + int paren = displayName.lastIndexOf('('); + if (paren != -1) { + clazz = displayName.substring(paren + 1, displayName.length() - 1); } } return clazz; } - public static String extractMethodName( String displayName ) - { + public static String extractMethodName(String displayName) { String method = null; - int parent = displayName.lastIndexOf( '(' ); - if ( parent != -1 ) - { - method = displayName.substring( 0, parent ); + int parent = displayName.lastIndexOf('('); + if (parent != -1) { + method = displayName.substring(0, parent); } return method; } diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/api/util/internal/WritableBufferedByteChannel.java b/surefire-api/src/main/java/org/apache/maven/surefire/api/util/internal/WritableBufferedByteChannel.java index ea86a822b7..626bf7e1e0 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/api/util/internal/WritableBufferedByteChannel.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/api/util/internal/WritableBufferedByteChannel.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.api.util.internal; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.api.util.internal; import java.io.IOException; import java.nio.ByteBuffer; @@ -31,8 +30,8 @@ * The method {@link #write(ByteBuffer)} flushes every written message. * You can flush the channel by {@link #write(ByteBuffer) writing} the zero length of {@link ByteBuffer}. */ -public interface WritableBufferedByteChannel extends WritableByteChannel -{ - void writeBuffered( ByteBuffer src ) throws IOException; +public interface WritableBufferedByteChannel extends WritableByteChannel { + void writeBuffered(ByteBuffer src) throws IOException; + long countBufferOverflows(); } diff --git a/surefire-api/src/test/java/org/apache/maven/JUnit4SuiteTest.java b/surefire-api/src/test/java/org/apache/maven/JUnit4SuiteTest.java index 016cce4ff0..f67b4f0e9d 100644 --- a/surefire-api/src/test/java/org/apache/maven/JUnit4SuiteTest.java +++ b/surefire-api/src/test/java/org/apache/maven/JUnit4SuiteTest.java @@ -1,5 +1,3 @@ -package org.apache.maven; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,13 +16,14 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven; import junit.framework.JUnit4TestAdapter; import junit.framework.Test; -import org.apache.maven.surefire.api.runorder.ThreadedExecutionSchedulerTest; import org.apache.maven.surefire.SpecificTestClassFilterTest; import org.apache.maven.surefire.api.booter.ForkingRunListenerTest; import org.apache.maven.surefire.api.report.LegacyPojoStackTraceWriterTest; +import org.apache.maven.surefire.api.runorder.ThreadedExecutionSchedulerTest; import org.apache.maven.surefire.api.stream.AbstractStreamDecoderTest; import org.apache.maven.surefire.api.stream.AbstractStreamEncoderTest; import org.apache.maven.surefire.api.suite.RunResultTest; @@ -52,7 +51,7 @@ * @author Tibor Digana (tibor17) * @since 2.19 */ -@Suite.SuiteClasses( { +@Suite.SuiteClasses({ ThreadedExecutionSchedulerTest.class, ForkingRunListenerTest.class, LegacyPojoStackTraceWriterTest.class, @@ -75,12 +74,10 @@ AbstractStreamEncoderTest.class, AbstractStreamDecoderTest.class, ObjectUtilsTest.class -} ) -@RunWith( Suite.class ) -public class JUnit4SuiteTest -{ - public static Test suite() - { - return new JUnit4TestAdapter( JUnit4SuiteTest.class ); +}) +@RunWith(Suite.class) +public class JUnit4SuiteTest { + public static Test suite() { + return new JUnit4TestAdapter(JUnit4SuiteTest.class); } } diff --git a/surefire-api/src/test/java/org/apache/maven/surefire/SpecificTestClassFilterTest.java b/surefire-api/src/test/java/org/apache/maven/surefire/SpecificTestClassFilterTest.java index da9ac4c611..d438e5c26d 100644 --- a/surefire-api/src/test/java/org/apache/maven/surefire/SpecificTestClassFilterTest.java +++ b/surefire-api/src/test/java/org/apache/maven/surefire/SpecificTestClassFilterTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire; import junit.framework.TestCase; import org.apache.maven.surefire.api.filter.SpecificTestClassFilter; @@ -25,37 +24,32 @@ /** * */ -public class SpecificTestClassFilterTest extends TestCase -{ - public void testMatchSingleCharacterWildcard() - { +public class SpecificTestClassFilterTest extends TestCase { + public void testMatchSingleCharacterWildcard() { SpecificTestClassFilter filter = new SpecificTestClassFilter( - new String[] {"org/apache/maven/surefire/api/filter/?pecificTestClassFilter.class"} ); + new String[] {"org/apache/maven/surefire/api/filter/?pecificTestClassFilter.class"}); - assertTrue( filter.accept( SpecificTestClassFilter.class ) ); + assertTrue(filter.accept(SpecificTestClassFilter.class)); } - public void testMatchSingleSegmentWordWildcard() - { + public void testMatchSingleSegmentWordWildcard() { SpecificTestClassFilter filter = new SpecificTestClassFilter( - new String[] {"org/apache/maven/surefire/api/filter/*TestClassFilter.class"} ); + new String[] {"org/apache/maven/surefire/api/filter/*TestClassFilter.class"}); - assertTrue( filter.accept( SpecificTestClassFilter.class ) ); + assertTrue(filter.accept(SpecificTestClassFilter.class)); } - public void testMatchMultiSegmentWildcard() - { - SpecificTestClassFilter filter = new SpecificTestClassFilter( - new String[] {"org/**/SpecificTestClassFilter.class"} ); + public void testMatchMultiSegmentWildcard() { + SpecificTestClassFilter filter = + new SpecificTestClassFilter(new String[] {"org/**/SpecificTestClassFilter.class"}); - assertTrue( filter.accept( SpecificTestClassFilter.class ) ); + assertTrue(filter.accept(SpecificTestClassFilter.class)); } - public void testMatchSingleSegmentWildcard() - { + public void testMatchSingleSegmentWildcard() { SpecificTestClassFilter filter = new SpecificTestClassFilter( - new String[] {"org/*/maven/surefire/api/filter/SpecificTestClassFilter.class"} ); + new String[] {"org/*/maven/surefire/api/filter/SpecificTestClassFilter.class"}); - assertTrue( filter.accept( SpecificTestClassFilter.class ) ); + assertTrue(filter.accept(SpecificTestClassFilter.class)); } } diff --git a/surefire-api/src/test/java/org/apache/maven/surefire/api/booter/ForkingRunListenerTest.java b/surefire-api/src/test/java/org/apache/maven/surefire/api/booter/ForkingRunListenerTest.java index bd5673d36d..694963df85 100644 --- a/surefire-api/src/test/java/org/apache/maven/surefire/api/booter/ForkingRunListenerTest.java +++ b/surefire-api/src/test/java/org/apache/maven/surefire/api/booter/ForkingRunListenerTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.api.booter; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.api.booter; import junit.framework.TestCase; import org.mockito.ArgumentCaptor; @@ -33,21 +32,16 @@ /** * @author Kristian Rosenvold */ -public class ForkingRunListenerTest - extends TestCase -{ - public void testInfo() - { - MasterProcessChannelEncoder encoder = mock( MasterProcessChannelEncoder.class ); - ArgumentCaptor argument1 = ArgumentCaptor.forClass( String.class ); - doNothing().when( encoder ).consoleInfoLog( anyString() ); - ForkingRunListener forkingRunListener = new ForkingRunListener( encoder, true ); - forkingRunListener.info( new String( new byte[]{ (byte) 'A' } ) ); - forkingRunListener.info( new String( new byte[]{ } ) ); - verify( encoder, times( 2 ) ).consoleInfoLog( argument1.capture() ); - assertThat( argument1.getAllValues() ) - .hasSize( 2 ) - .containsSequence( "A", "" ); - verifyNoMoreInteractions( encoder ); +public class ForkingRunListenerTest extends TestCase { + public void testInfo() { + MasterProcessChannelEncoder encoder = mock(MasterProcessChannelEncoder.class); + ArgumentCaptor argument1 = ArgumentCaptor.forClass(String.class); + doNothing().when(encoder).consoleInfoLog(anyString()); + ForkingRunListener forkingRunListener = new ForkingRunListener(encoder, true); + forkingRunListener.info(new String(new byte[] {(byte) 'A'})); + forkingRunListener.info(new String(new byte[] {})); + verify(encoder, times(2)).consoleInfoLog(argument1.capture()); + assertThat(argument1.getAllValues()).hasSize(2).containsSequence("A", ""); + verifyNoMoreInteractions(encoder); } } diff --git a/surefire-api/src/test/java/org/apache/maven/surefire/api/report/CategorizedReportEntryTest.java b/surefire-api/src/test/java/org/apache/maven/surefire/api/report/CategorizedReportEntryTest.java index 8c70d0d930..3ac827cca1 100644 --- a/surefire-api/src/test/java/org/apache/maven/surefire/api/report/CategorizedReportEntryTest.java +++ b/surefire-api/src/test/java/org/apache/maven/surefire/api/report/CategorizedReportEntryTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.api.report; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.api.report; import static org.apache.maven.surefire.api.report.RunMode.NORMAL_RUN; import static org.junit.Assert.assertEquals; @@ -25,45 +24,40 @@ /** * @author Ashley Scopes */ -public class CategorizedReportEntryTest -{ - public void testGetReportNameWithGroupWhenSourceTextIsNull() - { +public class CategorizedReportEntryTest { + public void testGetReportNameWithGroupWhenSourceTextIsNull() { String className = "ClassName"; String classText = null; String groupName = "The Group Name"; - ReportEntry reportEntry = new CategorizedReportEntry( - NORMAL_RUN, 1L, className, classText, groupName, null, null ); - assertEquals( "ClassName (of The Group Name)", reportEntry.getReportNameWithGroup() ); + ReportEntry reportEntry = + new CategorizedReportEntry(NORMAL_RUN, 1L, className, classText, groupName, null, null); + assertEquals("ClassName (of The Group Name)", reportEntry.getReportNameWithGroup()); } - public void testGetReportNameWithGroupWhenSourceTextIsEmpty() - { + public void testGetReportNameWithGroupWhenSourceTextIsEmpty() { String className = "ClassName"; String classText = ""; String groupName = "The Group Name"; - ReportEntry reportEntry = new CategorizedReportEntry( - NORMAL_RUN, 1L, className, classText, groupName, null, null ); - assertEquals( "ClassName (of The Group Name)", reportEntry.getReportNameWithGroup() ); + ReportEntry reportEntry = + new CategorizedReportEntry(NORMAL_RUN, 1L, className, classText, groupName, null, null); + assertEquals("ClassName (of The Group Name)", reportEntry.getReportNameWithGroup()); } - public void testGetReportNameWithGroupWhenSourceTextIsBlank() - { + public void testGetReportNameWithGroupWhenSourceTextIsBlank() { String className = "ClassName"; String classText = " "; String groupName = "The Group Name"; - ReportEntry reportEntry = new CategorizedReportEntry( - NORMAL_RUN, 1L, className, classText, groupName, null, null ); - assertEquals( "ClassName (of The Group Name)", reportEntry.getReportNameWithGroup() ); + ReportEntry reportEntry = + new CategorizedReportEntry(NORMAL_RUN, 1L, className, classText, groupName, null, null); + assertEquals("ClassName (of The Group Name)", reportEntry.getReportNameWithGroup()); } - public void testGetReportNameWithGroupWhenSourceTextIsProvided() - { + public void testGetReportNameWithGroupWhenSourceTextIsProvided() { String className = "ClassName"; String classText = "The Class Name"; String groupName = "The Group Name"; - ReportEntry reportEntry = new CategorizedReportEntry( - NORMAL_RUN, 1L, className, classText, groupName, null, null ); - assertEquals( "The Class Name (of The Group Name)", reportEntry.getReportNameWithGroup() ); + ReportEntry reportEntry = + new CategorizedReportEntry(NORMAL_RUN, 1L, className, classText, groupName, null, null); + assertEquals("The Class Name (of The Group Name)", reportEntry.getReportNameWithGroup()); } } diff --git a/surefire-api/src/test/java/org/apache/maven/surefire/api/report/LegacyPojoStackTraceWriterTest.java b/surefire-api/src/test/java/org/apache/maven/surefire/api/report/LegacyPojoStackTraceWriterTest.java index f2c8e85602..e06f19a113 100644 --- a/surefire-api/src/test/java/org/apache/maven/surefire/api/report/LegacyPojoStackTraceWriterTest.java +++ b/surefire-api/src/test/java/org/apache/maven/surefire/api/report/LegacyPojoStackTraceWriterTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.api.report; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.api.report; import java.io.PrintWriter; @@ -26,12 +25,10 @@ /** * @author Kristian Rosenvold */ -public class LegacyPojoStackTraceWriterTest extends TestCase -{ +public class LegacyPojoStackTraceWriterTest extends TestCase { - @SuppressWarnings( "checkstyle:linelength" ) - public void testWriteTrimmedTraceToString() - { + @SuppressWarnings("checkstyle:linelength") + public void testWriteTrimmedTraceToString() { String stackTrace = "junit.framework.AssertionFailedError: blah\n" + " at junit.framework.Assert.fail(Assert.java:47)\n" + " at TestSurefire3.testQuote(TestSurefire3.java:23)\n" @@ -61,16 +58,17 @@ public void testWriteTrimmedTraceToString() + " at java.lang.reflect.Method.invoke(Method.java:585)\n" + " at org.apache.maven.surefire.booter.SurefireBooter.runSuitesInProcess(SurefireBooter.java:318)\n" + " at org.apache.maven.surefire.booter.SurefireBooter.main(SurefireBooter.java:956)\n"; - MockThrowable t = new MockThrowable( stackTrace ); - LegacyPojoStackTraceWriter w = new LegacyPojoStackTraceWriter( "TestSurefire3", "testQuote", t ); + MockThrowable t = new MockThrowable(stackTrace); + LegacyPojoStackTraceWriter w = new LegacyPojoStackTraceWriter("TestSurefire3", "testQuote", t); String out = w.writeTrimmedTraceToString(); - String expected = "junit.framework.AssertionFailedError: blah\n" + " at junit.framework.Assert.fail(Assert.java:47)\n" + " at TestSurefire3.testQuote(TestSurefire3.java:23)\n"; - assertEquals( expected, out ); + String expected = + "junit.framework.AssertionFailedError: blah\n" + " at junit.framework.Assert.fail(Assert.java:47)\n" + + " at TestSurefire3.testQuote(TestSurefire3.java:23)\n"; + assertEquals(expected, out); } - @SuppressWarnings( "checkstyle:linelength" ) - public void testCausedBy() - { + @SuppressWarnings("checkstyle:linelength") + public void testCausedBy() { String stackTrace = "java.lang.RuntimeException: blah\n" + " at TestSurefire3.testBlah(TestSurefire3.java:45)\n" + " at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\n" @@ -105,8 +103,8 @@ public void testCausedBy() + " at TestSurefire3.testBlah(TestSurefire3.java:43)\n" + " at TestSurefire3.testBlah(TestSurefire3.java:43)\n" + " ... 26 more\n"; - MockThrowable t = new MockThrowable( stackTrace ); - LegacyPojoStackTraceWriter w = new LegacyPojoStackTraceWriter( "TestSurefire3", "testBlah", t ); + MockThrowable t = new MockThrowable(stackTrace); + LegacyPojoStackTraceWriter w = new LegacyPojoStackTraceWriter("TestSurefire3", "testBlah", t); String out = w.writeTrimmedTraceToString(); String expected = "java.lang.RuntimeException: blah\n" + " at TestSurefire3.testBlah(TestSurefire3.java:45)\n" @@ -116,41 +114,32 @@ public void testCausedBy() + " at TestSurefire3.testBlah(TestSurefire3.java:43)\n" + " at TestSurefire3.testBlah(TestSurefire3.java:43)\n" + " ... 26 more\n"; - assertEquals( expected, out ); + assertEquals(expected, out); } - static class MockThrowable extends Throwable - { + static class MockThrowable extends Throwable { private static final long serialVersionUID = 1L; private final String stackTrace; - MockThrowable( String stackTrace ) - { + MockThrowable(String stackTrace) { this.stackTrace = stackTrace; } @Override - public void printStackTrace( PrintWriter s ) - { - s.write( stackTrace ); + public void printStackTrace(PrintWriter s) { + s.write(stackTrace); } } - public void testMultiLineMessage() - { - String msg = "assert \"foo\" == \"bar\"\n" - + " |\n" - + " false"; - try - { - throw new RuntimeException( msg ); - } - catch ( Throwable t ) - { - LegacyPojoStackTraceWriter writer = new LegacyPojoStackTraceWriter( null, null, t ); + public void testMultiLineMessage() { + String msg = "assert \"foo\" == \"bar\"\n" + " |\n" + " false"; + try { + throw new RuntimeException(msg); + } catch (Throwable t) { + LegacyPojoStackTraceWriter writer = new LegacyPojoStackTraceWriter(null, null, t); String stackTrace = writer.writeTraceToString(); - assertTrue( stackTrace.startsWith( "java.lang.RuntimeException: \n" + msg ) ); + assertTrue(stackTrace.startsWith("java.lang.RuntimeException: \n" + msg)); } } } diff --git a/surefire-api/src/test/java/org/apache/maven/surefire/api/runorder/ThreadedExecutionSchedulerTest.java b/surefire-api/src/test/java/org/apache/maven/surefire/api/runorder/ThreadedExecutionSchedulerTest.java index 64fa7190c0..7ce94c6970 100644 --- a/surefire-api/src/test/java/org/apache/maven/surefire/api/runorder/ThreadedExecutionSchedulerTest.java +++ b/surefire-api/src/test/java/org/apache/maven/surefire/api/runorder/ThreadedExecutionSchedulerTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.api.runorder; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.api.runorder; import java.util.List; @@ -27,95 +26,76 @@ /** * @author Kristian Rosenvold */ -public class ThreadedExecutionSchedulerTest - extends TestCase -{ +public class ThreadedExecutionSchedulerTest extends TestCase { - private final RunEntryStatistics a1 = fromValues( 200, 2, A.class, "at1" ); + private final RunEntryStatistics a1 = fromValues(200, 2, A.class, "at1"); - private final RunEntryStatistics a2 = fromValues( 300, 2, A.class, "at2" ); + private final RunEntryStatistics a2 = fromValues(300, 2, A.class, "at2"); - private final RunEntryStatistics b1 = fromValues( 400, 2, B.class, "bt1" ); + private final RunEntryStatistics b1 = fromValues(400, 2, B.class, "bt1"); - private final RunEntryStatistics b2 = fromValues( 300, 2, B.class, "bt2" ); + private final RunEntryStatistics b2 = fromValues(300, 2, B.class, "bt2"); - private final RunEntryStatistics c1 = fromValues( 400, 2, C.class, "ct1" ); + private final RunEntryStatistics c1 = fromValues(400, 2, C.class, "ct1"); - private final RunEntryStatistics c2 = fromValues( 200, 2, C.class, "ct2" ); + private final RunEntryStatistics c2 = fromValues(200, 2, C.class, "ct2"); - private final RunEntryStatistics d1 = fromValues( 401, 2, D.class, "ct2" ); + private final RunEntryStatistics d1 = fromValues(401, 2, D.class, "ct2"); - private final RunEntryStatistics e1 = fromValues( 200, 2, E.class, "ct2" ); + private final RunEntryStatistics e1 = fromValues(200, 2, E.class, "ct2"); - public void testAddTest() - { - ThreadedExecutionScheduler threadedExecutionScheduler = new ThreadedExecutionScheduler( 2 ); - addPrioritizedTests( threadedExecutionScheduler ); + public void testAddTest() { + ThreadedExecutionScheduler threadedExecutionScheduler = new ThreadedExecutionScheduler(2); + addPrioritizedTests(threadedExecutionScheduler); final List> result = threadedExecutionScheduler.getResult(); - assertEquals( 5, result.size() ); - assertEquals( B.class, result.get( 0 ) ); - assertEquals( C.class, result.get( 1 ) ); - assertEquals( D.class, result.get( 2 ) ); - assertEquals( A.class, result.get( 3 ) ); - assertEquals( E.class, result.get( 4 ) ); + assertEquals(5, result.size()); + assertEquals(B.class, result.get(0)); + assertEquals(C.class, result.get(1)); + assertEquals(D.class, result.get(2)); + assertEquals(A.class, result.get(3)); + assertEquals(E.class, result.get(4)); } - public void testAddTestJaggedResult() - { - ThreadedExecutionScheduler threadedExecutionScheduler = new ThreadedExecutionScheduler( 4 ); - addPrioritizedTests( threadedExecutionScheduler ); + public void testAddTestJaggedResult() { + ThreadedExecutionScheduler threadedExecutionScheduler = new ThreadedExecutionScheduler(4); + addPrioritizedTests(threadedExecutionScheduler); final List> result = threadedExecutionScheduler.getResult(); - assertEquals( 5, result.size() ); + assertEquals(5, result.size()); } - private void addPrioritizedTests( ThreadedExecutionScheduler threadedExecutionScheduler ) - { - threadedExecutionScheduler.addTest( new PrioritizedTest( B.class, createPriority( b1, b2 ) ) ); - threadedExecutionScheduler.addTest( new PrioritizedTest( C.class, createPriority( c1, c2 ) ) ); - threadedExecutionScheduler.addTest( new PrioritizedTest( A.class, createPriority( a1, a2 ) ) ); - threadedExecutionScheduler.addTest( new PrioritizedTest( D.class, createPriority( d1 ) ) ); - threadedExecutionScheduler.addTest( new PrioritizedTest( E.class, createPriority( e1 ) ) ); + private void addPrioritizedTests(ThreadedExecutionScheduler threadedExecutionScheduler) { + threadedExecutionScheduler.addTest(new PrioritizedTest(B.class, createPriority(b1, b2))); + threadedExecutionScheduler.addTest(new PrioritizedTest(C.class, createPriority(c1, c2))); + threadedExecutionScheduler.addTest(new PrioritizedTest(A.class, createPriority(a1, a2))); + threadedExecutionScheduler.addTest(new PrioritizedTest(D.class, createPriority(d1))); + threadedExecutionScheduler.addTest(new PrioritizedTest(E.class, createPriority(e1))); } - private Priority createPriority( RunEntryStatistics runEntryStatistics ) - { - final Priority priority = new Priority( A.class.getName() ); - priority.addItem( runEntryStatistics ); + private Priority createPriority(RunEntryStatistics runEntryStatistics) { + final Priority priority = new Priority(A.class.getName()); + priority.addItem(runEntryStatistics); return priority; } - private Priority createPriority( RunEntryStatistics runEntryStatistics, RunEntryStatistics runEntryStatistics2 ) - { - final Priority priority = new Priority( A.class.getName() ); - priority.addItem( runEntryStatistics ); - priority.addItem( runEntryStatistics2 ); + private Priority createPriority(RunEntryStatistics runEntryStatistics, RunEntryStatistics runEntryStatistics2) { + final Priority priority = new Priority(A.class.getName()); + priority.addItem(runEntryStatistics); + priority.addItem(runEntryStatistics2); return priority; } - private static RunEntryStatistics fromValues( int runTime, int successfulBuilds, Class clazz, String testName ) - { - ClassMethod classMethod = new ClassMethod( clazz.getName(), testName ); - return new RunEntryStatistics( runTime, successfulBuilds, classMethod ); + private static RunEntryStatistics fromValues(int runTime, int successfulBuilds, Class clazz, String testName) { + ClassMethod classMethod = new ClassMethod(clazz.getName(), testName); + return new RunEntryStatistics(runTime, successfulBuilds, classMethod); } - class A - { - } // 500 total - - class B - { - } // 700 total + class A {} // 500 total - class C - { - } // 600 total + class B {} // 700 total - class D - { - } // 400 total + class C {} // 600 total - class E - { - } // 200 total + class D {} // 400 total + class E {} // 200 total } diff --git a/surefire-api/src/test/java/org/apache/maven/surefire/api/stream/AbstractStreamDecoderTest.java b/surefire-api/src/test/java/org/apache/maven/surefire/api/stream/AbstractStreamDecoderTest.java index 96c268ecf2..64fe1361df 100644 --- a/surefire-api/src/test/java/org/apache/maven/surefire/api/stream/AbstractStreamDecoderTest.java +++ b/surefire-api/src/test/java/org/apache/maven/surefire/api/stream/AbstractStreamDecoderTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.api.stream; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.api.stream; import javax.annotation.Nonnull; @@ -120,609 +119,519 @@ * } * */ -@SuppressWarnings( "checkstyle:magicnumber" ) -public class AbstractStreamDecoderTest -{ +@SuppressWarnings("checkstyle:magicnumber") +public class AbstractStreamDecoderTest { private static final Map EVENTS = new HashMap<>(); private static final String PATTERN1 = - "0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789"; + "0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789"; private static final String PATTERN2 = "€ab©c"; private static final byte[] PATTERN2_BYTES = - new byte[] {(byte) -30, (byte) -126, (byte) -84, 'a', 'b', (byte) 0xc2, (byte) 0xa9, 'c'}; + new byte[] {(byte) -30, (byte) -126, (byte) -84, 'a', 'b', (byte) 0xc2, (byte) 0xa9, 'c'}; @BeforeClass - public static void setup() - { - for ( ForkedProcessEventType event : ForkedProcessEventType.values() ) - { + public static void setup() { + for (ForkedProcessEventType event : ForkedProcessEventType.values()) { byte[] array = event.getOpcodeBinary(); - EVENTS.put( new Segment( array, 0, array.length ), event ); + EVENTS.put(new Segment(array, 0, array.length), event); } } @Test - public void shouldDecodeHappyCase() throws Exception - { - CharsetDecoder decoder = UTF_8.newDecoder().onMalformedInput( REPLACE ).onUnmappableCharacter( REPLACE ); - ByteBuffer input = ByteBuffer.allocate( 1024 ); - ( (Buffer) input.put( PATTERN2_BYTES ) ).flip(); + public void shouldDecodeHappyCase() throws Exception { + CharsetDecoder decoder = UTF_8.newDecoder().onMalformedInput(REPLACE).onUnmappableCharacter(REPLACE); + ByteBuffer input = ByteBuffer.allocate(1024); + ((Buffer) input.put(PATTERN2_BYTES)).flip(); int bytesToDecode = PATTERN2_BYTES.length; - Buffer output = CharBuffer.allocate( 1024 ); - int readBytes = invokeMethod( AbstractStreamDecoder.class, "decodeString", decoder, input, output, - bytesToDecode, true, 0 ); + Buffer output = CharBuffer.allocate(1024); + int readBytes = invokeMethod( + AbstractStreamDecoder.class, "decodeString", decoder, input, output, bytesToDecode, true, 0); - assertThat( readBytes ) - .isEqualTo( bytesToDecode ); + assertThat(readBytes).isEqualTo(bytesToDecode); - assertThat( output.flip().toString() ) - .isEqualTo( PATTERN2 ); + assertThat(output.flip().toString()).isEqualTo(PATTERN2); } @Test - public void shouldDecodeShifted() throws Exception - { - CharsetDecoder decoder = UTF_8.newDecoder().onMalformedInput( REPLACE ).onUnmappableCharacter( REPLACE ); - ByteBuffer input = ByteBuffer.allocate( 1024 ); - ( (Buffer) input.put( PATTERN1.getBytes( UTF_8 ) ) - .put( 90, (byte) 'A' ) - .put( 91, (byte) 'B' ) - .put( 92, (byte) 'C' ) ) - .position( 90 ); - Buffer output = CharBuffer.allocate( 1024 ); - int readBytes = - invokeMethod( AbstractStreamDecoder.class, "decodeString", decoder, input, output, 2, true, 0 ); - - assertThat( readBytes ).isEqualTo( 2 ); - - assertThat( output.flip().toString() ) - .isEqualTo( "AB" ); + public void shouldDecodeShifted() throws Exception { + CharsetDecoder decoder = UTF_8.newDecoder().onMalformedInput(REPLACE).onUnmappableCharacter(REPLACE); + ByteBuffer input = ByteBuffer.allocate(1024); + ((Buffer) input.put(PATTERN1.getBytes(UTF_8)) + .put(90, (byte) 'A') + .put(91, (byte) 'B') + .put(92, (byte) 'C')) + .position(90); + Buffer output = CharBuffer.allocate(1024); + int readBytes = invokeMethod(AbstractStreamDecoder.class, "decodeString", decoder, input, output, 2, true, 0); + + assertThat(readBytes).isEqualTo(2); + + assertThat(output.flip().toString()).isEqualTo("AB"); } - @Test( expected = IllegalArgumentException.class ) - public void shouldNotDecode() throws Exception - { + @Test(expected = IllegalArgumentException.class) + public void shouldNotDecode() throws Exception { CharsetDecoder decoder = UTF_8.newDecoder(); - ByteBuffer input = ByteBuffer.allocate( 100 ); + ByteBuffer input = ByteBuffer.allocate(100); int bytesToDecode = 101; - CharBuffer output = CharBuffer.allocate( 1000 ); - invokeMethod( AbstractStreamDecoder.class, "decodeString", decoder, input, output, bytesToDecode, true, 0 ); + CharBuffer output = CharBuffer.allocate(1000); + invokeMethod(AbstractStreamDecoder.class, "decodeString", decoder, input, output, bytesToDecode, true, 0); } @Test - public void shouldReadInt() throws Exception - { - Channel channel = new Channel( new byte[] {0x01, 0x02, 0x03, 0x04, ':'}, 1 ); + public void shouldReadInt() throws Exception { + Channel channel = new Channel(new byte[] {0x01, 0x02, 0x03, 0x04, ':'}, 1); - Mock thread = new Mock( channel, new MockForkNodeArguments(), emptyMap() ); + Mock thread = new Mock(channel, new MockForkNodeArguments(), emptyMap()); Memento memento = thread.new Memento(); - assertThat( thread.readInt( memento ) ) - .isEqualTo( new BigInteger( new byte[] {0x01, 0x02, 0x03, 0x04} ).intValue() ); + assertThat(thread.readInt(memento)).isEqualTo(new BigInteger(new byte[] {0x01, 0x02, 0x03, 0x04}).intValue()); } @Test - public void shouldReadInteger() throws Exception - { - Channel channel = new Channel( new byte[] {(byte) 0xff, 0x01, 0x02, 0x03, 0x04, ':'}, 1 ); + public void shouldReadInteger() throws Exception { + Channel channel = new Channel(new byte[] {(byte) 0xff, 0x01, 0x02, 0x03, 0x04, ':'}, 1); - Mock thread = new Mock( channel, new MockForkNodeArguments(), emptyMap() ); + Mock thread = new Mock(channel, new MockForkNodeArguments(), emptyMap()); Memento memento = thread.new Memento(); - assertThat( thread.readInteger( memento ) ) - .isEqualTo( new BigInteger( new byte[] {0x01, 0x02, 0x03, 0x04} ).intValue() ); + assertThat(thread.readInteger(memento)) + .isEqualTo(new BigInteger(new byte[] {0x01, 0x02, 0x03, 0x04}).intValue()); } @Test - public void shouldReadNullInteger() throws Exception - { - Channel channel = new Channel( new byte[] {(byte) 0x00, ':'}, 1 ); + public void shouldReadNullInteger() throws Exception { + Channel channel = new Channel(new byte[] {(byte) 0x00, ':'}, 1); - Mock thread = new Mock( channel, new MockForkNodeArguments(), emptyMap() ); + Mock thread = new Mock(channel, new MockForkNodeArguments(), emptyMap()); Memento memento = thread.new Memento(); - assertThat( thread.readInteger( memento ) ) - .isNull(); + assertThat(thread.readInteger(memento)).isNull(); } - @Test( expected = EOFException.class ) - public void shouldNotReadString() throws Exception - { - Channel channel = new Channel( PATTERN1.getBytes(), PATTERN1.length() ); - channel.read( ByteBuffer.allocate( 100 ) ); + @Test(expected = EOFException.class) + public void shouldNotReadString() throws Exception { + Channel channel = new Channel(PATTERN1.getBytes(), PATTERN1.length()); + channel.read(ByteBuffer.allocate(100)); - Mock thread = new Mock( channel, new MockForkNodeArguments(), emptyMap() ); + Mock thread = new Mock(channel, new MockForkNodeArguments(), emptyMap()); Memento memento = thread.new Memento(); - invokeMethod( thread, "readString", memento, 10 ); + invokeMethod(thread, "readString", memento, 10); } @Test - public void shouldReadString() throws Exception - { - Channel channel = new Channel( PATTERN1.getBytes(), PATTERN1.length() ); + public void shouldReadString() throws Exception { + Channel channel = new Channel(PATTERN1.getBytes(), PATTERN1.length()); - Mock thread = new Mock( channel, new MockForkNodeArguments(), emptyMap() ); + Mock thread = new Mock(channel, new MockForkNodeArguments(), emptyMap()); Memento memento = thread.new Memento(); - String s = invokeMethod( thread, "readString", memento, 10 ); - assertThat( s ) - .isEqualTo( "0123456789" ); + String s = invokeMethod(thread, "readString", memento, 10); + assertThat(s).isEqualTo("0123456789"); } @Test - public void shouldReadStringOverflowOnNewLine() throws Exception - { - StringBuilder s = new StringBuilder( 1025 ); - for ( int i = 0; i < 10; i++ ) - { - s.append( PATTERN1 ); + public void shouldReadStringOverflowOnNewLine() throws Exception { + StringBuilder s = new StringBuilder(1025); + for (int i = 0; i < 10; i++) { + s.append(PATTERN1); } - s.append( PATTERN1, 0, 23 ); - s.append( "\u00FA\n" ); // 2-bytes encoded character + LF + s.append(PATTERN1, 0, 23); + s.append("\u00FA\n"); // 2-bytes encoded character + LF - Channel channel = new Channel( s.toString().getBytes( UTF_8 ), s.length() ); + Channel channel = new Channel(s.toString().getBytes(UTF_8), s.length()); - Mock thread = new Mock( channel, new MockForkNodeArguments(), emptyMap() ); + Mock thread = new Mock(channel, new MockForkNodeArguments(), emptyMap()); Memento memento = thread.new Memento(); - assertThat( (String) invokeMethod( thread, "readString", memento, 1026 ) ) - .isEqualTo( s.toString() ); + assertThat((String) invokeMethod(thread, "readString", memento, 1026)).isEqualTo(s.toString()); - assertThat ( memento.getByteBuffer().remaining() ) - .isEqualTo( 0 ); + assertThat(memento.getByteBuffer().remaining()).isEqualTo(0); } @Test - public void shouldReadStringOverflowOn4BytesEncodedSymbol() throws Exception - { - StringBuilder s = new StringBuilder( 1025 ); - for ( int i = 0; i < 10; i++ ) - { - s.append( PATTERN1 ); + public void shouldReadStringOverflowOn4BytesEncodedSymbol() throws Exception { + StringBuilder s = new StringBuilder(1025); + for (int i = 0; i < 10; i++) { + s.append(PATTERN1); } - s.append( PATTERN1, 0, 23 ); - s.append( "\uD83D\uDE35" ); // 4-bytes encoded character + s.append(PATTERN1, 0, 23); + s.append("\uD83D\uDE35"); // 4-bytes encoded character - Channel channel = new Channel( s.toString().getBytes( UTF_8 ), s.length() ); + Channel channel = new Channel(s.toString().getBytes(UTF_8), s.length()); - Mock thread = new Mock( channel, new MockForkNodeArguments(), emptyMap() ); + Mock thread = new Mock(channel, new MockForkNodeArguments(), emptyMap()); Memento memento = thread.new Memento(); - assertThat( (String) invokeMethod( thread, "readString", memento, 1027 ) ) - .isEqualTo( s.toString() ); + assertThat((String) invokeMethod(thread, "readString", memento, 1027)).isEqualTo(s.toString()); - assertThat ( memento.getByteBuffer().remaining() ) - .isEqualTo( 0 ); + assertThat(memento.getByteBuffer().remaining()).isEqualTo(0); } @Test - public void shouldReadStringShiftedBuffer() throws Exception - { - StringBuilder s = new StringBuilder( 1100 ); - for ( int i = 0; i < 11; i++ ) - { - s.append( PATTERN1 ); + public void shouldReadStringShiftedBuffer() throws Exception { + StringBuilder s = new StringBuilder(1100); + for (int i = 0; i < 11; i++) { + s.append(PATTERN1); } - Channel channel = new Channel( s.toString().getBytes( UTF_8 ), s.length() ); + Channel channel = new Channel(s.toString().getBytes(UTF_8), s.length()); - Mock thread = new Mock( channel, new MockForkNodeArguments(), emptyMap() ); + Mock thread = new Mock(channel, new MockForkNodeArguments(), emptyMap()); Memento memento = thread.new Memento(); // whatever position will be compacted to 0 - ( (Buffer) ( (Buffer) memento.getByteBuffer() ).limit( 974 ) ).position( 974 ); - assertThat( (String) invokeMethod( thread, "readString", memento, PATTERN1.length() + 3 ) ) - .isEqualTo( PATTERN1 + "012" ); + ((Buffer) ((Buffer) memento.getByteBuffer()).limit(974)).position(974); + assertThat((String) invokeMethod(thread, "readString", memento, PATTERN1.length() + 3)) + .isEqualTo(PATTERN1 + "012"); } @Test - public void shouldReadStringShiftedInput() throws Exception - { - StringBuilder s = new StringBuilder( 1100 ); - for ( int i = 0; i < 11; i++ ) - { - s.append( PATTERN1 ); + public void shouldReadStringShiftedInput() throws Exception { + StringBuilder s = new StringBuilder(1100); + for (int i = 0; i < 11; i++) { + s.append(PATTERN1); } - Channel channel = new Channel( s.toString().getBytes( UTF_8 ), s.length() ); - channel.read( ByteBuffer.allocate( 997 ) ); + Channel channel = new Channel(s.toString().getBytes(UTF_8), s.length()); + channel.read(ByteBuffer.allocate(997)); - Mock thread = new Mock( channel, new MockForkNodeArguments(), emptyMap() ); + Mock thread = new Mock(channel, new MockForkNodeArguments(), emptyMap()); Memento memento = thread.new Memento(); - assertThat( (String) invokeMethod( thread, "readString", memento, PATTERN1.length() ) ) - .isEqualTo( "789" + PATTERN1.substring( 0, 97 ) ); + assertThat((String) invokeMethod(thread, "readString", memento, PATTERN1.length())) + .isEqualTo("789" + PATTERN1.substring(0, 97)); } @Test - public void shouldReadMultipleStringsAndShiftedInput() throws Exception - { - StringBuilder s = new StringBuilder( 5000 ); + public void shouldReadMultipleStringsAndShiftedInput() throws Exception { + StringBuilder s = new StringBuilder(5000); - for ( int i = 0; i < 50; i++ ) - { - s.append( PATTERN1 ); + for (int i = 0; i < 50; i++) { + s.append(PATTERN1); } - Channel channel = new Channel( s.toString().getBytes( UTF_8 ), s.length() ); - channel.read( ByteBuffer.allocate( 1997 ) ); + Channel channel = new Channel(s.toString().getBytes(UTF_8), s.length()); + channel.read(ByteBuffer.allocate(1997)); - Mock thread = new Mock( channel, new MockForkNodeArguments(), emptyMap() ); + Mock thread = new Mock(channel, new MockForkNodeArguments(), emptyMap()); Memento memento = thread.new Memento(); // whatever position will be compacted to 0 - ( (Buffer) memento.getByteBuffer() ).limit( 974 ).position( 974 ); + ((Buffer) memento.getByteBuffer()).limit(974).position(974); - StringBuilder expected = new StringBuilder( "789" ); - for ( int i = 0; i < 11; i++ ) - { - expected.append( PATTERN1 ); + StringBuilder expected = new StringBuilder("789"); + for (int i = 0; i < 11; i++) { + expected.append(PATTERN1); } - expected.setLength( 1100 ); - assertThat( (String) invokeMethod( thread, "readString", memento, 1100 ) ) - .isEqualTo( expected.toString() ); + expected.setLength(1100); + assertThat((String) invokeMethod(thread, "readString", memento, 1100)).isEqualTo(expected.toString()); } @Test - public void shouldDecode3BytesEncodedSymbol() throws Exception - { + public void shouldDecode3BytesEncodedSymbol() throws Exception { byte[] encodedSymbol = new byte[] {(byte) -30, (byte) -126, (byte) -84}; int countSymbols = 1024; byte[] input = new byte[encodedSymbol.length * countSymbols]; - for ( int i = 0; i < countSymbols; i++ ) - { - arraycopy( encodedSymbol, 0, input, encodedSymbol.length * i, encodedSymbol.length ); + for (int i = 0; i < countSymbols; i++) { + arraycopy(encodedSymbol, 0, input, encodedSymbol.length * i, encodedSymbol.length); } - Channel channel = new Channel( input, 64 * 1024 ); - Mock thread = new Mock( channel, new MockForkNodeArguments(), emptyMap() ); + Channel channel = new Channel(input, 64 * 1024); + Mock thread = new Mock(channel, new MockForkNodeArguments(), emptyMap()); Memento memento = thread.new Memento(); - String decodedOutput = invokeMethod( thread, "readString", memento, input.length ); + String decodedOutput = invokeMethod(thread, "readString", memento, input.length); - assertThat( decodedOutput ) - .isEqualTo( new String( input, 0, input.length, UTF_8 ) ); + assertThat(decodedOutput).isEqualTo(new String(input, 0, input.length, UTF_8)); } @Test - public void shouldDecode100Bytes() throws Exception - { - CharsetDecoder decoder = DEFAULT_STREAM_ENCODING.newDecoder() - .onMalformedInput( REPLACE ) - .onUnmappableCharacter( REPLACE ); + public void shouldDecode100Bytes() throws Exception { + CharsetDecoder decoder = + DEFAULT_STREAM_ENCODING.newDecoder().onMalformedInput(REPLACE).onUnmappableCharacter(REPLACE); // empty stream: CharsetDecoder + ByteBuffer.allocate( 0 ) makes 11.5 nanos // empty stream: CharsetDecoder + ByteBuffer.allocate( 0 ) + toString() makes 16.1 nanos - ByteBuffer buffer = ByteBuffer.wrap( PATTERN1.getBytes( UTF_8 ) ); - CharBuffer chars = CharBuffer.allocate( 100 ); + ByteBuffer buffer = ByteBuffer.wrap(PATTERN1.getBytes(UTF_8)); + CharBuffer chars = CharBuffer.allocate(100); // uncomment this section for a proper measurement of the exec time - TimeUnit.SECONDS.sleep( 2 ); + TimeUnit.SECONDS.sleep(2); System.gc(); - TimeUnit.SECONDS.sleep( 5 ); + TimeUnit.SECONDS.sleep(5); String s = null; long l1 = System.currentTimeMillis(); - for ( int i = 0; i < 10_000_000; i++ ) - { - decoder.reset() - .decode( buffer, chars, true ); // CharsetDecoder 71 nanos - s = ( (Buffer) chars ).flip().toString(); // CharsetDecoder + toString = 91 nanos - ( (Buffer) buffer ).clear(); - ( (Buffer) chars ).clear(); + for (int i = 0; i < 10_000_000; i++) { + decoder.reset().decode(buffer, chars, true); // CharsetDecoder 71 nanos + s = ((Buffer) chars).flip().toString(); // CharsetDecoder + toString = 91 nanos + ((Buffer) buffer).clear(); + ((Buffer) chars).clear(); } long l2 = System.currentTimeMillis(); - System.out.println( "decoded 100 bytes within " + ( l2 - l1 ) + " millis (10 million cycles)" ); - assertThat( s ) - .isEqualTo( PATTERN1 ); + System.out.println("decoded 100 bytes within " + (l2 - l1) + " millis (10 million cycles)"); + assertThat(s).isEqualTo(PATTERN1); } @Test - public void shouldReadEventType() throws Exception - { + public void shouldReadEventType() throws Exception { byte[] array = BOOTERCODE_STDOUT.getOpcodeBinary(); Map messageType = - singletonMap( new Segment( array, 0, array.length ), BOOTERCODE_STDOUT ); + singletonMap(new Segment(array, 0, array.length), BOOTERCODE_STDOUT); - byte[] stream = ":maven-surefire-event:\u000E:std-out-stream:".getBytes( UTF_8 ); - Channel channel = new Channel( stream, 1 ); - Mock thread = new Mock( channel, new MockForkNodeArguments(), messageType ); + byte[] stream = ":maven-surefire-event:\u000E:std-out-stream:".getBytes(UTF_8); + Channel channel = new Channel(stream, 1); + Mock thread = new Mock(channel, new MockForkNodeArguments(), messageType); Memento memento = thread.new Memento(); - memento.setCharset( UTF_8 ); + memento.setCharset(UTF_8); - ForkedProcessEventType eventType = thread.readMessageType( memento ); - assertThat( eventType ) - .isEqualTo( BOOTERCODE_STDOUT ); + ForkedProcessEventType eventType = thread.readMessageType(memento); + assertThat(eventType).isEqualTo(BOOTERCODE_STDOUT); } - @Test( expected = EOFException.class ) - public void shouldEventTypeReachedEndOfStream() throws Exception - { - byte[] stream = ":maven-surefire-event:\u000E:xxx".getBytes( UTF_8 ); - Channel channel = new Channel( stream, 1 ); - Mock thread = new Mock( channel, new MockForkNodeArguments(), EVENTS ); + @Test(expected = EOFException.class) + public void shouldEventTypeReachedEndOfStream() throws Exception { + byte[] stream = ":maven-surefire-event:\u000E:xxx".getBytes(UTF_8); + Channel channel = new Channel(stream, 1); + Mock thread = new Mock(channel, new MockForkNodeArguments(), EVENTS); Memento memento = thread.new Memento(); - memento.setCharset( UTF_8 ); - thread.readMessageType( memento ); + memento.setCharset(UTF_8); + thread.readMessageType(memento); } - @Test( expected = MalformedFrameException.class ) - public void shouldEventTypeReachedMalformedHeader() throws Exception - { - byte[] stream = ":xxxxx-xxxxxxxx-xxxxx:\u000E:xxx".getBytes( UTF_8 ); - Channel channel = new Channel( stream, 1 ); - Mock thread = new Mock( channel, new MockForkNodeArguments(), emptyMap() ); + @Test(expected = MalformedFrameException.class) + public void shouldEventTypeReachedMalformedHeader() throws Exception { + byte[] stream = ":xxxxx-xxxxxxxx-xxxxx:\u000E:xxx".getBytes(UTF_8); + Channel channel = new Channel(stream, 1); + Mock thread = new Mock(channel, new MockForkNodeArguments(), emptyMap()); Memento memento = thread.new Memento(); - memento.setCharset( UTF_8 ); - thread.readMessageType( memento ); + memento.setCharset(UTF_8); + thread.readMessageType(memento); } @Test - public void shouldReadEmptyString() throws Exception - { - byte[] stream = "\u0000\u0000\u0000\u0000::".getBytes( UTF_8 ); - Channel channel = new Channel( stream, 1 ); - Mock thread = new Mock( channel, new MockForkNodeArguments(), emptyMap() ); + public void shouldReadEmptyString() throws Exception { + byte[] stream = "\u0000\u0000\u0000\u0000::".getBytes(UTF_8); + Channel channel = new Channel(stream, 1); + Mock thread = new Mock(channel, new MockForkNodeArguments(), emptyMap()); Memento memento = thread.new Memento(); - memento.setCharset( UTF_8 ); + memento.setCharset(UTF_8); - assertThat( thread.readString( memento ) ) - .isEmpty(); + assertThat(thread.readString(memento)).isEmpty(); } @Test - public void shouldReadNullString() throws Exception - { - byte[] stream = "\u0000\u0000\u0000\u0001:\u0000:".getBytes( UTF_8 ); - Channel channel = new Channel( stream, 1 ); - Mock thread = new Mock( channel, new MockForkNodeArguments(), emptyMap() ); + public void shouldReadNullString() throws Exception { + byte[] stream = "\u0000\u0000\u0000\u0001:\u0000:".getBytes(UTF_8); + Channel channel = new Channel(stream, 1); + Mock thread = new Mock(channel, new MockForkNodeArguments(), emptyMap()); Memento memento = thread.new Memento(); - memento.setCharset( UTF_8 ); + memento.setCharset(UTF_8); - assertThat( thread.readString( memento ) ) - .isNull(); + assertThat(thread.readString(memento)).isNull(); } @Test - public void shouldReadSingleCharString() throws Exception - { - byte[] stream = "\u0000\u0000\u0000\u0001:A:".getBytes( UTF_8 ); - Channel channel = new Channel( stream, 1 ); - Mock thread = new Mock( channel, new MockForkNodeArguments(), emptyMap() ); + public void shouldReadSingleCharString() throws Exception { + byte[] stream = "\u0000\u0000\u0000\u0001:A:".getBytes(UTF_8); + Channel channel = new Channel(stream, 1); + Mock thread = new Mock(channel, new MockForkNodeArguments(), emptyMap()); Memento memento = thread.new Memento(); - memento.setCharset( UTF_8 ); + memento.setCharset(UTF_8); - assertThat( thread.readString( memento ) ) - .isEqualTo( "A" ); + assertThat(thread.readString(memento)).isEqualTo("A"); } @Test - public void shouldReadThreeCharactersString() throws Exception - { - byte[] stream = "\u0000\u0000\u0000\u0003:ABC:".getBytes( UTF_8 ); - Channel channel = new Channel( stream, 1 ); - Mock thread = new Mock( channel, new MockForkNodeArguments(), emptyMap() ); + public void shouldReadThreeCharactersString() throws Exception { + byte[] stream = "\u0000\u0000\u0000\u0003:ABC:".getBytes(UTF_8); + Channel channel = new Channel(stream, 1); + Mock thread = new Mock(channel, new MockForkNodeArguments(), emptyMap()); Memento memento = thread.new Memento(); - memento.setCharset( UTF_8 ); + memento.setCharset(UTF_8); - assertThat( thread.readString( memento ) ) - .isEqualTo( "ABC" ); + assertThat(thread.readString(memento)).isEqualTo("ABC"); } @Test - public void shouldReadDefaultCharset() throws Exception - { - byte[] stream = "\u0005:UTF-8:".getBytes( US_ASCII ); - Channel channel = new Channel( stream, 1 ); - Mock thread = new Mock( channel, new MockForkNodeArguments(), emptyMap() ); + public void shouldReadDefaultCharset() throws Exception { + byte[] stream = "\u0005:UTF-8:".getBytes(US_ASCII); + Channel channel = new Channel(stream, 1); + Mock thread = new Mock(channel, new MockForkNodeArguments(), emptyMap()); Memento memento = thread.new Memento(); - memento.setCharset( UTF_8 ); + memento.setCharset(UTF_8); - assertThat( thread.readCharset( memento ) ) - .isNotNull() - .isEqualTo( UTF_8 ); + assertThat(thread.readCharset(memento)).isNotNull().isEqualTo(UTF_8); } @Test - public void shouldReadNonDefaultCharset() throws Exception - { - byte[] stream = ( (char) 10 + ":ISO_8859_1:" ).getBytes( US_ASCII ); - Channel channel = new Channel( stream, 1 ); - Mock thread = new Mock( channel, new MockForkNodeArguments(), emptyMap() ); + public void shouldReadNonDefaultCharset() throws Exception { + byte[] stream = ((char) 10 + ":ISO_8859_1:").getBytes(US_ASCII); + Channel channel = new Channel(stream, 1); + Mock thread = new Mock(channel, new MockForkNodeArguments(), emptyMap()); Memento memento = thread.new Memento(); - memento.setCharset( UTF_8 ); + memento.setCharset(UTF_8); - assertThat( thread.readCharset( memento ) ) - .isNotNull() - .isEqualTo( ISO_8859_1 ); + assertThat(thread.readCharset(memento)).isNotNull().isEqualTo(ISO_8859_1); } @Test - public void shouldSetNonDefaultCharset() - { + public void shouldSetNonDefaultCharset() { byte[] stream = {}; - Channel channel = new Channel( stream, 1 ); - Mock thread = new Mock( channel, new MockForkNodeArguments(), emptyMap() ); + Channel channel = new Channel(stream, 1); + Mock thread = new Mock(channel, new MockForkNodeArguments(), emptyMap()); Memento memento = thread.new Memento(); - memento.setCharset( ISO_8859_1 ); - assertThat( memento.getDecoder().charset() ).isEqualTo( ISO_8859_1 ); + memento.setCharset(ISO_8859_1); + assertThat(memento.getDecoder().charset()).isEqualTo(ISO_8859_1); - memento.setCharset( UTF_8 ); - assertThat( memento.getDecoder().charset() ).isEqualTo( UTF_8 ); + memento.setCharset(UTF_8); + assertThat(memento.getDecoder().charset()).isEqualTo(UTF_8); memento.reset(); - assertThat( memento.getDecoder() ).isNotNull(); - assertThat( memento.getDecoder().charset() ).isEqualTo( UTF_8 ); + assertThat(memento.getDecoder()).isNotNull(); + assertThat(memento.getDecoder().charset()).isEqualTo(UTF_8); } - @Test( expected = MalformedFrameException.class ) - public void malformedCharset() throws Exception - { - byte[] stream = ( (char) 8 + ":ISO_8859:" ).getBytes( US_ASCII ); - Channel channel = new Channel( stream, 1 ); - Mock thread = new Mock( channel, new MockForkNodeArguments(), emptyMap() ); + @Test(expected = MalformedFrameException.class) + public void malformedCharset() throws Exception { + byte[] stream = ((char) 8 + ":ISO_8859:").getBytes(US_ASCII); + Channel channel = new Channel(stream, 1); + Mock thread = new Mock(channel, new MockForkNodeArguments(), emptyMap()); Memento memento = thread.new Memento(); - memento.setCharset( UTF_8 ); + memento.setCharset(UTF_8); - thread.readCharset( memento ); + thread.readCharset(memento); } - private static class Channel implements ReadableByteChannel - { + private static class Channel implements ReadableByteChannel { private final byte[] bytes; private final int chunkSize; protected int i; - Channel( byte[] bytes, int chunkSize ) - { + Channel(byte[] bytes, int chunkSize) { this.bytes = bytes; this.chunkSize = chunkSize; } @Override - public int read( ByteBuffer dst ) - { - if ( i == bytes.length ) - { + public int read(ByteBuffer dst) { + if (i == bytes.length) { return -1; - } - else if ( dst.hasRemaining() ) - { - int length = min( min( chunkSize, bytes.length - i ), dst.remaining() ) ; - dst.put( bytes, i, length ); + } else if (dst.hasRemaining()) { + int length = min(min(chunkSize, bytes.length - i), dst.remaining()); + dst.put(bytes, i, length); i += length; return length; - } - else - { + } else { return 0; } } @Override - public boolean isOpen() - { + public boolean isOpen() { return false; } @Override - public void close() - { - } + public void close() {} } - private static class MockForkNodeArguments implements ForkNodeArguments - { + private static class MockForkNodeArguments implements ForkNodeArguments { @Nonnull @Override - public String getSessionId() - { + public String getSessionId() { return null; } @Override - public int getForkChannelId() - { + public int getForkChannelId() { return 0; } @Nonnull @Override - public File dumpStreamText( @Nonnull String text ) - { + public File dumpStreamText(@Nonnull String text) { return null; } @Nonnull @Override - public File dumpStreamException( @Nonnull Throwable t ) - { + public File dumpStreamException(@Nonnull Throwable t) { return null; } @Override - public void logWarningAtEnd( @Nonnull String text ) - { - } + public void logWarningAtEnd(@Nonnull String text) {} @Nonnull @Override - public ConsoleLogger getConsoleLogger() - { + public ConsoleLogger getConsoleLogger() { return null; } @Nonnull @Override - public Object getConsoleLock() - { + public Object getConsoleLock() { return new Object(); } @Override - public File getEventStreamBinaryFile() - { + public File getEventStreamBinaryFile() { return null; } @Override - public File getCommandStreamBinaryFile() - { + public File getCommandStreamBinaryFile() { return null; } } - private static class Mock extends AbstractStreamDecoder - { - protected Mock( @Nonnull ReadableByteChannel channel, @Nonnull ForkNodeArguments arguments, - @Nonnull Map messageTypes ) - { - super( channel, arguments, messageTypes ); + private static class Mock extends AbstractStreamDecoder { + protected Mock( + @Nonnull ReadableByteChannel channel, + @Nonnull ForkNodeArguments arguments, + @Nonnull Map messageTypes) { + super(channel, arguments, messageTypes); } @Override - public Event decode( @Nonnull Memento memento ) throws MalformedChannelException - { + public Event decode(@Nonnull Memento memento) throws MalformedChannelException { throw new MalformedChannelException(); } @Nonnull @Override - protected byte[] getEncodedMagicNumber() - { + protected byte[] getEncodedMagicNumber() { return Constants.MAGIC_NUMBER_FOR_EVENTS_BYTES; } @Nonnull @Override - protected SegmentType[] nextSegmentType( @Nonnull ForkedProcessEventType messageType ) - { + protected SegmentType[] nextSegmentType(@Nonnull ForkedProcessEventType messageType) { return new SegmentType[] {END_OF_FRAME}; } @Nonnull @Override - protected Event toMessage( @Nonnull ForkedProcessEventType messageType, @Nonnull Memento memento ) - { + protected Event toMessage(@Nonnull ForkedProcessEventType messageType, @Nonnull Memento memento) { return null; } @Override - public void close() throws Exception - { - } + public void close() throws Exception {} } } diff --git a/surefire-api/src/test/java/org/apache/maven/surefire/api/stream/AbstractStreamEncoderTest.java b/surefire-api/src/test/java/org/apache/maven/surefire/api/stream/AbstractStreamEncoderTest.java index e28823eb09..1f9ad6e467 100644 --- a/surefire-api/src/test/java/org/apache/maven/surefire/api/stream/AbstractStreamEncoderTest.java +++ b/surefire-api/src/test/java/org/apache/maven/surefire/api/stream/AbstractStreamEncoderTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.api.stream; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,18 +16,20 @@ * specific language governing permissions and limitations * under the License. */ - -import org.apache.maven.surefire.api.booter.ForkedProcessEventType; -import org.apache.maven.surefire.api.util.internal.WritableBufferedByteChannel; -import org.junit.Test; +package org.apache.maven.surefire.api.stream; import javax.annotation.Nonnull; + import java.io.ByteArrayOutputStream; import java.nio.Buffer; import java.nio.ByteBuffer; import java.nio.charset.Charset; import java.nio.charset.CharsetEncoder; +import org.apache.maven.surefire.api.booter.ForkedProcessEventType; +import org.apache.maven.surefire.api.util.internal.WritableBufferedByteChannel; +import org.junit.Test; + import static java.nio.charset.StandardCharsets.US_ASCII; import static java.nio.charset.StandardCharsets.UTF_8; import static org.apache.maven.surefire.api.booter.Constants.MAGIC_NUMBER_FOR_EVENTS_BYTES; @@ -60,275 +60,354 @@ /** * */ -@SuppressWarnings( { "checkstyle:linelength", "checkstyle:magicnumber" } ) -public class AbstractStreamEncoderTest -{ +@SuppressWarnings({"checkstyle:linelength", "checkstyle:magicnumber"}) +public class AbstractStreamEncoderTest { @Test - public void shouldComputeStreamPreemptiveLength() - { - Encoder streamEncoder = new Encoder( new DummyChannel() ); + public void shouldComputeStreamPreemptiveLength() { + Encoder streamEncoder = new Encoder(new DummyChannel()); CharsetEncoder encoder = streamEncoder.newCharsetEncoder(); // :maven-surefire-event:8:sys-prop:10:normal-run:1:5:UTF-8:0003:kkk:0003:vvv: - assertThat( streamEncoder.estimateBufferLength( BOOTERCODE_SYSPROPS.getOpcodeBinary().length, NORMAL_RUN, - encoder, 0, 1, "k", "v" ) ) - .isEqualTo( 82 ); + assertThat(streamEncoder.estimateBufferLength( + BOOTERCODE_SYSPROPS.getOpcodeBinary().length, NORMAL_RUN, encoder, 0, 1, "k", "v")) + .isEqualTo(82); // :maven-surefire-event:16:testset-starting:10:normal-run:1:5:UTF-8:0003:sss:0003:sss:0003:sss:0003:sss:0003:sss:0003:sss:X0003:0003:sss:0003:sss:0003:sss: - assertThat( streamEncoder.estimateBufferLength( BOOTERCODE_TESTSET_STARTING.getOpcodeBinary().length, - NORMAL_RUN, encoder, 1, 1, "s", "s", "s", "s", "s", "s", "s", "s", "s" ) ) - .isEqualTo( 159 ); + assertThat(streamEncoder.estimateBufferLength( + BOOTERCODE_TESTSET_STARTING.getOpcodeBinary().length, + NORMAL_RUN, + encoder, + 1, + 1, + "s", + "s", + "s", + "s", + "s", + "s", + "s", + "s", + "s")) + .isEqualTo(159); // :maven-surefire-event:17:testset-completed:10:normal-run:1:5:UTF-8:0003:sss:0003:sss:0003:sss:0003:sss:0003:sss:0003:sss:X0003:0003:sss:0003:sss:0003:sss: - assertThat( streamEncoder.estimateBufferLength( BOOTERCODE_TESTSET_COMPLETED.getOpcodeBinary().length, - NORMAL_RUN, encoder, 1, 1, "s", "s", "s", "s", "s", "s", "s", "s", "s" ) ) - .isEqualTo( 160 ); + assertThat(streamEncoder.estimateBufferLength( + BOOTERCODE_TESTSET_COMPLETED.getOpcodeBinary().length, + NORMAL_RUN, + encoder, + 1, + 1, + "s", + "s", + "s", + "s", + "s", + "s", + "s", + "s", + "s")) + .isEqualTo(160); // :maven-surefire-event:13:test-starting:10:normal-run:1:5:UTF-8:0003:sss:0003:sss:0003:sss:0003:sss:0003:sss:0003:sss:X0003:0003:sss:0003:sss:0003:sss: - assertThat( streamEncoder.estimateBufferLength( BOOTERCODE_TEST_STARTING.getOpcodeBinary().length, - NORMAL_RUN, encoder, 1, 1, "s", "s", "s", "s", "s", "s", "s", "s", "s" ) ) - .isEqualTo( 156 ); + assertThat(streamEncoder.estimateBufferLength( + BOOTERCODE_TEST_STARTING.getOpcodeBinary().length, + NORMAL_RUN, + encoder, + 1, + 1, + "s", + "s", + "s", + "s", + "s", + "s", + "s", + "s", + "s")) + .isEqualTo(156); // :maven-surefire-event:14:test-succeeded:10:normal-run:1:5:UTF-8:0003:sss:0003:sss:0003:sss:0003:sss:0003:sss:0003:sss:X0003:0003:sss:0003:sss:0003:sss: - assertThat( streamEncoder.estimateBufferLength( BOOTERCODE_TEST_SUCCEEDED.getOpcodeBinary().length, - NORMAL_RUN, encoder, 1, 1, "s", "s", "s", "s", "s", "s", "s", "s", "s" ) ) - .isEqualTo( 157 ); + assertThat(streamEncoder.estimateBufferLength( + BOOTERCODE_TEST_SUCCEEDED.getOpcodeBinary().length, + NORMAL_RUN, + encoder, + 1, + 1, + "s", + "s", + "s", + "s", + "s", + "s", + "s", + "s", + "s")) + .isEqualTo(157); // :maven-surefire-event:11:test-failed:10:normal-run:1:5:UTF-8:0003:sss:0003:sss:0003:sss:0003:sss:0003:sss:0003:sss:X0003:0003:sss:0003:sss:0003:sss: - assertThat( streamEncoder.estimateBufferLength( BOOTERCODE_TEST_FAILED.getOpcodeBinary().length, - NORMAL_RUN, encoder, 1, 1, "s", "s", "s", "s", "s", "s", "s", "s", "s" ) ) - .isEqualTo( 154 ); + assertThat(streamEncoder.estimateBufferLength( + BOOTERCODE_TEST_FAILED.getOpcodeBinary().length, + NORMAL_RUN, + encoder, + 1, + 1, + "s", + "s", + "s", + "s", + "s", + "s", + "s", + "s", + "s")) + .isEqualTo(154); // :maven-surefire-event:12:test-skipped:10:normal-run:1:5:UTF-8:0003:sss:0003:sss:0003:sss:0003:sss:0003:sss:0003:sss:X0003:0003:sss:0003:sss:0003:sss: - assertThat( streamEncoder.estimateBufferLength( BOOTERCODE_TEST_SKIPPED.getOpcodeBinary().length, - NORMAL_RUN, encoder, 1, 1, "s", "s", "s", "s", "s", "s", "s", "s", "s" ) ) - .isEqualTo( 155 ); + assertThat(streamEncoder.estimateBufferLength( + BOOTERCODE_TEST_SKIPPED.getOpcodeBinary().length, + NORMAL_RUN, + encoder, + 1, + 1, + "s", + "s", + "s", + "s", + "s", + "s", + "s", + "s", + "s")) + .isEqualTo(155); // :maven-surefire-event:10:test-error:10:normal-run:1:5:UTF-8:0003:sss:0003:sss:0003:sss:0003:sss:0003:sss:0003:sss:X0003:0003:sss:0003:sss:0003:sss: - assertThat( streamEncoder.estimateBufferLength( BOOTERCODE_TEST_ERROR.getOpcodeBinary().length, - NORMAL_RUN, encoder, 1, 1, "s", "s", "s", "s", "s", "s", "s", "s", "s" ) ) - .isEqualTo( 153 ); + assertThat(streamEncoder.estimateBufferLength( + BOOTERCODE_TEST_ERROR.getOpcodeBinary().length, + NORMAL_RUN, + encoder, + 1, + 1, + "s", + "s", + "s", + "s", + "s", + "s", + "s", + "s", + "s")) + .isEqualTo(153); // :maven-surefire-event:23:test-assumption-failure:10:normal-run:1:5:UTF-8:0003:sss:0003:sss:0003:sss:0003:sss:0003:sss:0003:sss:X0003:0003:sss:0003:sss:0003:sss: - assertThat( streamEncoder.estimateBufferLength( BOOTERCODE_TEST_ASSUMPTIONFAILURE.getOpcodeBinary().length, - NORMAL_RUN, encoder, 1, 1, "s", "s", "s", "s", "s", "s", "s", "s", "s" ) ) - .isEqualTo( 166 ); + assertThat(streamEncoder.estimateBufferLength( + BOOTERCODE_TEST_ASSUMPTIONFAILURE.getOpcodeBinary().length, + NORMAL_RUN, + encoder, + 1, + 1, + "s", + "s", + "s", + "s", + "s", + "s", + "s", + "s", + "s")) + .isEqualTo(166); // :maven-surefire-event:14:std-out-stream:10:normal-run:1:5:UTF-8:0003:sss: - assertThat( streamEncoder.estimateBufferLength( BOOTERCODE_STDOUT.getOpcodeBinary().length, - NORMAL_RUN, encoder, 0, 1, "s" ) ) - .isEqualTo( 79 ); + assertThat(streamEncoder.estimateBufferLength( + BOOTERCODE_STDOUT.getOpcodeBinary().length, NORMAL_RUN, encoder, 0, 1, "s")) + .isEqualTo(79); // :maven-surefire-event:23:std-out-stream-new-line:10:normal-run:1:5:UTF-8:0003:sss: - assertThat( streamEncoder.estimateBufferLength( BOOTERCODE_STDOUT_NEW_LINE.getOpcodeBinary().length, - NORMAL_RUN, encoder, 0, 1, "s" ) ) - .isEqualTo( 88 ); + assertThat(streamEncoder.estimateBufferLength( + BOOTERCODE_STDOUT_NEW_LINE.getOpcodeBinary().length, NORMAL_RUN, encoder, 0, 1, "s")) + .isEqualTo(88); // :maven-surefire-event:14:std-err-stream:10:normal-run:1:5:UTF-8:0003:sss: - assertThat( streamEncoder.estimateBufferLength( BOOTERCODE_STDERR.getOpcodeBinary().length, - NORMAL_RUN, encoder, 0, 1, "s" ) ) - .isEqualTo( 79 ); + assertThat(streamEncoder.estimateBufferLength( + BOOTERCODE_STDERR.getOpcodeBinary().length, NORMAL_RUN, encoder, 0, 1, "s")) + .isEqualTo(79); // :maven-surefire-event:23:std-err-stream-new-line:10:normal-run:1:5:UTF-8:0003:sss: - assertThat( streamEncoder.estimateBufferLength( BOOTERCODE_STDERR_NEW_LINE.getOpcodeBinary().length, - NORMAL_RUN, encoder, 0, 1, "s" ) ) - .isEqualTo( 88 ); + assertThat(streamEncoder.estimateBufferLength( + BOOTERCODE_STDERR_NEW_LINE.getOpcodeBinary().length, NORMAL_RUN, encoder, 0, 1, "s")) + .isEqualTo(88); // :maven-surefire-event:16:console-info-log:0::5:UTF-8:0001:s: - assertThat( streamEncoder.estimateBufferLength( BOOTERCODE_CONSOLE_INFO.getOpcodeBinary().length, - null, encoder, 0, 0, "s" ) ) - .isEqualTo( 61 ); + assertThat(streamEncoder.estimateBufferLength( + BOOTERCODE_CONSOLE_INFO.getOpcodeBinary().length, null, encoder, 0, 0, "s")) + .isEqualTo(61); // :maven-surefire-event:17:console-debug-log:0::5:UTF-8:0001:s: - assertThat( streamEncoder.estimateBufferLength( BOOTERCODE_CONSOLE_DEBUG.getOpcodeBinary().length, - null, encoder, 0, 0, "s" ) ) - .isEqualTo( 62 ); + assertThat(streamEncoder.estimateBufferLength( + BOOTERCODE_CONSOLE_DEBUG.getOpcodeBinary().length, null, encoder, 0, 0, "s")) + .isEqualTo(62); // :maven-surefire-event:19:console-warning-log:0::5:UTF-8:0001:s: - assertThat( streamEncoder.estimateBufferLength( BOOTERCODE_CONSOLE_WARNING.getOpcodeBinary().length, - null, encoder, 0, 0, "s" ) ) - .isEqualTo( 64 ); + assertThat(streamEncoder.estimateBufferLength( + BOOTERCODE_CONSOLE_WARNING.getOpcodeBinary().length, null, encoder, 0, 0, "s")) + .isEqualTo(64); // :maven-surefire-event:17:console-error-log:0::5:UTF-8:0001:s: - assertThat( streamEncoder.estimateBufferLength( BOOTERCODE_CONSOLE_ERROR.getOpcodeBinary().length, - null, encoder, 0, 0, "s" ) ) - .isEqualTo( 62 ); + assertThat(streamEncoder.estimateBufferLength( + BOOTERCODE_CONSOLE_ERROR.getOpcodeBinary().length, null, encoder, 0, 0, "s")) + .isEqualTo(62); // :maven-surefire-event:3:bye:0:: - assertThat( streamEncoder.estimateBufferLength( BOOTERCODE_BYE.getOpcodeBinary().length, - null, null, 0, 0 ) ) - .isEqualTo( 31 ); + assertThat(streamEncoder.estimateBufferLength(BOOTERCODE_BYE.getOpcodeBinary().length, null, null, 0, 0)) + .isEqualTo(31); // :maven-surefire-event:17:stop-on-next-test:0:: - assertThat( streamEncoder.estimateBufferLength( BOOTERCODE_STOP_ON_NEXT_TEST.getOpcodeBinary().length, - null, null, 0, 0 ) ) - .isEqualTo( 45 ); + assertThat(streamEncoder.estimateBufferLength( + BOOTERCODE_STOP_ON_NEXT_TEST.getOpcodeBinary().length, null, null, 0, 0)) + .isEqualTo(45); // :maven-surefire-event:9:next-test:0:: - assertThat( streamEncoder.estimateBufferLength( BOOTERCODE_NEXT_TEST.getOpcodeBinary().length, - null, null, 0, 0 ) ) - .isEqualTo( 37 ); + assertThat(streamEncoder.estimateBufferLength(BOOTERCODE_NEXT_TEST.getOpcodeBinary().length, null, null, 0, 0)) + .isEqualTo(37); // :maven-surefire-event:14:jvm-exit-error:0:: - assertThat( streamEncoder.estimateBufferLength( BOOTERCODE_JVM_EXIT_ERROR.getOpcodeBinary().length, - null, null, 0, 0 ) ) - .isEqualTo( 42 ); + assertThat(streamEncoder.estimateBufferLength( + BOOTERCODE_JVM_EXIT_ERROR.getOpcodeBinary().length, null, null, 0, 0)) + .isEqualTo(42); } @Test - public void testSendOpcode() - { - Encoder streamEncoder = new Encoder( new DummyChannel() ); - ByteBuffer result = ByteBuffer.allocate( 128 ); - streamEncoder.encodeHeader( result, BOOTERCODE_TEST_ERROR, NORMAL_RUN, 1L ); - assertThat( toString( result ) ) - .isEqualTo( ":maven-surefire-event:" + (char) 10 + ":test-error:" + (char) 10 - + ":normal-run:\u0001\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0001:" ); - - result = ByteBuffer.allocate( 1024 ); - streamEncoder.encodeHeader( result, BOOTERCODE_CONSOLE_ERROR ); - streamEncoder.encodeCharset( result ); - assertThat( toString( result ) ) - .isEqualTo( ":maven-surefire-event:" + (char) 17 + ":console-error-log:" + (char) 5 + ":UTF-8:" ); + public void testSendOpcode() { + Encoder streamEncoder = new Encoder(new DummyChannel()); + ByteBuffer result = ByteBuffer.allocate(128); + streamEncoder.encodeHeader(result, BOOTERCODE_TEST_ERROR, NORMAL_RUN, 1L); + assertThat(toString(result)) + .isEqualTo(":maven-surefire-event:" + (char) 10 + ":test-error:" + (char) 10 + + ":normal-run:\u0001\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0001:"); + + result = ByteBuffer.allocate(1024); + streamEncoder.encodeHeader(result, BOOTERCODE_CONSOLE_ERROR); + streamEncoder.encodeCharset(result); + assertThat(toString(result)) + .isEqualTo(":maven-surefire-event:" + (char) 17 + ":console-error-log:" + (char) 5 + ":UTF-8:"); } @Test - public void testEncodedString() - { - Encoder streamEncoder = new Encoder( new DummyChannel() ); - ByteBuffer result = ByteBuffer.allocate( 128 ); - streamEncoder.encode( streamEncoder.newCharsetEncoder(), result, BOOTERCODE_STDOUT, NORMAL_RUN, 1L, "msg" ); - assertThat( toString( result ) ) - .isEqualTo( ":maven-surefire-event:\u000e:std-out-stream:" - + (char) 10 + ":normal-run:\u0001\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0001" - + ":\u0005:UTF-8:\u0000\u0000\u0000\u0003:msg:" ); + public void testEncodedString() { + Encoder streamEncoder = new Encoder(new DummyChannel()); + ByteBuffer result = ByteBuffer.allocate(128); + streamEncoder.encode(streamEncoder.newCharsetEncoder(), result, BOOTERCODE_STDOUT, NORMAL_RUN, 1L, "msg"); + assertThat(toString(result)) + .isEqualTo(":maven-surefire-event:\u000e:std-out-stream:" + + (char) 10 + ":normal-run:\u0001\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0001" + + ":\u0005:UTF-8:\u0000\u0000\u0000\u0003:msg:"); } @Test - public void testIntegerAsNull() - { - Encoder streamEncoder = new Encoder( new DummyChannel() ); - ByteBuffer result = ByteBuffer.allocate( 4 ); - streamEncoder.encodeInteger( result, null ); - assertThat( ( (Buffer) result ).position() ).isEqualTo( 2 ); - assertThat( result.get( 0 ) ).isEqualTo( (byte) 0 ); - assertThat( result.get( 1 ) ).isEqualTo( (byte) ':' ); + public void testIntegerAsNull() { + Encoder streamEncoder = new Encoder(new DummyChannel()); + ByteBuffer result = ByteBuffer.allocate(4); + streamEncoder.encodeInteger(result, null); + assertThat(((Buffer) result).position()).isEqualTo(2); + assertThat(result.get(0)).isEqualTo((byte) 0); + assertThat(result.get(1)).isEqualTo((byte) ':'); } @Test - public void testInteger() - { - Encoder streamEncoder = new Encoder( new DummyChannel() ); - ByteBuffer result = ByteBuffer.allocate( 8 ); - streamEncoder.encodeInteger( result, 5 ); - assertThat( ( (Buffer) result ).position() ).isEqualTo( 6 ); - ( (Buffer) result ).position( 0 ); - assertThat( result.get() ).isEqualTo( (byte) 0xff ); - assertThat( result.getInt() ).isEqualTo( (byte) 5 ); - assertThat( result.get( 5 ) ).isEqualTo( (byte) ':' ); + public void testInteger() { + Encoder streamEncoder = new Encoder(new DummyChannel()); + ByteBuffer result = ByteBuffer.allocate(8); + streamEncoder.encodeInteger(result, 5); + assertThat(((Buffer) result).position()).isEqualTo(6); + ((Buffer) result).position(0); + assertThat(result.get()).isEqualTo((byte) 0xff); + assertThat(result.getInt()).isEqualTo((byte) 5); + assertThat(result.get(5)).isEqualTo((byte) ':'); } @Test - public void testWrite() throws Exception - { + public void testWrite() throws Exception { DummyChannel channel = new DummyChannel(); - Encoder streamEncoder = new Encoder( channel ); - streamEncoder.write( ByteBuffer.allocate( 0 ), false ); - assertThat( channel.writeBuffered ).isTrue(); - assertThat( channel.write ).isFalse(); + Encoder streamEncoder = new Encoder(channel); + streamEncoder.write(ByteBuffer.allocate(0), false); + assertThat(channel.writeBuffered).isTrue(); + assertThat(channel.write).isFalse(); channel.writeBuffered = false; channel.write = false; - streamEncoder.write( ByteBuffer.allocate( 0 ), true ); - assertThat( channel.writeBuffered ).isFalse(); - assertThat( channel.write ).isTrue(); + streamEncoder.write(ByteBuffer.allocate(0), true); + assertThat(channel.writeBuffered).isFalse(); + assertThat(channel.write).isTrue(); } - private static String toString( ByteBuffer frame ) - { + private static String toString(ByteBuffer frame) { ByteArrayOutputStream os = new ByteArrayOutputStream(); - ( (Buffer) frame ).flip(); - os.write( frame.array(), frame.arrayOffset() + ( (Buffer) frame ).position(), frame.remaining() ); - return new String( os.toByteArray(), UTF_8 ); + ((Buffer) frame).flip(); + os.write(frame.array(), frame.arrayOffset() + ((Buffer) frame).position(), frame.remaining()); + return new String(os.toByteArray(), UTF_8); } - private static class Encoder extends AbstractStreamEncoder - { + private static class Encoder extends AbstractStreamEncoder { - Encoder( WritableBufferedByteChannel out ) - { - super( out ); + Encoder(WritableBufferedByteChannel out) { + super(out); } @Nonnull @Override - public byte[] getEncodedMagicNumber() - { + public byte[] getEncodedMagicNumber() { return MAGIC_NUMBER_FOR_EVENTS_BYTES; } @Nonnull @Override - protected byte[] enumToByteArray( ForkedProcessEventType forkedProcessEventType ) - { + protected byte[] enumToByteArray(ForkedProcessEventType forkedProcessEventType) { return forkedProcessEventType.getOpcodeBinary(); } @Nonnull @Override - protected byte[] getEncodedCharsetName() - { - return getCharset().name().getBytes( US_ASCII ); + protected byte[] getEncodedCharsetName() { + return getCharset().name().getBytes(US_ASCII); } @Nonnull @Override - public Charset getCharset() - { + public Charset getCharset() { return UTF_8; } @Nonnull @Override - public CharsetEncoder newCharsetEncoder() - { + public CharsetEncoder newCharsetEncoder() { return getCharset().newEncoder(); } } - private static class DummyChannel implements WritableBufferedByteChannel - { + private static class DummyChannel implements WritableBufferedByteChannel { boolean writeBuffered; boolean write; @Override - public void writeBuffered( ByteBuffer src ) - { + public void writeBuffered(ByteBuffer src) { writeBuffered = true; } @Override - public long countBufferOverflows() - { + public long countBufferOverflows() { return 0; } @Override - public int write( ByteBuffer src ) - { + public int write(ByteBuffer src) { write = true; return 0; } @Override - public boolean isOpen() - { + public boolean isOpen() { return false; } @Override - public void close() - { - } + public void close() {} } - } diff --git a/surefire-api/src/test/java/org/apache/maven/surefire/api/suite/RunResultTest.java b/surefire-api/src/test/java/org/apache/maven/surefire/api/suite/RunResultTest.java index 6a9899980e..04a529deae 100644 --- a/surefire-api/src/test/java/org/apache/maven/surefire/api/suite/RunResultTest.java +++ b/surefire-api/src/test/java/org/apache/maven/surefire/api/suite/RunResultTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.api.suite; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,27 +16,24 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.api.suite; import junit.framework.TestCase; /** * @author Kristian Rosenvold */ -public class RunResultTest - extends TestCase -{ +public class RunResultTest extends TestCase { - public void testEmptySummaryShouldBeErrorFree() - { + public void testEmptySummaryShouldBeErrorFree() { RunResult summary = RunResult.noTestsRun(); - assertTrue( summary.isErrorFree() ); + assertTrue(summary.isErrorFree()); } - @SuppressWarnings( "checkstyle:magicnumber" ) - public void testFailuresInFirstRun() - { - RunResult resultOne = new RunResult( 10, 1, 3, 2 ); - RunResult resultTwo = new RunResult( 20, 0, 0, 0 ); - assertFalse( resultOne.aggregate( resultTwo ).isErrorFree() ); + @SuppressWarnings("checkstyle:magicnumber") + public void testFailuresInFirstRun() { + RunResult resultOne = new RunResult(10, 1, 3, 2); + RunResult resultTwo = new RunResult(20, 0, 0, 0); + assertFalse(resultOne.aggregate(resultTwo).isErrorFree()); } } diff --git a/surefire-api/src/test/java/org/apache/maven/surefire/api/testdata/DataZT1A.java b/surefire-api/src/test/java/org/apache/maven/surefire/api/testdata/DataZT1A.java index 11f9a0ba04..c5bc20b07e 100644 --- a/surefire-api/src/test/java/org/apache/maven/surefire/api/testdata/DataZT1A.java +++ b/surefire-api/src/test/java/org/apache/maven/surefire/api/testdata/DataZT1A.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.api.testdata; /* @@ -22,6 +40,4 @@ /** * */ -public class DataZT1A -{ -} +public class DataZT1A {} diff --git a/surefire-api/src/test/java/org/apache/maven/surefire/api/testdata/DataZT2A.java b/surefire-api/src/test/java/org/apache/maven/surefire/api/testdata/DataZT2A.java index c4d73a8e92..f4073fd4f4 100644 --- a/surefire-api/src/test/java/org/apache/maven/surefire/api/testdata/DataZT2A.java +++ b/surefire-api/src/test/java/org/apache/maven/surefire/api/testdata/DataZT2A.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.api.testdata; /* @@ -22,6 +40,4 @@ /** * */ -public class DataZT2A -{ -} +public class DataZT2A {} diff --git a/surefire-api/src/test/java/org/apache/maven/surefire/api/testdata/DataZT3A.java b/surefire-api/src/test/java/org/apache/maven/surefire/api/testdata/DataZT3A.java index 1a6b695ae0..0795ef75c6 100644 --- a/surefire-api/src/test/java/org/apache/maven/surefire/api/testdata/DataZT3A.java +++ b/surefire-api/src/test/java/org/apache/maven/surefire/api/testdata/DataZT3A.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.api.testdata; /* @@ -22,6 +40,4 @@ /** * */ -public class DataZT3A -{ -} +public class DataZT3A {} diff --git a/surefire-api/src/test/java/org/apache/maven/surefire/api/testdata/java/javascript/DataJavaZT4A.java b/surefire-api/src/test/java/org/apache/maven/surefire/api/testdata/java/javascript/DataJavaZT4A.java index 1d828e910d..90cf1ba3f3 100644 --- a/surefire-api/src/test/java/org/apache/maven/surefire/api/testdata/java/javascript/DataJavaZT4A.java +++ b/surefire-api/src/test/java/org/apache/maven/surefire/api/testdata/java/javascript/DataJavaZT4A.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.api.testdata.java.javascript; /* @@ -25,6 +43,4 @@ * Date: August 16, 2010 * Time: 11:13:18 PM */ -public class DataJavaZT4A -{ -} +public class DataJavaZT4A {} diff --git a/surefire-api/src/test/java/org/apache/maven/surefire/api/testset/FundamentalFilterTest.java b/surefire-api/src/test/java/org/apache/maven/surefire/api/testset/FundamentalFilterTest.java index 22796073b2..2a2875b103 100644 --- a/surefire-api/src/test/java/org/apache/maven/surefire/api/testset/FundamentalFilterTest.java +++ b/surefire-api/src/test/java/org/apache/maven/surefire/api/testset/FundamentalFilterTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.api.testset; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,13 +16,14 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.api.testset; import org.junit.Test; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; -@SuppressWarnings( { "javadoc", "checkstyle:javadoctype" } ) +@SuppressWarnings({"javadoc", "checkstyle:javadoctype"}) /** * Inclusive test patters:

    * @@ -325,259 +324,226 @@ * * */ -public class FundamentalFilterTest -{ +public class FundamentalFilterTest { @Test - public void testIncludes1() - { - ResolvedTest pattern = new ResolvedTest( (String) null, null, false ); - assertThat( pattern.matchAsInclusive( null, null ), is( true ) ); + public void testIncludes1() { + ResolvedTest pattern = new ResolvedTest((String) null, null, false); + assertThat(pattern.matchAsInclusive(null, null), is(true)); } @Test - public void testIncludes2() - { - ResolvedTest pattern = new ResolvedTest( (String) null, "method", false ); - assertThat( pattern.matchAsInclusive( null, null ), is( true ) ); + public void testIncludes2() { + ResolvedTest pattern = new ResolvedTest((String) null, "method", false); + assertThat(pattern.matchAsInclusive(null, null), is(true)); } @Test - public void testIncludes3() - { - ResolvedTest pattern = new ResolvedTest( "Test", null, false ); - assertThat( pattern.matchAsInclusive( null, null ), is( true ) ); + public void testIncludes3() { + ResolvedTest pattern = new ResolvedTest("Test", null, false); + assertThat(pattern.matchAsInclusive(null, null), is(true)); } @Test - public void testIncludes4() - { - ResolvedTest pattern = new ResolvedTest( "Test", "method", false ); - assertThat( pattern.matchAsInclusive( null, null ), is( true ) ); + public void testIncludes4() { + ResolvedTest pattern = new ResolvedTest("Test", "method", false); + assertThat(pattern.matchAsInclusive(null, null), is(true)); } @Test - public void testIncludes5() - { - ResolvedTest pattern = new ResolvedTest( (String) null, null, false ); - assertThat( pattern.matchAsInclusive( null, "method" ), is( true ) ); + public void testIncludes5() { + ResolvedTest pattern = new ResolvedTest((String) null, null, false); + assertThat(pattern.matchAsInclusive(null, "method"), is(true)); } @Test - public void testIncludes6() - { - ResolvedTest pattern = new ResolvedTest( (String) null, "method", false ); - assertThat( pattern.matchAsInclusive( null, "method" ), is( true ) ); - assertThat( pattern.matchAsInclusive( null, "otherMethod" ), is( false ) ); + public void testIncludes6() { + ResolvedTest pattern = new ResolvedTest((String) null, "method", false); + assertThat(pattern.matchAsInclusive(null, "method"), is(true)); + assertThat(pattern.matchAsInclusive(null, "otherMethod"), is(false)); } /** * Does not throw NPE due to Cucumber has test class NULL and test method NOT NULL. */ @Test - public void testIncludes7() - { - ResolvedTest pattern = new ResolvedTest( "Test", null, false ); - assertThat( pattern.matchAsInclusive( null, "method" ), is( true ) ); + public void testIncludes7() { + ResolvedTest pattern = new ResolvedTest("Test", null, false); + assertThat(pattern.matchAsInclusive(null, "method"), is(true)); } /** * Does not throw NPE due to Cucumber has test class NULL and test method NOT NULL. */ @Test - public void testIncludes8() - { - ResolvedTest pattern = new ResolvedTest( "Test", "method", false ); - assertThat( pattern.matchAsInclusive( null, "method" ), is( true ) ); - assertThat( pattern.matchAsInclusive( null, "otherMethod" ), is( true ) ); + public void testIncludes8() { + ResolvedTest pattern = new ResolvedTest("Test", "method", false); + assertThat(pattern.matchAsInclusive(null, "method"), is(true)); + assertThat(pattern.matchAsInclusive(null, "otherMethod"), is(true)); } @Test - public void testIncludes9() - { - ResolvedTest pattern = new ResolvedTest( (String) null, null, false ); - assertThat( pattern.matchAsInclusive( "Test.class", null ), is( true ) ); + public void testIncludes9() { + ResolvedTest pattern = new ResolvedTest((String) null, null, false); + assertThat(pattern.matchAsInclusive("Test.class", null), is(true)); } @Test - public void testIncludes10() - { - ResolvedTest pattern = new ResolvedTest( (String) null, "method", false ); - assertThat( pattern.matchAsInclusive( "Test.class", null ), is( true ) ); + public void testIncludes10() { + ResolvedTest pattern = new ResolvedTest((String) null, "method", false); + assertThat(pattern.matchAsInclusive("Test.class", null), is(true)); } @Test - public void testIncludes11() - { - ResolvedTest pattern = new ResolvedTest( "Test", null, false ); - assertThat( pattern.matchAsInclusive( "Test.class", null ), is( true ) ); - assertThat( pattern.matchAsInclusive( "Other.class", null ), is( false ) ); + public void testIncludes11() { + ResolvedTest pattern = new ResolvedTest("Test", null, false); + assertThat(pattern.matchAsInclusive("Test.class", null), is(true)); + assertThat(pattern.matchAsInclusive("Other.class", null), is(false)); } @Test - public void testIncludes12() - { - ResolvedTest pattern = new ResolvedTest( "Test", "method", false ); - assertThat( pattern.matchAsInclusive( "Test.class", null ), is( true ) ); - assertThat( pattern.matchAsInclusive( "Other.class", null ), is( false ) ); + public void testIncludes12() { + ResolvedTest pattern = new ResolvedTest("Test", "method", false); + assertThat(pattern.matchAsInclusive("Test.class", null), is(true)); + assertThat(pattern.matchAsInclusive("Other.class", null), is(false)); } @Test - public void testIncludes13() - { - ResolvedTest pattern = new ResolvedTest( (String) null, null, false ); - assertThat( pattern.matchAsInclusive( "Test.class", "method" ), is( true ) ); + public void testIncludes13() { + ResolvedTest pattern = new ResolvedTest((String) null, null, false); + assertThat(pattern.matchAsInclusive("Test.class", "method"), is(true)); } @Test - public void testIncludes14() - { - ResolvedTest pattern = new ResolvedTest( (String) null, "method", false ); - assertThat( pattern.matchAsInclusive( "Test.class", "method" ), is( true ) ); - assertThat( pattern.matchAsInclusive( "Test.class", "otherMethod" ), is( false ) ); + public void testIncludes14() { + ResolvedTest pattern = new ResolvedTest((String) null, "method", false); + assertThat(pattern.matchAsInclusive("Test.class", "method"), is(true)); + assertThat(pattern.matchAsInclusive("Test.class", "otherMethod"), is(false)); } @Test - public void testIncludes15() - { - ResolvedTest pattern = new ResolvedTest( "Test", null, false ); - assertThat( pattern.matchAsInclusive( "Test.class", "method" ), is( true ) ); - assertThat( pattern.matchAsInclusive( "Other.class", "method" ), is( false ) ); + public void testIncludes15() { + ResolvedTest pattern = new ResolvedTest("Test", null, false); + assertThat(pattern.matchAsInclusive("Test.class", "method"), is(true)); + assertThat(pattern.matchAsInclusive("Other.class", "method"), is(false)); } @Test - public void testIncludes16() - { - ResolvedTest pattern = new ResolvedTest( "Test", "method", false ); - assertThat( pattern.matchAsInclusive( "Test.class", "method" ), is( true ) ); - assertThat( pattern.matchAsInclusive( "Test.class", "otherMethod" ), is( false ) ); - assertThat( pattern.matchAsInclusive( "Other.class", "method" ), is( false ) ); - assertThat( pattern.matchAsInclusive( "Other.class", "otherMethod" ), is( false ) ); + public void testIncludes16() { + ResolvedTest pattern = new ResolvedTest("Test", "method", false); + assertThat(pattern.matchAsInclusive("Test.class", "method"), is(true)); + assertThat(pattern.matchAsInclusive("Test.class", "otherMethod"), is(false)); + assertThat(pattern.matchAsInclusive("Other.class", "method"), is(false)); + assertThat(pattern.matchAsInclusive("Other.class", "otherMethod"), is(false)); } @Test - public void testExcludes1() - { - ResolvedTest pattern = new ResolvedTest( (String) null, null, false ); - assertThat( pattern.matchAsExclusive( null, null ), is( false ) ); + public void testExcludes1() { + ResolvedTest pattern = new ResolvedTest((String) null, null, false); + assertThat(pattern.matchAsExclusive(null, null), is(false)); } @Test - public void testExcludes2() - { - ResolvedTest pattern = new ResolvedTest( (String) null, "method", false ); - assertThat( pattern.matchAsExclusive( null, null ), is( false ) ); + public void testExcludes2() { + ResolvedTest pattern = new ResolvedTest((String) null, "method", false); + assertThat(pattern.matchAsExclusive(null, null), is(false)); } @Test - public void testExcludes3() - { - ResolvedTest pattern = new ResolvedTest( "Test", null, false ); - assertThat( pattern.matchAsExclusive( null, null ), is( false ) ); + public void testExcludes3() { + ResolvedTest pattern = new ResolvedTest("Test", null, false); + assertThat(pattern.matchAsExclusive(null, null), is(false)); } @Test - public void testExcludes4() - { - ResolvedTest pattern = new ResolvedTest( "Test", "method", false ); - assertThat( pattern.matchAsExclusive( null, null ), is( false ) ); + public void testExcludes4() { + ResolvedTest pattern = new ResolvedTest("Test", "method", false); + assertThat(pattern.matchAsExclusive(null, null), is(false)); } @Test - public void testExcludes5() - { - ResolvedTest pattern = new ResolvedTest( (String) null, null, false ); - assertThat( pattern.matchAsExclusive( null, "method" ), is( false ) ); + public void testExcludes5() { + ResolvedTest pattern = new ResolvedTest((String) null, null, false); + assertThat(pattern.matchAsExclusive(null, "method"), is(false)); } @Test - public void testExcludes6() - { - ResolvedTest pattern = new ResolvedTest( (String) null, "method", false ); - assertThat( pattern.matchAsExclusive( null, "method" ), is( true ) ); - assertThat( pattern.matchAsExclusive( null, "otherMethod" ), is( false ) ); + public void testExcludes6() { + ResolvedTest pattern = new ResolvedTest((String) null, "method", false); + assertThat(pattern.matchAsExclusive(null, "method"), is(true)); + assertThat(pattern.matchAsExclusive(null, "otherMethod"), is(false)); } /** * Does not throw NPE due to Cucumber has test class NULL and test method NOT NULL. */ @Test - public void testExcludes7() - { - ResolvedTest pattern = new ResolvedTest( "Test", null, false ); - assertThat( pattern.matchAsExclusive( null, "method" ), is( false ) ); + public void testExcludes7() { + ResolvedTest pattern = new ResolvedTest("Test", null, false); + assertThat(pattern.matchAsExclusive(null, "method"), is(false)); } /** * Does not throw NPE due to Cucumber has test class NULL and test method NOT NULL. */ @Test - public void testExcludes8() - { - ResolvedTest pattern = new ResolvedTest( "Test", "method", false ); - assertThat( pattern.matchAsExclusive( null, "method" ), is( false ) ); - assertThat( pattern.matchAsExclusive( null, "otherMethod" ), is( false ) ); + public void testExcludes8() { + ResolvedTest pattern = new ResolvedTest("Test", "method", false); + assertThat(pattern.matchAsExclusive(null, "method"), is(false)); + assertThat(pattern.matchAsExclusive(null, "otherMethod"), is(false)); } @Test - public void testExcludes9() - { - ResolvedTest pattern = new ResolvedTest( (String) null, null, false ); - assertThat( pattern.matchAsExclusive( "Test.class", null ), is( false ) ); + public void testExcludes9() { + ResolvedTest pattern = new ResolvedTest((String) null, null, false); + assertThat(pattern.matchAsExclusive("Test.class", null), is(false)); } @Test - public void testExcludes10() - { - ResolvedTest pattern = new ResolvedTest( (String) null, "method", false ); - assertThat( pattern.matchAsExclusive( "Test.class", null ), is( false ) ); + public void testExcludes10() { + ResolvedTest pattern = new ResolvedTest((String) null, "method", false); + assertThat(pattern.matchAsExclusive("Test.class", null), is(false)); } @Test - public void testExcludes11() - { - ResolvedTest pattern = new ResolvedTest( "Test", null, false ); - assertThat( pattern.matchAsExclusive( "Test.class", null ), is( true ) ); - assertThat( pattern.matchAsExclusive( "Other.class", null ), is( false ) ); + public void testExcludes11() { + ResolvedTest pattern = new ResolvedTest("Test", null, false); + assertThat(pattern.matchAsExclusive("Test.class", null), is(true)); + assertThat(pattern.matchAsExclusive("Other.class", null), is(false)); } @Test - public void testExcludes12() - { - ResolvedTest pattern = new ResolvedTest( "Test", "method", false ); - assertThat( pattern.matchAsExclusive( "Test.class", null ), is( false ) ); - assertThat( pattern.matchAsExclusive( "Other.class", null ), is( false ) ); + public void testExcludes12() { + ResolvedTest pattern = new ResolvedTest("Test", "method", false); + assertThat(pattern.matchAsExclusive("Test.class", null), is(false)); + assertThat(pattern.matchAsExclusive("Other.class", null), is(false)); } @Test - public void testExcludes13() - { - ResolvedTest pattern = new ResolvedTest( (String) null, null, false ); - assertThat( pattern.matchAsExclusive( "Test.class", "method" ), is( false ) ); + public void testExcludes13() { + ResolvedTest pattern = new ResolvedTest((String) null, null, false); + assertThat(pattern.matchAsExclusive("Test.class", "method"), is(false)); } @Test - public void testExcludes14() - { - ResolvedTest pattern = new ResolvedTest( (String) null, "method", false ); - assertThat( pattern.matchAsExclusive( "Test.class", "method" ), is( true ) ); - assertThat( pattern.matchAsExclusive( "Test.class", "otherMethod" ), is( false ) ); + public void testExcludes14() { + ResolvedTest pattern = new ResolvedTest((String) null, "method", false); + assertThat(pattern.matchAsExclusive("Test.class", "method"), is(true)); + assertThat(pattern.matchAsExclusive("Test.class", "otherMethod"), is(false)); } @Test - public void testExcludes15() - { - ResolvedTest pattern = new ResolvedTest( "Test", null, false ); - assertThat( pattern.matchAsExclusive( "Test.class", "method" ), is( true ) ); - assertThat( pattern.matchAsExclusive( "Other.class", "method" ), is( false ) ); + public void testExcludes15() { + ResolvedTest pattern = new ResolvedTest("Test", null, false); + assertThat(pattern.matchAsExclusive("Test.class", "method"), is(true)); + assertThat(pattern.matchAsExclusive("Other.class", "method"), is(false)); } @Test - public void testExcludes16() - { - ResolvedTest pattern = new ResolvedTest( "Test", "method", false ); - assertThat( pattern.matchAsExclusive( "Test.class", "method" ), is( true ) ); - assertThat( pattern.matchAsExclusive( "Test.class", "otherMethod" ), is( false ) ); - assertThat( pattern.matchAsExclusive( "Other.class", "method" ), is( false ) ); - assertThat( pattern.matchAsExclusive( "Other.class", "otherMethod" ), is( false ) ); + public void testExcludes16() { + ResolvedTest pattern = new ResolvedTest("Test", "method", false); + assertThat(pattern.matchAsExclusive("Test.class", "method"), is(true)); + assertThat(pattern.matchAsExclusive("Test.class", "otherMethod"), is(false)); + assertThat(pattern.matchAsExclusive("Other.class", "method"), is(false)); + assertThat(pattern.matchAsExclusive("Other.class", "otherMethod"), is(false)); } } diff --git a/surefire-api/src/test/java/org/apache/maven/surefire/api/testset/ResolvedTestTest.java b/surefire-api/src/test/java/org/apache/maven/surefire/api/testset/ResolvedTestTest.java index d953688f8d..0d9d2b78cd 100644 --- a/surefire-api/src/test/java/org/apache/maven/surefire/api/testset/ResolvedTestTest.java +++ b/surefire-api/src/test/java/org/apache/maven/surefire/api/testset/ResolvedTestTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.api.testset; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.api.testset; import junit.framework.TestCase; @@ -28,48 +27,43 @@ /** * */ -public class ResolvedTestTest - extends TestCase -{ - public void testEmptyClassRegex() - { - ResolvedTest test = new ResolvedTest( CLASS, " ", true ); - assertNull( test.getTestClassPattern() ); - assertNull( test.getTestMethodPattern() ); - assertFalse( test.hasTestClassPattern() ); - assertFalse( test.hasTestMethodPattern() ); - assertTrue( test.isRegexTestClassPattern() ); - assertFalse( test.isRegexTestMethodPattern() ); - assertTrue( test.isEmpty() ); +public class ResolvedTestTest extends TestCase { + public void testEmptyClassRegex() { + ResolvedTest test = new ResolvedTest(CLASS, " ", true); + assertNull(test.getTestClassPattern()); + assertNull(test.getTestMethodPattern()); + assertFalse(test.hasTestClassPattern()); + assertFalse(test.hasTestMethodPattern()); + assertTrue(test.isRegexTestClassPattern()); + assertFalse(test.isRegexTestMethodPattern()); + assertTrue(test.isEmpty()); } - public void testEmptyMethodRegex() - { - ResolvedTest test = new ResolvedTest( METHOD, " ", true ); - assertNull( test.getTestClassPattern() ); - assertNull( test.getTestMethodPattern() ); - assertFalse( test.hasTestClassPattern() ); - assertFalse( test.hasTestMethodPattern() ); - assertFalse( test.isRegexTestClassPattern() ); - assertTrue( test.isRegexTestMethodPattern() ); - assertTrue( test.isEmpty() ); + public void testEmptyMethodRegex() { + ResolvedTest test = new ResolvedTest(METHOD, " ", true); + assertNull(test.getTestClassPattern()); + assertNull(test.getTestMethodPattern()); + assertFalse(test.hasTestClassPattern()); + assertFalse(test.hasTestMethodPattern()); + assertFalse(test.isRegexTestClassPattern()); + assertTrue(test.isRegexTestMethodPattern()); + assertTrue(test.isEmpty()); } - public void testFromFullyQualifiedClass() - { - String classFileName = fromFullyQualifiedClass( "my.package.MyTest" ); - assertEquals( "my/package/MyTest", classFileName ); + public void testFromFullyQualifiedClass() { + String classFileName = fromFullyQualifiedClass("my.package.MyTest"); + assertEquals("my/package/MyTest", classFileName); - classFileName = fromFullyQualifiedClass( "my.package.MyTest.class" ); - assertEquals( "my/package/MyTest.class", classFileName ); + classFileName = fromFullyQualifiedClass("my.package.MyTest.class"); + assertEquals("my/package/MyTest.class", classFileName); - classFileName = fromFullyQualifiedClass( "my/package/MyTest.class" ); - assertEquals( "my/package/MyTest.class", classFileName ); + classFileName = fromFullyQualifiedClass("my/package/MyTest.class"); + assertEquals("my/package/MyTest.class", classFileName); - classFileName = fromFullyQualifiedClass( "my/package/MyTest.*" ); - assertEquals( "my/package/MyTest.*", classFileName ); + classFileName = fromFullyQualifiedClass("my/package/MyTest.*"); + assertEquals("my/package/MyTest.*", classFileName); - classFileName = fromFullyQualifiedClass( "my.package.MyTest.*" ); - assertEquals( "my/package/MyTest.*", classFileName ); + classFileName = fromFullyQualifiedClass("my.package.MyTest.*"); + assertEquals("my/package/MyTest.*", classFileName); } } diff --git a/surefire-api/src/test/java/org/apache/maven/surefire/api/testset/TestListResolverTest.java b/surefire-api/src/test/java/org/apache/maven/surefire/api/testset/TestListResolverTest.java index 8ca9753a45..43b053deb0 100644 --- a/surefire-api/src/test/java/org/apache/maven/surefire/api/testset/TestListResolverTest.java +++ b/surefire-api/src/test/java/org/apache/maven/surefire/api/testset/TestListResolverTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.api.testset; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,8 +16,7 @@ * specific language governing permissions and limitations * under the License. */ - -import junit.framework.TestCase; +package org.apache.maven.surefire.api.testset; import java.util.ArrayList; import java.util.Collection; @@ -29,476 +26,409 @@ import java.util.LinkedHashSet; import java.util.Set; -import static java.util.Collections.addAll; -import static org.apache.maven.surefire.api.testset.TestListResolver.newTestListResolver; -import static org.apache.maven.surefire.api.testset.ResolvedTest.Type.CLASS; +import junit.framework.TestCase; + import static java.util.Arrays.asList; +import static java.util.Collections.addAll; import static java.util.Collections.emptySet; import static java.util.Collections.singleton; +import static org.apache.maven.surefire.api.testset.ResolvedTest.Type.CLASS; +import static org.apache.maven.surefire.api.testset.TestListResolver.newTestListResolver; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; /** * */ -public class TestListResolverTest - extends TestCase -{ +public class TestListResolverTest extends TestCase { private static final String DEFAULT_SUREFIRE_INCLUDED_TEST_PATTERNS = - "**/Test*.java, **/*Test.java, **/*TestCase.java"; + "**/Test*.java, **/*Test.java, **/*TestCase.java"; private static final String DEFAULT_SUREFIRE_EXCLUDED_TEST_PATTERNS = "**/*$*"; - public void testRegexSanity1() - { - try - { - TestListResolver.isRegexPrefixedPattern( "#%regex[]" ); - fail( "#%regex[]" ); - } - catch ( IllegalArgumentException e ) - { + public void testRegexSanity1() { + try { + TestListResolver.isRegexPrefixedPattern("#%regex[]"); + fail("#%regex[]"); + } catch (IllegalArgumentException e) { // expected in junit 3.x } } - public void testRegexSanity2() - { - try - { - TestListResolver.isRegexPrefixedPattern( "%regex[]#" ); - fail( "%regex[]#" ); - } - catch ( IllegalArgumentException e ) - { + public void testRegexSanity2() { + try { + TestListResolver.isRegexPrefixedPattern("%regex[]#"); + fail("%regex[]#"); + } catch (IllegalArgumentException e) { // expected in junit 3.x } } - public void testRegexSanity3() - { - try - { - TestListResolver.isRegexPrefixedPattern( "%regex[]%regex[]" ); - fail( "%regex[]%regex[]" ); - } - catch ( IllegalArgumentException e ) - { + public void testRegexSanity3() { + try { + TestListResolver.isRegexPrefixedPattern("%regex[]%regex[]"); + fail("%regex[]%regex[]"); + } catch (IllegalArgumentException e) { // expected in junit 3.x } } - public void testMinRegexLength() - { - assertFalse( TestListResolver.isRegexMinLength( "%regex[]" ) ); - assertFalse( TestListResolver.isRegexMinLength( "%regex[ ]" ) ); - assertTrue( TestListResolver.isRegexMinLength( "%regex[*Test]" ) ); + public void testMinRegexLength() { + assertFalse(TestListResolver.isRegexMinLength("%regex[]")); + assertFalse(TestListResolver.isRegexMinLength("%regex[ ]")); + assertTrue(TestListResolver.isRegexMinLength("%regex[*Test]")); } - public void testRemoveExclamationMark() - { - String pattern = TestListResolver.removeExclamationMark( "!%regex[]" ); - assertEquals( "%regex[]", pattern ); - pattern = TestListResolver.removeExclamationMark( "%regex[]" ); - assertEquals( "%regex[]", pattern ); + public void testRemoveExclamationMark() { + String pattern = TestListResolver.removeExclamationMark("!%regex[]"); + assertEquals("%regex[]", pattern); + pattern = TestListResolver.removeExclamationMark("%regex[]"); + assertEquals("%regex[]", pattern); } - public void testUnwrapped() - { - String[] classAndMethod = TestListResolver.unwrap( " MyTest " ); - assertEquals( "MyTest", classAndMethod[0] ); - assertEquals( "", classAndMethod[1] ); - classAndMethod = TestListResolver.unwrap( " # test " ); - assertEquals( "", classAndMethod[0] ); - assertEquals( "test", classAndMethod[1] ); - classAndMethod = TestListResolver.unwrap( " MyTest # test " ); - assertEquals( "MyTest", classAndMethod[0] ); - assertEquals( "test", classAndMethod[1] ); + public void testUnwrapped() { + String[] classAndMethod = TestListResolver.unwrap(" MyTest "); + assertEquals("MyTest", classAndMethod[0]); + assertEquals("", classAndMethod[1]); + classAndMethod = TestListResolver.unwrap(" # test "); + assertEquals("", classAndMethod[0]); + assertEquals("test", classAndMethod[1]); + classAndMethod = TestListResolver.unwrap(" MyTest # test "); + assertEquals("MyTest", classAndMethod[0]); + assertEquals("test", classAndMethod[1]); } - public void testUnwrappedRegex() - { - String[] classAndMethod = TestListResolver.unwrapRegex( "%regex[ .*.MyTest.class ]" ); - assertEquals( ".*.MyTest.class", classAndMethod[0] ); - assertEquals( "", classAndMethod[1] ); - classAndMethod = TestListResolver.unwrapRegex( "%regex[ # myMethod|secondTest ]" ); - assertEquals( "", classAndMethod[0] ); - assertEquals( "myMethod|secondTest", classAndMethod[1] ); - classAndMethod = TestListResolver.unwrapRegex( "%regex[ .*.MyTest.class # myMethod|secondTest ]" ); - assertEquals( ".*.MyTest.class", classAndMethod[0] ); - assertEquals( "myMethod|secondTest", classAndMethod[1] ); + public void testUnwrappedRegex() { + String[] classAndMethod = TestListResolver.unwrapRegex("%regex[ .*.MyTest.class ]"); + assertEquals(".*.MyTest.class", classAndMethod[0]); + assertEquals("", classAndMethod[1]); + classAndMethod = TestListResolver.unwrapRegex("%regex[ # myMethod|secondTest ]"); + assertEquals("", classAndMethod[0]); + assertEquals("myMethod|secondTest", classAndMethod[1]); + classAndMethod = TestListResolver.unwrapRegex("%regex[ .*.MyTest.class # myMethod|secondTest ]"); + assertEquals(".*.MyTest.class", classAndMethod[0]); + assertEquals("myMethod|secondTest", classAndMethod[1]); } - public void testMakeRegex() - { - String regex = ResolvedTest.wrapRegex( ".*.MyTest.class" ); - assertEquals( "%regex[.*.MyTest.class]", regex ); + public void testMakeRegex() { + String regex = ResolvedTest.wrapRegex(".*.MyTest.class"); + assertEquals("%regex[.*.MyTest.class]", regex); } - public void testNonRegexClassAndMethod() - { + public void testNonRegexClassAndMethod() { Collection includedFilters = new ArrayList<>(); Collection excludedFilters = new ArrayList<>(); IncludedExcludedPatterns includedExcludedPatterns = new IncludedExcludedPatterns(); - TestListResolver.nonRegexClassAndMethods( "MyTest", "myTest", false, includedExcludedPatterns, includedFilters, - excludedFilters ); - assertTrue( includedExcludedPatterns.hasIncludedMethodPatterns ); - assertFalse( includedExcludedPatterns.hasExcludedMethodPatterns ); - assertFalse( includedFilters.isEmpty() ); - assertTrue( excludedFilters.isEmpty() ); - assertEquals( 1, includedFilters.size() ); + TestListResolver.nonRegexClassAndMethods( + "MyTest", "myTest", false, includedExcludedPatterns, includedFilters, excludedFilters); + assertTrue(includedExcludedPatterns.hasIncludedMethodPatterns); + assertFalse(includedExcludedPatterns.hasExcludedMethodPatterns); + assertFalse(includedFilters.isEmpty()); + assertTrue(excludedFilters.isEmpty()); + assertEquals(1, includedFilters.size()); ResolvedTest test = includedFilters.iterator().next(); - assertFalse( test.isEmpty() ); - assertFalse( test.isRegexTestClassPattern() ); - assertFalse( test.isRegexTestMethodPattern() ); - assertTrue( test.hasTestClassPattern() ); - assertTrue( test.hasTestMethodPattern() ); - assertEquals( "**/MyTest", test.getTestClassPattern() ); - assertEquals( "myTest", test.getTestMethodPattern() ); - assertTrue( test.matchAsInclusive( "MyTest", "myTest" ) ); - assertFalse( test.matchAsInclusive( "MyTest", "otherTest" ) ); - } - - public void testNonRegexClassAndMethods() - { + assertFalse(test.isEmpty()); + assertFalse(test.isRegexTestClassPattern()); + assertFalse(test.isRegexTestMethodPattern()); + assertTrue(test.hasTestClassPattern()); + assertTrue(test.hasTestMethodPattern()); + assertEquals("**/MyTest", test.getTestClassPattern()); + assertEquals("myTest", test.getTestMethodPattern()); + assertTrue(test.matchAsInclusive("MyTest", "myTest")); + assertFalse(test.matchAsInclusive("MyTest", "otherTest")); + } + + public void testNonRegexClassAndMethods() { Collection includedFilters = new ArrayList<>(); Collection excludedFilters = new ArrayList<>(); IncludedExcludedPatterns includedExcludedPatterns = new IncludedExcludedPatterns(); - TestListResolver.nonRegexClassAndMethods( "MyTest.class", "first*+second*", false, includedExcludedPatterns, - includedFilters, excludedFilters ); - assertTrue( includedExcludedPatterns.hasIncludedMethodPatterns ); - assertFalse( includedExcludedPatterns.hasExcludedMethodPatterns ); - assertFalse( includedFilters.isEmpty() ); - assertTrue( excludedFilters.isEmpty() ); - assertEquals( 2, includedFilters.size() ); + TestListResolver.nonRegexClassAndMethods( + "MyTest.class", "first*+second*", false, includedExcludedPatterns, includedFilters, excludedFilters); + assertTrue(includedExcludedPatterns.hasIncludedMethodPatterns); + assertFalse(includedExcludedPatterns.hasExcludedMethodPatterns); + assertFalse(includedFilters.isEmpty()); + assertTrue(excludedFilters.isEmpty()); + assertEquals(2, includedFilters.size()); Iterator tests = includedFilters.iterator(); ResolvedTest first = tests.next(); - assertFalse( first.isEmpty() ); - assertFalse( first.isRegexTestClassPattern() ); - assertFalse( first.isRegexTestMethodPattern() ); - assertTrue( first.hasTestClassPattern() ); - assertTrue( first.hasTestMethodPattern() ); - assertEquals( "**/MyTest.class", first.getTestClassPattern() ); - assertEquals( "first*", first.getTestMethodPattern() ); - assertTrue( first.matchAsInclusive( "your/pkg/MyTest.class", "firstTest" ) ); + assertFalse(first.isEmpty()); + assertFalse(first.isRegexTestClassPattern()); + assertFalse(first.isRegexTestMethodPattern()); + assertTrue(first.hasTestClassPattern()); + assertTrue(first.hasTestMethodPattern()); + assertEquals("**/MyTest.class", first.getTestClassPattern()); + assertEquals("first*", first.getTestMethodPattern()); + assertTrue(first.matchAsInclusive("your/pkg/MyTest.class", "firstTest")); ResolvedTest second = tests.next(); - assertFalse( second.isEmpty() ); - assertFalse( second.isRegexTestClassPattern() ); - assertFalse( second.isRegexTestMethodPattern() ); - assertTrue( second.hasTestClassPattern() ); - assertTrue( second.hasTestMethodPattern() ); - assertEquals( "**/MyTest.class", second.getTestClassPattern() ); - assertEquals( "second*", second.getTestMethodPattern() ); - assertTrue( second.matchAsInclusive( "your/pkg/MyTest.class", "secondTest" ) ); - assertFalse( second.matchAsInclusive( "your/pkg/MyTest.class", "thirdTest" ) ); - } - - public void testNegativeNonRegexClassAndMethod() - { + assertFalse(second.isEmpty()); + assertFalse(second.isRegexTestClassPattern()); + assertFalse(second.isRegexTestMethodPattern()); + assertTrue(second.hasTestClassPattern()); + assertTrue(second.hasTestMethodPattern()); + assertEquals("**/MyTest.class", second.getTestClassPattern()); + assertEquals("second*", second.getTestMethodPattern()); + assertTrue(second.matchAsInclusive("your/pkg/MyTest.class", "secondTest")); + assertFalse(second.matchAsInclusive("your/pkg/MyTest.class", "thirdTest")); + } + + public void testNegativeNonRegexClassAndMethod() { Collection includedFilters = new ArrayList<>(); Collection excludedFilters = new ArrayList<>(); IncludedExcludedPatterns includedExcludedPatterns = new IncludedExcludedPatterns(); - TestListResolver.nonRegexClassAndMethods( "MyTest", "myTest", true, includedExcludedPatterns, includedFilters, - excludedFilters ); - assertFalse( includedExcludedPatterns.hasIncludedMethodPatterns ); - assertTrue( includedExcludedPatterns.hasExcludedMethodPatterns ); - assertTrue( includedFilters.isEmpty() ); - assertEquals( 1, excludedFilters.size() ); + TestListResolver.nonRegexClassAndMethods( + "MyTest", "myTest", true, includedExcludedPatterns, includedFilters, excludedFilters); + assertFalse(includedExcludedPatterns.hasIncludedMethodPatterns); + assertTrue(includedExcludedPatterns.hasExcludedMethodPatterns); + assertTrue(includedFilters.isEmpty()); + assertEquals(1, excludedFilters.size()); ResolvedTest test = excludedFilters.iterator().next(); - assertFalse( test.isEmpty() ); - assertFalse( test.isRegexTestClassPattern() ); - assertFalse( test.isRegexTestMethodPattern() ); - assertTrue( test.hasTestClassPattern() ); - assertTrue( test.hasTestMethodPattern() ); - assertEquals( "**/MyTest", test.getTestClassPattern() ); - assertEquals( "myTest", test.getTestMethodPattern() ); + assertFalse(test.isEmpty()); + assertFalse(test.isRegexTestClassPattern()); + assertFalse(test.isRegexTestMethodPattern()); + assertTrue(test.hasTestClassPattern()); + assertTrue(test.hasTestMethodPattern()); + assertEquals("**/MyTest", test.getTestClassPattern()); + assertEquals("myTest", test.getTestMethodPattern()); // ResolvedTest should not care about isExcluded. This attribute is handled by TestListResolver. - assertTrue( test.matchAsInclusive( "MyTest", "myTest" ) ); - assertFalse( test.matchAsInclusive( "MyTest", "otherTest" ) ); - assertFalse( test.matchAsInclusive( "pkg/OtherTest.class", "myTest" ) ); + assertTrue(test.matchAsInclusive("MyTest", "myTest")); + assertFalse(test.matchAsInclusive("MyTest", "otherTest")); + assertFalse(test.matchAsInclusive("pkg/OtherTest.class", "myTest")); } - public void testResolveTestRequest() - { + public void testResolveTestRequest() { Collection includedFilters = new ArrayList<>(); Collection excludedFilters = new ArrayList<>(); IncludedExcludedPatterns includedExcludedPatterns = new IncludedExcludedPatterns(); - TestListResolver.resolveTestRequest( "!%regex[.*.MyTest.class#myTest]", includedExcludedPatterns, - includedFilters, excludedFilters ); - assertFalse( includedExcludedPatterns.hasIncludedMethodPatterns ); - assertTrue( includedExcludedPatterns.hasExcludedMethodPatterns ); - assertTrue( includedFilters.isEmpty() ); - assertFalse( excludedFilters.isEmpty() ); - assertEquals( 1, excludedFilters.size() ); + TestListResolver.resolveTestRequest( + "!%regex[.*.MyTest.class#myTest]", includedExcludedPatterns, includedFilters, excludedFilters); + assertFalse(includedExcludedPatterns.hasIncludedMethodPatterns); + assertTrue(includedExcludedPatterns.hasExcludedMethodPatterns); + assertTrue(includedFilters.isEmpty()); + assertFalse(excludedFilters.isEmpty()); + assertEquals(1, excludedFilters.size()); ResolvedTest test = excludedFilters.iterator().next(); // ResolvedTest should not care about isExcluded. This attribute is handled by TestListResolver. - assertTrue( test.matchAsInclusive( "pkg/MyTest.class", "myTest" ) ); - assertFalse( test.matchAsInclusive( "pkg/MyTest.class", "otherTest" ) ); - assertFalse( test.matchAsInclusive( "pkg/OtherTest.class", "myTest" ) ); + assertTrue(test.matchAsInclusive("pkg/MyTest.class", "myTest")); + assertFalse(test.matchAsInclusive("pkg/MyTest.class", "otherTest")); + assertFalse(test.matchAsInclusive("pkg/OtherTest.class", "myTest")); } - public void testShouldRunTestWithoutMethod() - { - new TestListResolver( "**/*Test.class, !%regex[.*.MyTest.class#myTest]" ) - .shouldRun( "pkg/MyTest.class", null ); + public void testShouldRunTestWithoutMethod() { + new TestListResolver("**/*Test.class, !%regex[.*.MyTest.class#myTest]").shouldRun("pkg/MyTest.class", null); } - public void testShouldNotRunExcludedMethods() - { - TestListResolver resolver = new TestListResolver( "!#*Fail*, !%regex[#.*One], !#testSuccessThree" ); - assertTrue( resolver.shouldRun( "pkg/MyTest.class", null ) ); + public void testShouldNotRunExcludedMethods() { + TestListResolver resolver = new TestListResolver("!#*Fail*, !%regex[#.*One], !#testSuccessThree"); + assertTrue(resolver.shouldRun("pkg/MyTest.class", null)); } - public void testShouldRunSuiteWithIncludedMethods() - { - TestListResolver resolver = new TestListResolver( "#*Fail*, %regex[#.*One], #testSuccessThree" ); - assertTrue( resolver.shouldRun( "pkg/MyTest.class", null ) ); + public void testShouldRunSuiteWithIncludedMethods() { + TestListResolver resolver = new TestListResolver("#*Fail*, %regex[#.*One], #testSuccessThree"); + assertTrue(resolver.shouldRun("pkg/MyTest.class", null)); } - public void testShouldRunAny() - { + public void testShouldRunAny() { TestListResolver resolver = TestListResolver.getEmptyTestListResolver(); - assertTrue( resolver.shouldRun( "pkg/MyTest.class", null ) ); + assertTrue(resolver.shouldRun("pkg/MyTest.class", null)); - resolver = new TestListResolver( Collections.emptySet() ); - assertTrue( resolver.shouldRun( "pkg/MyTest.class", null ) ); + resolver = new TestListResolver(Collections.emptySet()); + assertTrue(resolver.shouldRun("pkg/MyTest.class", null)); } - public void testClassFilter() - { - TestListResolver resolver = new TestListResolver( "#test" ); - assertTrue( resolver.shouldRun( "pkg/MyTest.class", null ) ); + public void testClassFilter() { + TestListResolver resolver = new TestListResolver("#test"); + assertTrue(resolver.shouldRun("pkg/MyTest.class", null)); - resolver = new TestListResolver( "!#test" ); - assertTrue( resolver.shouldRun( "pkg/MyTest.class", null ) ); + resolver = new TestListResolver("!#test"); + assertTrue(resolver.shouldRun("pkg/MyTest.class", null)); - resolver = new TestListResolver( "SomeOtherClass" ); - assertFalse( resolver.shouldRun( "pkg/MyTest.class", null ) ); + resolver = new TestListResolver("SomeOtherClass"); + assertFalse(resolver.shouldRun("pkg/MyTest.class", null)); } - public void testBrokenPatternThrowsException() - { + public void testBrokenPatternThrowsException() { Collection included = emptySet(); - Collection excluded = asList( "BasicTest, !**/TestTwo, **/TestThree.java" ); - try - { - new TestListResolver( included, excluded ); - fail( "Expected: IllegalArgumentException" ); - } - catch ( IllegalArgumentException e ) - { + Collection excluded = asList("BasicTest, !**/TestTwo, **/TestThree.java"); + try { + new TestListResolver(included, excluded); + fail("Expected: IllegalArgumentException"); + } catch (IllegalArgumentException e) { // JUnit 3.x style - assertEquals( "Exclamation mark not expected in 'exclusion': BasicTest, !**/TestTwo, **/TestThree.java", - e.getLocalizedMessage() ); + assertEquals( + "Exclamation mark not expected in 'exclusion': BasicTest, !**/TestTwo, **/TestThree.java", + e.getLocalizedMessage()); } } - public void testMultipleExcludedClassesOnly() - { + public void testMultipleExcludedClassesOnly() { Collection included = emptySet(); - Collection excluded = asList( "BasicTest, **/TestTwo, **/TestThree.java" ); - TestListResolver resolver = new TestListResolver( included, excluded ); - assertFalse( resolver.shouldRun( "jiras/surefire745/BasicTest.class", null ) ); - assertFalse( resolver.shouldRun( "jiras/surefire745/TestTwo.class", null ) ); - assertFalse( resolver.shouldRun( "jiras/surefire745/TestThree.class", null ) ); - assertTrue( resolver.shouldRun( "jiras/surefire745/TestFour.class", null ) ); - } - - public void testMultipleExcludedClasses() - { - Collection included = singleton( DEFAULT_SUREFIRE_INCLUDED_TEST_PATTERNS ); - Collection excluded = asList( "BasicTest, **/TestTwo, **/TestThree.java" ); - TestListResolver resolver = new TestListResolver( included, excluded ); - assertFalse( resolver.shouldRun( "jiras/surefire745/BasicTest.class", null ) ); - assertFalse( resolver.shouldRun( "jiras/surefire745/TestTwo.class", null ) ); - assertFalse( resolver.shouldRun( "jiras/surefire745/TestThree.class", null ) ); - assertTrue( resolver.shouldRun( "jiras/surefire745/TestFour.class", null ) ); - } - - public void testAndFilters() - { - TestListResolver firstFilter = new TestListResolver( "BasicTest, **/TestTwo, **/TestThree.java" ); - TestListResolver secondFilter = new TestListResolver( "*icTest, Test???*" ); - TestFilter filter = firstFilter.and( secondFilter ); - - assertTrue( filter.shouldRun( "jiras/surefire745/BasicTest.class", null ) ); - assertTrue( filter.shouldRun( "jiras/surefire745/TestTwo.class", null ) ); - assertTrue( filter.shouldRun( "jiras/surefire745/TestThree.class", null ) ); - assertFalse( filter.shouldRun( "jiras/surefire745/TestFour.class", null ) ); - } - - public void testTestListResolverWithoutMethods() - { - ResolvedTest inc1 = new ResolvedTest( "A?Test.java", null, false ); - ResolvedTest inc2 = new ResolvedTest( "**/?Test", null, false ); - ResolvedTest exc1 = new ResolvedTest( "AATest", null, false ); - ResolvedTest exc2 = new ResolvedTest( "**/BTest.java", null, false ); - TestListResolver resolver = newTestListResolver( toSet( inc1, inc2 ), toSet( exc1, exc2 ) ); - assertThat( resolver.getPluginParameterTest(), is( "A?Test.java, **/?Test, !AATest, !**/BTest.java" ) ); - assertFalse( resolver.isEmpty() ); - assertFalse( resolver.hasIncludedMethodPatterns() ); - assertFalse( resolver.hasExcludedMethodPatterns() ); - assertFalse( resolver.hasMethodPatterns() ); - assertTrue( resolver.shouldRun( "ATest.class", null ) ); - assertFalse( resolver.shouldRun( "AATest.class", null ) ); - assertTrue( resolver.shouldRun( "ABTest.class", null ) ); - assertFalse( resolver.shouldRun( "BTest.class", null ) ); - assertTrue( resolver.shouldRun( "CTest.class", null ) ); - assertFalse( resolver.hasMethodPatterns() ); - } - - public void testTestListResolverWithMethods() - { - ResolvedTest inc1 = new ResolvedTest( "A?Test.java", null, false ); - ResolvedTest inc2 = new ResolvedTest( "*?Test", null, false ); - ResolvedTest exc1 = new ResolvedTest( "AATest", null, false ); - ResolvedTest exc2 = new ResolvedTest( "*BTest.java", "failedTest", false ); - TestListResolver resolver = newTestListResolver( toSet( inc1, inc2 ), toSet( exc1, exc2 ) ); - assertThat( resolver.getPluginParameterTest(), is( "A?Test.java, *?Test, !AATest, !*BTest.java#failedTest" ) ); - assertFalse( resolver.isEmpty() ); - assertFalse( resolver.hasIncludedMethodPatterns() ); - assertTrue( resolver.hasExcludedMethodPatterns() ); - assertTrue( resolver.hasMethodPatterns() ); - assertTrue( resolver.shouldRun( "ATest.class", null ) ); - assertFalse( resolver.shouldRun( "AATest.class", null ) ); - assertTrue( resolver.shouldRun( "ABTest.class", null ) ); - assertTrue( resolver.shouldRun( "BTest.class", null ) ); - assertFalse( resolver.shouldRun( "BTest.class", "failedTest" ) ); - assertTrue( resolver.shouldRun( "CTest.class", null ) ); - assertFalse( TestListResolver.optionallyWildcardFilter( resolver ).isEmpty() ); - } - - private static Set toSet( ResolvedTest... patterns ) - { + Collection excluded = asList("BasicTest, **/TestTwo, **/TestThree.java"); + TestListResolver resolver = new TestListResolver(included, excluded); + assertFalse(resolver.shouldRun("jiras/surefire745/BasicTest.class", null)); + assertFalse(resolver.shouldRun("jiras/surefire745/TestTwo.class", null)); + assertFalse(resolver.shouldRun("jiras/surefire745/TestThree.class", null)); + assertTrue(resolver.shouldRun("jiras/surefire745/TestFour.class", null)); + } + + public void testMultipleExcludedClasses() { + Collection included = singleton(DEFAULT_SUREFIRE_INCLUDED_TEST_PATTERNS); + Collection excluded = asList("BasicTest, **/TestTwo, **/TestThree.java"); + TestListResolver resolver = new TestListResolver(included, excluded); + assertFalse(resolver.shouldRun("jiras/surefire745/BasicTest.class", null)); + assertFalse(resolver.shouldRun("jiras/surefire745/TestTwo.class", null)); + assertFalse(resolver.shouldRun("jiras/surefire745/TestThree.class", null)); + assertTrue(resolver.shouldRun("jiras/surefire745/TestFour.class", null)); + } + + public void testAndFilters() { + TestListResolver firstFilter = new TestListResolver("BasicTest, **/TestTwo, **/TestThree.java"); + TestListResolver secondFilter = new TestListResolver("*icTest, Test???*"); + TestFilter filter = firstFilter.and(secondFilter); + + assertTrue(filter.shouldRun("jiras/surefire745/BasicTest.class", null)); + assertTrue(filter.shouldRun("jiras/surefire745/TestTwo.class", null)); + assertTrue(filter.shouldRun("jiras/surefire745/TestThree.class", null)); + assertFalse(filter.shouldRun("jiras/surefire745/TestFour.class", null)); + } + + public void testTestListResolverWithoutMethods() { + ResolvedTest inc1 = new ResolvedTest("A?Test.java", null, false); + ResolvedTest inc2 = new ResolvedTest("**/?Test", null, false); + ResolvedTest exc1 = new ResolvedTest("AATest", null, false); + ResolvedTest exc2 = new ResolvedTest("**/BTest.java", null, false); + TestListResolver resolver = newTestListResolver(toSet(inc1, inc2), toSet(exc1, exc2)); + assertThat(resolver.getPluginParameterTest(), is("A?Test.java, **/?Test, !AATest, !**/BTest.java")); + assertFalse(resolver.isEmpty()); + assertFalse(resolver.hasIncludedMethodPatterns()); + assertFalse(resolver.hasExcludedMethodPatterns()); + assertFalse(resolver.hasMethodPatterns()); + assertTrue(resolver.shouldRun("ATest.class", null)); + assertFalse(resolver.shouldRun("AATest.class", null)); + assertTrue(resolver.shouldRun("ABTest.class", null)); + assertFalse(resolver.shouldRun("BTest.class", null)); + assertTrue(resolver.shouldRun("CTest.class", null)); + assertFalse(resolver.hasMethodPatterns()); + } + + public void testTestListResolverWithMethods() { + ResolvedTest inc1 = new ResolvedTest("A?Test.java", null, false); + ResolvedTest inc2 = new ResolvedTest("*?Test", null, false); + ResolvedTest exc1 = new ResolvedTest("AATest", null, false); + ResolvedTest exc2 = new ResolvedTest("*BTest.java", "failedTest", false); + TestListResolver resolver = newTestListResolver(toSet(inc1, inc2), toSet(exc1, exc2)); + assertThat(resolver.getPluginParameterTest(), is("A?Test.java, *?Test, !AATest, !*BTest.java#failedTest")); + assertFalse(resolver.isEmpty()); + assertFalse(resolver.hasIncludedMethodPatterns()); + assertTrue(resolver.hasExcludedMethodPatterns()); + assertTrue(resolver.hasMethodPatterns()); + assertTrue(resolver.shouldRun("ATest.class", null)); + assertFalse(resolver.shouldRun("AATest.class", null)); + assertTrue(resolver.shouldRun("ABTest.class", null)); + assertTrue(resolver.shouldRun("BTest.class", null)); + assertFalse(resolver.shouldRun("BTest.class", "failedTest")); + assertTrue(resolver.shouldRun("CTest.class", null)); + assertFalse(TestListResolver.optionallyWildcardFilter(resolver).isEmpty()); + } + + private static Set toSet(ResolvedTest... patterns) { Set set = new LinkedHashSet<>(); - addAll( set, patterns ); + addAll(set, patterns); return set; } - public void testDefaultPatternsMatching() - { - Set inclusions = resolveClass( DEFAULT_SUREFIRE_INCLUDED_TEST_PATTERNS ); - Set exclusions = resolveClass( DEFAULT_SUREFIRE_EXCLUDED_TEST_PATTERNS ); - TestListResolver tlr = newTestListResolver( inclusions, exclusions ); - boolean shouldRun = tlr.shouldRun( "org/apache/maven/surefire/SomeTest.class", null ); - assertTrue( shouldRun ); + public void testDefaultPatternsMatching() { + Set inclusions = resolveClass(DEFAULT_SUREFIRE_INCLUDED_TEST_PATTERNS); + Set exclusions = resolveClass(DEFAULT_SUREFIRE_EXCLUDED_TEST_PATTERNS); + TestListResolver tlr = newTestListResolver(inclusions, exclusions); + boolean shouldRun = tlr.shouldRun("org/apache/maven/surefire/SomeTest.class", null); + assertTrue(shouldRun); } - public void testDefaultPatternsNotMatching() - { - Set inclusions = resolveClass( DEFAULT_SUREFIRE_INCLUDED_TEST_PATTERNS ); - Set exclusions = resolveClass( DEFAULT_SUREFIRE_EXCLUDED_TEST_PATTERNS ); - TestListResolver tlr = newTestListResolver( inclusions, exclusions ); - boolean shouldRun = tlr.shouldRun( "org/apache/maven/surefire/SomeTestNotRunning.class", null ); - assertFalse( shouldRun ); + public void testDefaultPatternsNotMatching() { + Set inclusions = resolveClass(DEFAULT_SUREFIRE_INCLUDED_TEST_PATTERNS); + Set exclusions = resolveClass(DEFAULT_SUREFIRE_EXCLUDED_TEST_PATTERNS); + TestListResolver tlr = newTestListResolver(inclusions, exclusions); + boolean shouldRun = tlr.shouldRun("org/apache/maven/surefire/SomeTestNotRunning.class", null); + assertFalse(shouldRun); } - public void testInclusiveWithDefaultExclusivePattern() - { - Set defaultExclusions = resolveClass( DEFAULT_SUREFIRE_EXCLUDED_TEST_PATTERNS ); - boolean runnable = newTestListResolver( resolveClass( "A*Test" ), defaultExclusions ) - .shouldRun( "org/apache/maven/surefire/ARunnableTest.class", null ); - assertTrue( runnable ); + public void testInclusiveWithDefaultExclusivePattern() { + Set defaultExclusions = resolveClass(DEFAULT_SUREFIRE_EXCLUDED_TEST_PATTERNS); + boolean runnable = newTestListResolver(resolveClass("A*Test"), defaultExclusions) + .shouldRun("org/apache/maven/surefire/ARunnableTest.class", null); + assertTrue(runnable); } - public void testWildcard() - { - TestListResolver tlr = TestListResolver.optionallyWildcardFilter( new TestListResolver( (String) null ) ); - assertThat( tlr, is( new TestListResolver( "**/*.class" ) ) ); - assertThat( tlr.isWildcard(), is( true ) ); - assertThat( tlr.isEmpty(), is( false ) ); + public void testWildcard() { + TestListResolver tlr = TestListResolver.optionallyWildcardFilter(new TestListResolver((String) null)); + assertThat(tlr, is(new TestListResolver("**/*.class"))); + assertThat(tlr.isWildcard(), is(true)); + assertThat(tlr.isEmpty(), is(false)); - tlr = TestListResolver.optionallyWildcardFilter( new TestListResolver( "**/**/MethodLessPattern.class" ) ); - assertThat( tlr, is( new TestListResolver( "**/*.class" ) ) ); - assertThat( tlr.isWildcard(), is( true ) ); - assertThat( tlr.isEmpty(), is( false ) ); + tlr = TestListResolver.optionallyWildcardFilter(new TestListResolver("**/**/MethodLessPattern.class")); + assertThat(tlr, is(new TestListResolver("**/*.class"))); + assertThat(tlr.isWildcard(), is(true)); + assertThat(tlr.isEmpty(), is(false)); } - public void testRegexRuleViolationQuotedHashMark() - { - try - { - new TestListResolver( "%regex[.\\Q#\\E.]" ); - fail( "IllegalArgumentException is expected" ); - } - catch ( IllegalArgumentException iea ) - { + public void testRegexRuleViolationQuotedHashMark() { + try { + new TestListResolver("%regex[.\\Q#\\E.]"); + fail("IllegalArgumentException is expected"); + } catch (IllegalArgumentException iea) { // expected } } - public void testRegexRuleViolationEnclosedMethodSeparator() - { - try - { - new TestListResolver( "%regex[(.|.#.)]" ); - fail( "IllegalArgumentException is expected" ); - } - catch ( IllegalArgumentException iea ) - { + public void testRegexRuleViolationEnclosedMethodSeparator() { + try { + new TestListResolver("%regex[(.|.#.)]"); + fail("IllegalArgumentException is expected"); + } catch (IllegalArgumentException iea) { // expected } } - public void testRegexRuleViolationMultipleHashmarkWithClassConstraint() - { - try - { - new TestListResolver( "%regex[.*#.|#.]" ); - fail( "IllegalArgumentException is expected" ); - } - catch ( IllegalArgumentException iea ) - { + public void testRegexRuleViolationMultipleHashmarkWithClassConstraint() { + try { + new TestListResolver("%regex[.*#.|#.]"); + fail("IllegalArgumentException is expected"); + } catch (IllegalArgumentException iea) { // expected } } - public void testRegexRuleViolationMultipleHashmarkForMethods() - { - try - { - new TestListResolver( "%regex[#.|#.]" ); - fail( "IllegalArgumentException is expected" ); - } - catch ( IllegalArgumentException iea ) - { + public void testRegexRuleViolationMultipleHashmarkForMethods() { + try { + new TestListResolver("%regex[#.|#.]"); + fail("IllegalArgumentException is expected"); + } catch (IllegalArgumentException iea) { // expected } } - public void testRegexRuleViolationInvalidClassPattern() - { - try - { - new TestListResolver( "%regex[.(.]" ) - .shouldRun( "x", "x" ); - fail( "IllegalArgumentException is expected" ); - } - catch ( IllegalArgumentException iea ) - { + public void testRegexRuleViolationInvalidClassPattern() { + try { + new TestListResolver("%regex[.(.]").shouldRun("x", "x"); + fail("IllegalArgumentException is expected"); + } catch (IllegalArgumentException iea) { // expected } } - public void testRegexRuleViolationInvalidMethodPattern() - { - try - { - new TestListResolver( "%regex[#.(.]" ); - fail( "IllegalArgumentException is expected" ); - } - catch ( IllegalArgumentException iea ) - { + public void testRegexRuleViolationInvalidMethodPattern() { + try { + new TestListResolver("%regex[#.(.]"); + fail("IllegalArgumentException is expected"); + } catch (IllegalArgumentException iea) { // expected } } - private static Set resolveClass( String patterns ) - { + private static Set resolveClass(String patterns) { Set resolved = new HashSet<>(); - for ( String pattern : patterns.split( "," ) ) - { - resolved.add( new ResolvedTest( CLASS, pattern, false ) ); + for (String pattern : patterns.split(",")) { + resolved.add(new ResolvedTest(CLASS, pattern, false)); } return resolved; } diff --git a/surefire-api/src/test/java/org/apache/maven/surefire/api/util/DefaultDirectoryScannerTest.java b/surefire-api/src/test/java/org/apache/maven/surefire/api/util/DefaultDirectoryScannerTest.java index 83c5bd9679..b82830b1ba 100644 --- a/surefire-api/src/test/java/org/apache/maven/surefire/api/util/DefaultDirectoryScannerTest.java +++ b/surefire-api/src/test/java/org/apache/maven/surefire/api/util/DefaultDirectoryScannerTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.api.util; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,37 +16,34 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.api.util; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; -import org.apache.maven.surefire.api.testset.TestSetFailedException; import junit.framework.TestCase; +import org.apache.maven.surefire.api.testset.TestSetFailedException; /** * Test of the directory scanner. */ -public class DefaultDirectoryScannerTest - extends TestCase -{ - public void testLocateTestClasses() - throws IOException, TestSetFailedException - { +public class DefaultDirectoryScannerTest extends TestCase { + public void testLocateTestClasses() throws IOException, TestSetFailedException { // use target as people can configure ide to compile in an other place than maven - File baseDir = new File( new File( "target" ).getCanonicalPath() ); + File baseDir = new File(new File("target").getCanonicalPath()); List include = new ArrayList<>(); - include.add( "**/*ZT*A.java" ); + include.add("**/*ZT*A.java"); List exclude = new ArrayList<>(); DefaultDirectoryScanner surefireDirectoryScanner = - new DefaultDirectoryScanner( baseDir, include, exclude, new ArrayList() ); + new DefaultDirectoryScanner(baseDir, include, exclude, new ArrayList()); String[] classNames = surefireDirectoryScanner.collectTests(); - assertNotNull( classNames ); - System.out.println( "classNames " + Arrays.asList( classNames ) ); - assertEquals( 4, classNames.length ); + assertNotNull(classNames); + System.out.println("classNames " + Arrays.asList(classNames)); + assertEquals(4, classNames.length); } } diff --git a/surefire-api/src/test/java/org/apache/maven/surefire/api/util/ReflectionUtilsTest.java b/surefire-api/src/test/java/org/apache/maven/surefire/api/util/ReflectionUtilsTest.java index 1c9ea47da0..a548cd8a33 100644 --- a/surefire-api/src/test/java/org/apache/maven/surefire/api/util/ReflectionUtilsTest.java +++ b/surefire-api/src/test/java/org/apache/maven/surefire/api/util/ReflectionUtilsTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.api.util; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,11 +16,12 @@ * specific language governing permissions and limitations * under the License. */ - -import org.junit.Test; +package org.apache.maven.surefire.api.util; import java.lang.reflect.Constructor; +import org.junit.Test; + import static org.assertj.core.api.Assertions.assertThat; /** @@ -31,112 +30,88 @@ * @author Tibor Digana (tibor17) * @since 2.20.1 */ -public class ReflectionUtilsTest -{ +public class ReflectionUtilsTest { @Test - public void shouldGetConstructor() throws Exception - { + public void shouldGetConstructor() throws Exception { Constructor constructor = - ReflectionUtils.tryGetConstructor( ClassWithParameterizedConstructor.class, int.class ); - assertThat( constructor ).isNotNull(); + ReflectionUtils.tryGetConstructor(ClassWithParameterizedConstructor.class, int.class); + assertThat(constructor).isNotNull(); // Verify the Constructor returned really is for the class it should be - assertThat( constructor.newInstance( 10 ) ).isInstanceOf( ClassWithParameterizedConstructor.class ); + assertThat(constructor.newInstance(10)).isInstanceOf(ClassWithParameterizedConstructor.class); } @Test - public void shouldNotGetNonExistingConstructor() - { - assertThat( ReflectionUtils.tryGetConstructor( ClassWithParameterizedConstructor.class, String.class ) ) - .isNull(); + public void shouldNotGetNonExistingConstructor() { + assertThat(ReflectionUtils.tryGetConstructor(ClassWithParameterizedConstructor.class, String.class)) + .isNull(); } @Test - public void shouldReloadClass() throws Exception - { + public void shouldReloadClass() throws Exception { ClassLoader cl = Thread.currentThread().getContextClassLoader(); - assertThat( ReflectionUtils.reloadClass( cl, new B() ) ) - .isEqualTo( B.class ); + assertThat(ReflectionUtils.reloadClass(cl, new B())).isEqualTo(B.class); } - @Test( expected = RuntimeException.class ) - public void shouldNotInvokeStaticMethod() - { - ReflectionUtils.invokeStaticMethod( ReflectionUtilsTest.class, "notCallable", - new Class[0], new Object[0] ); + @Test(expected = RuntimeException.class) + public void shouldNotInvokeStaticMethod() { + ReflectionUtils.invokeStaticMethod(ReflectionUtilsTest.class, "notCallable", new Class[0], new Object[0]); } @Test - public void shouldInvokeStaticMethod() - { - Object o = ReflectionUtils.invokeStaticMethod( ReflectionUtilsTest.class, "callable", - new Class[0], new Object[0] ); - assertThat( o ) - .isEqualTo( 3L ); + public void shouldInvokeStaticMethod() { + Object o = ReflectionUtils.invokeStaticMethod( + ReflectionUtilsTest.class, "callable", new Class[0], new Object[0]); + assertThat(o).isEqualTo(3L); } @Test - public void shouldInvokeMethodChain() - { - Class[] classes1 = { A.class, A.class }; - String[] chain = { "current", "pid" }; - Object o = ReflectionUtils.invokeMethodChain( classes1, chain, null ); - assertThat( o ) - .isEqualTo( 3L ); - - Class[] classes2 = { A.class, A.class, B.class }; - String[] longChain = { "current", "createB", "pid" }; - o = ReflectionUtils.invokeMethodChain( classes2, longChain, null ); - assertThat( o ) - .isEqualTo( 1L ); + public void shouldInvokeMethodChain() { + Class[] classes1 = {A.class, A.class}; + String[] chain = {"current", "pid"}; + Object o = ReflectionUtils.invokeMethodChain(classes1, chain, null); + assertThat(o).isEqualTo(3L); + + Class[] classes2 = {A.class, A.class, B.class}; + String[] longChain = {"current", "createB", "pid"}; + o = ReflectionUtils.invokeMethodChain(classes2, longChain, null); + assertThat(o).isEqualTo(1L); } @Test - public void shouldInvokeFallbackOnMethodChain() - { - Class[] classes1 = { A.class, A.class }; - String[] chain = { "current", "abc" }; - Object o = ReflectionUtils.invokeMethodChain( classes1, chain, 5L ); - assertThat( o ) - .isEqualTo( 5L ); - - Class[] classes2 = { A.class, B.class, B.class }; - String[] longChain = { "current", "createB", "abc" }; - o = ReflectionUtils.invokeMethodChain( classes2, longChain, 6L ); - assertThat( o ) - .isEqualTo( 6L ); + public void shouldInvokeFallbackOnMethodChain() { + Class[] classes1 = {A.class, A.class}; + String[] chain = {"current", "abc"}; + Object o = ReflectionUtils.invokeMethodChain(classes1, chain, 5L); + assertThat(o).isEqualTo(5L); + + Class[] classes2 = {A.class, B.class, B.class}; + String[] longChain = {"current", "createB", "abc"}; + o = ReflectionUtils.invokeMethodChain(classes2, longChain, 6L); + assertThat(o).isEqualTo(6L); } - private static void notCallable() - { - } + private static void notCallable() {} - public static long callable() - { + public static long callable() { return 3L; } - static class A - { - public static A current() - { + static class A { + public static A current() { return new A(); } - public long pid() - { + public long pid() { return 3L; } - public B createB() - { + public B createB() { return new B(); } } - static class B - { - public long pid() - { + static class B { + public long pid() { return 1L; } } @@ -144,10 +119,7 @@ public long pid() // The constructor has to be public for ReflectionUtils.tryGetConstructor to find it. Currently, the checkstyle // rules require that class be public too, and a public class must be documented, hence minimalist javadoc. /** */ - public static class ClassWithParameterizedConstructor - { - public ClassWithParameterizedConstructor( int param ) - { - } + public static class ClassWithParameterizedConstructor { + public ClassWithParameterizedConstructor(int param) {} } } diff --git a/surefire-api/src/test/java/org/apache/maven/surefire/api/util/RunOrderCalculatorTest.java b/surefire-api/src/test/java/org/apache/maven/surefire/api/util/RunOrderCalculatorTest.java index 63768cf03d..3ff55dc1f9 100644 --- a/surefire-api/src/test/java/org/apache/maven/surefire/api/util/RunOrderCalculatorTest.java +++ b/surefire-api/src/test/java/org/apache/maven/surefire/api/util/RunOrderCalculatorTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.api.util; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,45 +16,35 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.api.util; import java.util.LinkedHashSet; import java.util.Set; -import org.apache.maven.surefire.api.testset.RunOrderParameters; - import junit.framework.TestCase; +import org.apache.maven.surefire.api.testset.RunOrderParameters; /** * @author Kristian Rosenvold */ -public class RunOrderCalculatorTest - extends TestCase -{ +public class RunOrderCalculatorTest extends TestCase { - public void testOrderTestClasses() - { + public void testOrderTestClasses() { getClassesToRun(); - TestsToRun testsToRun = new TestsToRun( getClassesToRun() ); - RunOrderCalculator runOrderCalculator = new DefaultRunOrderCalculator( RunOrderParameters.alphabetical(), 1 ); - final TestsToRun testsToRun1 = runOrderCalculator.orderTestClasses( testsToRun ); - assertEquals( A.class, testsToRun1.iterator().next() ); + TestsToRun testsToRun = new TestsToRun(getClassesToRun()); + RunOrderCalculator runOrderCalculator = new DefaultRunOrderCalculator(RunOrderParameters.alphabetical(), 1); + final TestsToRun testsToRun1 = runOrderCalculator.orderTestClasses(testsToRun); + assertEquals(A.class, testsToRun1.iterator().next()); } - private Set> getClassesToRun() - { + private Set> getClassesToRun() { Set> classesToRun = new LinkedHashSet<>(); - classesToRun.add( B.class ); - classesToRun.add( A.class ); + classesToRun.add(B.class); + classesToRun.add(A.class); return classesToRun; } - static class A - { - - } + static class A {} - static class B - { - - } + static class B {} } diff --git a/surefire-api/src/test/java/org/apache/maven/surefire/api/util/RunOrderTest.java b/surefire-api/src/test/java/org/apache/maven/surefire/api/util/RunOrderTest.java index a579cc6274..d4683caee8 100644 --- a/surefire-api/src/test/java/org/apache/maven/surefire/api/util/RunOrderTest.java +++ b/surefire-api/src/test/java/org/apache/maven/surefire/api/util/RunOrderTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.api.util; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,52 +16,42 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.api.util; import junit.framework.TestCase; /** * */ -public class RunOrderTest - extends TestCase -{ - public void testShouldReturnRunOrderForLowerCaseName() - { - assertEquals( RunOrder.HOURLY, RunOrder.valueOfMulti( "hourly" )[0] ); +public class RunOrderTest extends TestCase { + public void testShouldReturnRunOrderForLowerCaseName() { + assertEquals(RunOrder.HOURLY, RunOrder.valueOfMulti("hourly")[0]); } - public void testMultiValue() - { - final RunOrder[] hourlies = RunOrder.valueOfMulti( "failedfirst,balanced" ); - assertEquals( RunOrder.FAILEDFIRST, hourlies[0] ); - assertEquals( RunOrder.BALANCED, hourlies[1] ); + public void testMultiValue() { + final RunOrder[] hourlies = RunOrder.valueOfMulti("failedfirst,balanced"); + assertEquals(RunOrder.FAILEDFIRST, hourlies[0]); + assertEquals(RunOrder.BALANCED, hourlies[1]); } - public void testAsString() - { - RunOrder[] orders = new RunOrder[]{ RunOrder.FAILEDFIRST, RunOrder.ALPHABETICAL }; - assertEquals( "failedfirst,alphabetical", RunOrder.asString( orders ) ); + public void testAsString() { + RunOrder[] orders = new RunOrder[] {RunOrder.FAILEDFIRST, RunOrder.ALPHABETICAL}; + assertEquals("failedfirst,alphabetical", RunOrder.asString(orders)); } - public void testShouldReturnRunOrderForUpperCaseName() - { - assertEquals( RunOrder.HOURLY, RunOrder.valueOfMulti( "HOURLY" )[0] ); + public void testShouldReturnRunOrderForUpperCaseName() { + assertEquals(RunOrder.HOURLY, RunOrder.valueOfMulti("HOURLY")[0]); } - public void testShouldReturnNullForNullName() - { - assertTrue( RunOrder.valueOfMulti( null ).length == 0 ); + public void testShouldReturnNullForNullName() { + assertTrue(RunOrder.valueOfMulti(null).length == 0); } - public void testShouldThrowExceptionForInvalidName() - { - try - { - RunOrder.valueOfMulti( "arbitraryName" ); - fail( "IllegalArgumentException not thrown." ); - } - catch ( IllegalArgumentException expected ) - { + public void testShouldThrowExceptionForInvalidName() { + try { + RunOrder.valueOfMulti("arbitraryName"); + fail("IllegalArgumentException not thrown."); + } catch (IllegalArgumentException expected) { } } diff --git a/surefire-api/src/test/java/org/apache/maven/surefire/api/util/ScanResultTest.java b/surefire-api/src/test/java/org/apache/maven/surefire/api/util/ScanResultTest.java index d7b789a396..dbea77206f 100644 --- a/surefire-api/src/test/java/org/apache/maven/surefire/api/util/ScanResultTest.java +++ b/surefire-api/src/test/java/org/apache/maven/surefire/api/util/ScanResultTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.api.util; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,32 +16,29 @@ * specific language governing permissions and limitations * under the License. */ - -import junit.framework.TestCase; +package org.apache.maven.surefire.api.util; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; +import junit.framework.TestCase; + /** * @author Kristian Rosenvold */ -public class ScanResultTest - extends TestCase -{ - public void testWriteTo() - throws Exception - { - List files = Arrays.asList( "abc", "cde" ); - DefaultScanResult scanResult = new DefaultScanResult( files ); +public class ScanResultTest extends TestCase { + public void testWriteTo() throws Exception { + List files = Arrays.asList("abc", "cde"); + DefaultScanResult scanResult = new DefaultScanResult(files); Map serialized = new HashMap<>(); - scanResult.writeTo( serialized ); + scanResult.writeTo(serialized); - DefaultScanResult read = DefaultScanResult.from( serialized ); + DefaultScanResult read = DefaultScanResult.from(serialized); List classes = read.getClasses(); - assertEquals( 2, classes.size() ); - assertTrue( classes.contains( "abc" ) ); - assertTrue( classes.contains( "cde" ) ); + assertEquals(2, classes.size()); + assertTrue(classes.contains("abc")); + assertTrue(classes.contains("cde")); } } diff --git a/surefire-api/src/test/java/org/apache/maven/surefire/api/util/SureFireFileManagerTest.java b/surefire-api/src/test/java/org/apache/maven/surefire/api/util/SureFireFileManagerTest.java index cda37d83fd..27c21e8a95 100644 --- a/surefire-api/src/test/java/org/apache/maven/surefire/api/util/SureFireFileManagerTest.java +++ b/surefire-api/src/test/java/org/apache/maven/surefire/api/util/SureFireFileManagerTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.api.util; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,11 +16,7 @@ * specific language governing permissions and limitations * under the License. */ - -import static org.assertj.core.api.Assertions.assertThat; - -import junit.framework.TestCase; -import org.junit.Test; +package org.apache.maven.surefire.api.util; import java.io.File; import java.io.IOException; @@ -32,33 +26,33 @@ import java.nio.file.attribute.PosixFilePermissions; import java.util.Set; +import junit.framework.TestCase; +import org.junit.Test; + +import static org.assertj.core.api.Assertions.assertThat; + /** * Unit test for the surefire instance of temp file manager. * * @author Markus Spann */ -public class SureFireFileManagerTest extends TestCase -{ +public class SureFireFileManagerTest extends TestCase { @Test - public void testCreateTempFile() throws IOException - { + public void testCreateTempFile() throws IOException { - File tempFile = SureFireFileManager.createTempFile( "sfprefix", "sfsuffix" ); - assertThat( tempFile ).isWritable(); - assertThat( tempFile.getName() ).startsWith( "sfprefix" ).endsWith( "sfsuffix" ); + File tempFile = SureFireFileManager.createTempFile("sfprefix", "sfsuffix"); + assertThat(tempFile).isWritable(); + assertThat(tempFile.getName()).startsWith("sfprefix").endsWith("sfsuffix"); File tempDir = tempFile.getParentFile(); - assertThat( tempDir ).isDirectory().isWritable(); - assertThat( tempDir.getName() ).startsWith( "surefire-" ).doesNotMatch( "[^A-Za-z0-9\\\\-_]" ); + assertThat(tempDir).isDirectory().isWritable(); + assertThat(tempDir.getName()).startsWith("surefire-").doesNotMatch("[^A-Za-z0-9\\\\-_]"); - boolean isPosix = FileSystems.getDefault().supportedFileAttributeViews().contains( "posix" ); - if ( isPosix ) - { - Set permissions = Files.getPosixFilePermissions( tempDir.toPath() ); - assertEquals( "rwxrwxr-x", PosixFilePermissions.toString( permissions ) ); + boolean isPosix = FileSystems.getDefault().supportedFileAttributeViews().contains("posix"); + if (isPosix) { + Set permissions = Files.getPosixFilePermissions(tempDir.toPath()); + assertEquals("rwxrwxr-x", PosixFilePermissions.toString(permissions)); } - } - } diff --git a/surefire-api/src/test/java/org/apache/maven/surefire/api/util/TempFileManagerTest.java b/surefire-api/src/test/java/org/apache/maven/surefire/api/util/TempFileManagerTest.java index d8e54f9eee..f4e37b6668 100644 --- a/surefire-api/src/test/java/org/apache/maven/surefire/api/util/TempFileManagerTest.java +++ b/surefire-api/src/test/java/org/apache/maven/surefire/api/util/TempFileManagerTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.api.util; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,90 +16,83 @@ * specific language governing permissions and limitations * under the License. */ - -import static org.assertj.core.api.Assertions.assertThat; -import static org.powermock.reflect.Whitebox.getInternalState; - -import junit.framework.TestCase; -import org.junit.Test; +package org.apache.maven.surefire.api.util; import java.io.File; import java.io.IOException; import java.util.List; import java.util.Random; +import junit.framework.TestCase; +import org.junit.Test; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.powermock.reflect.Whitebox.getInternalState; + /** * Unit test for the surefire temp file manager. * * @author Markus Spann */ -public class TempFileManagerTest extends TestCase -{ +public class TempFileManagerTest extends TestCase { @Test - public void testDefaultInstance() - { + public void testDefaultInstance() { TempFileManager tfm = TempFileManager.instance(); - assertSame( tfm, TempFileManager.instance( (File) null ) ); - assertSame( tfm, TempFileManager.instance( (String) null ) ); - assertSame( tfm, TempFileManager.instance( new File( System.getProperty( "java.io.tmpdir" ) ) ) ); + assertSame(tfm, TempFileManager.instance((File) null)); + assertSame(tfm, TempFileManager.instance((String) null)); + assertSame(tfm, TempFileManager.instance(new File(System.getProperty("java.io.tmpdir")))); - assertThat( tfm.getTempDir() ).isEqualTo( new File( System.getProperty( "java.io.tmpdir" ) ) ); - assertThat( tfm.toString() ).contains( "tempDir=" + tfm.getTempDir().getPath() ); - assertThat( tfm.toString() ).contains( "baseName=" + getInternalState( tfm, "baseName" ) ); + assertThat(tfm.getTempDir()).isEqualTo(new File(System.getProperty("java.io.tmpdir"))); + assertThat(tfm.toString()).contains("tempDir=" + tfm.getTempDir().getPath()); + assertThat(tfm.toString()).contains("baseName=" + getInternalState(tfm, "baseName")); } @Test - public void testSubdirInstance() - { + public void testSubdirInstance() { String subDirName = TempFileManagerTest.class.getSimpleName() + new Random().nextLong(); - TempFileManager tfm = TempFileManager.instance( subDirName ); - assertEquals( tfm.getTempDir(), new File( System.getProperty( "java.io.tmpdir" ), subDirName ) ); - assertFalse( tfm.getTempDir() + " should not exist", tfm.getTempDir().exists() ); + TempFileManager tfm = TempFileManager.instance(subDirName); + assertEquals(tfm.getTempDir(), new File(System.getProperty("java.io.tmpdir"), subDirName)); + assertFalse(tfm.getTempDir() + " should not exist", tfm.getTempDir().exists()); } @Test - public void testCreateTempFileAndDelete() - { + public void testCreateTempFileAndDelete() { String subDirName = TempFileManagerTest.class.getSimpleName() + new Random().nextLong(); - TempFileManager tfm = TempFileManager.instance( subDirName ); + TempFileManager tfm = TempFileManager.instance(subDirName); String prefix = "prefix"; String suffix = "suffix"; - File tempFile = tfm.createTempFile( prefix, suffix ); - assertThat( tempFile ).exists(); - assertThat( tempFile ).isWritable(); - assertTrue( tempFile.getParentFile().equals( tfm.getTempDir() ) ); - assertThat( tempFile.getName() ).startsWith( prefix ); - assertThat( tempFile.getName() ).endsWith( suffix ); - assertThat( tempFile.getName() ).contains( (String) getInternalState( tfm, "baseName" ) ); - - List tempFiles = getInternalState( tfm, "tempFiles" ); - assertThat( tempFiles ).contains( tempFile ); - assertThat( tempFiles ).size().isEqualTo( 1 ); + File tempFile = tfm.createTempFile(prefix, suffix); + assertThat(tempFile).exists(); + assertThat(tempFile).isWritable(); + assertTrue(tempFile.getParentFile().equals(tfm.getTempDir())); + assertThat(tempFile.getName()).startsWith(prefix); + assertThat(tempFile.getName()).endsWith(suffix); + assertThat(tempFile.getName()).contains((String) getInternalState(tfm, "baseName")); + + List tempFiles = getInternalState(tfm, "tempFiles"); + assertThat(tempFiles).contains(tempFile); + assertThat(tempFiles).size().isEqualTo(1); tfm.deleteAll(); - assertThat( tempFile ).doesNotExist(); - assertThat( tfm.getTempDir() ).doesNotExist(); + assertThat(tempFile).doesNotExist(); + assertThat(tfm.getTempDir()).doesNotExist(); } @Test - public void testFileCreateTempFile() throws IOException - { - File tempFile = File.createTempFile( "TempFileManager", ".tmp" ); - assertTrue( tempFile.exists() ); - assertTrue( tempFile.delete() ); - assertFalse( tempFile.exists() ); + public void testFileCreateTempFile() throws IOException { + File tempFile = File.createTempFile("TempFileManager", ".tmp"); + assertTrue(tempFile.exists()); + assertTrue(tempFile.delete()); + assertFalse(tempFile.exists()); } @Test - public void testDeleteOnExit() - { + public void testDeleteOnExit() { TempFileManager tfm = TempFileManager.instance(); - assertFalse( tfm.isDeleteOnExit() ); - tfm.setDeleteOnExit( true ); - assertTrue( tfm.isDeleteOnExit() ); + assertFalse(tfm.isDeleteOnExit()); + tfm.setDeleteOnExit(true); + assertTrue(tfm.isDeleteOnExit()); } - - } diff --git a/surefire-api/src/test/java/org/apache/maven/surefire/api/util/TestsToRunTest.java b/surefire-api/src/test/java/org/apache/maven/surefire/api/util/TestsToRunTest.java index f4bd13773e..07a9265872 100644 --- a/surefire-api/src/test/java/org/apache/maven/surefire/api/util/TestsToRunTest.java +++ b/surefire-api/src/test/java/org/apache/maven/surefire/api/util/TestsToRunTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.api.util; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.api.util; import java.util.Iterator; import java.util.LinkedHashSet; @@ -28,94 +27,79 @@ /** * @author Kristian Rosenvold */ -public class TestsToRunTest - extends TestCase -{ - public void testGetTestSets() - { +public class TestsToRunTest extends TestCase { + public void testGetTestSets() { Set> classes = new LinkedHashSet<>(); - classes.add( T1.class ); - classes.add( T2.class ); - TestsToRun testsToRun = new TestsToRun( classes ); + classes.add(T1.class); + classes.add(T2.class); + TestsToRun testsToRun = new TestsToRun(classes); Iterator> it = testsToRun.iterator(); - assertTrue( it.hasNext() ); - assertEquals( it.next(), T1.class ); - assertTrue( it.hasNext() ); - assertEquals( it.next(), T2.class ); - assertFalse( it.hasNext() ); + assertTrue(it.hasNext()); + assertEquals(it.next(), T1.class); + assertTrue(it.hasNext()); + assertEquals(it.next(), T2.class); + assertFalse(it.hasNext()); } - public void testContainsAtLeast() - { + public void testContainsAtLeast() { Set> classes = new LinkedHashSet<>(); - classes.add( T1.class ); - classes.add( T2.class ); - TestsToRun testsToRun = new TestsToRun( classes ); - assertTrue( testsToRun.containsAtLeast( 2 ) ); - assertFalse( testsToRun.containsAtLeast( 3 ) ); + classes.add(T1.class); + classes.add(T2.class); + TestsToRun testsToRun = new TestsToRun(classes); + assertTrue(testsToRun.containsAtLeast(2)); + assertFalse(testsToRun.containsAtLeast(3)); } - public void testContainsExactly() - { + public void testContainsExactly() { Set> classes = new LinkedHashSet<>(); - classes.add( T1.class ); - classes.add( T2.class ); - TestsToRun testsToRun = new TestsToRun( classes ); - assertFalse( testsToRun.containsExactly( 1 ) ); - assertTrue( testsToRun.containsExactly( 2 ) ); - assertFalse( testsToRun.containsExactly( 3 ) ); + classes.add(T1.class); + classes.add(T2.class); + TestsToRun testsToRun = new TestsToRun(classes); + assertFalse(testsToRun.containsExactly(1)); + assertTrue(testsToRun.containsExactly(2)); + assertFalse(testsToRun.containsExactly(3)); } - public void testToRunArray() - { + public void testToRunArray() { Set> classes = new LinkedHashSet<>(); - classes.add( T1.class ); - classes.add( T2.class ); - TestsToRun testsToRun = new TestsToRun( classes ); + classes.add(T1.class); + classes.add(T2.class); + TestsToRun testsToRun = new TestsToRun(classes); Class[] locatedClasses = testsToRun.getLocatedClasses(); - assertEquals( 2, locatedClasses.length ); + assertEquals(2, locatedClasses.length); } - public void testGetClassByName() - { + public void testGetClassByName() { Set> classes = new LinkedHashSet<>(); - classes.add( T1.class ); - classes.add( T2.class ); - TestsToRun testsToRun = new TestsToRun( classes ); - assertEquals( T1.class, testsToRun.getClassByName( "org.apache.maven.surefire.api.util.TestsToRunTest$T1" ) ); - assertEquals( T2.class, testsToRun.getClassByName( "org.apache.maven.surefire.api.util.TestsToRunTest$T2" ) ); - assertNull( testsToRun.getClassByName( "org.apache.maven.surefire.util.TestsToRunTest$T3" ) ); + classes.add(T1.class); + classes.add(T2.class); + TestsToRun testsToRun = new TestsToRun(classes); + assertEquals(T1.class, testsToRun.getClassByName("org.apache.maven.surefire.api.util.TestsToRunTest$T1")); + assertEquals(T2.class, testsToRun.getClassByName("org.apache.maven.surefire.api.util.TestsToRunTest$T2")); + assertNull(testsToRun.getClassByName("org.apache.maven.surefire.util.TestsToRunTest$T3")); } - public void testTwoIterators() - { + public void testTwoIterators() { Set> classes = new LinkedHashSet<>(); - classes.add( T1.class ); - classes.add( T2.class ); - TestsToRun testsToRun = new TestsToRun( classes ); + classes.add(T1.class); + classes.add(T2.class); + TestsToRun testsToRun = new TestsToRun(classes); Iterator> it1 = testsToRun.iterator(); - assertEquals( it1.next(), T1.class ); - assertTrue( it1.hasNext() ); + assertEquals(it1.next(), T1.class); + assertTrue(it1.hasNext()); Iterator> it2 = testsToRun.iterated(); - assertEquals( it1.next(), T2.class ); - assertFalse( it1.hasNext() ); - - assertEquals( it2.next(), T1.class ); - assertFalse( it1.hasNext() ); - } - - static class T1 - { + assertEquals(it1.next(), T2.class); + assertFalse(it1.hasNext()); + assertEquals(it2.next(), T1.class); + assertFalse(it1.hasNext()); } - static class T2 - { + static class T1 {} - } + static class T2 {} } - diff --git a/surefire-api/src/test/java/org/apache/maven/surefire/api/util/internal/AsyncSocketTest.java b/surefire-api/src/test/java/org/apache/maven/surefire/api/util/internal/AsyncSocketTest.java index dc2b6a2ea9..47fda06228 100644 --- a/surefire-api/src/test/java/org/apache/maven/surefire/api/util/internal/AsyncSocketTest.java +++ b/surefire-api/src/test/java/org/apache/maven/surefire/api/util/internal/AsyncSocketTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.api.util.internal; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,8 +16,7 @@ * specific language governing permissions and limitations * under the License. */ - -import org.junit.Test; +package org.apache.maven.surefire.api.util.internal; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; @@ -44,6 +41,8 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; +import org.junit.Test; + import static java.net.StandardSocketOptions.SO_KEEPALIVE; import static java.net.StandardSocketOptions.SO_REUSEADDR; import static java.net.StandardSocketOptions.TCP_NODELAY; @@ -54,122 +53,100 @@ /** * Low level Java benchmark test. */ -@SuppressWarnings( "checkstyle:magicnumber" ) -public class AsyncSocketTest -{ +@SuppressWarnings("checkstyle:magicnumber") +public class AsyncSocketTest { private static final String LONG_STRING = - "0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789"; + "0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789"; - private final CountDownLatch barrier = new CountDownLatch( 1 ); + private final CountDownLatch barrier = new CountDownLatch(1); private final AtomicLong writeTime = new AtomicLong(); private final AtomicLong readTime = new AtomicLong(); private volatile InetSocketAddress address; - @Test( timeout = 10_000L ) - public void test() throws Exception - { + @Test(timeout = 10_000L) + public void test() throws Exception { int forks = 2; ThreadFactory factory = DaemonThreadFactory.newDaemonThreadFactory(); - ExecutorService executorService = Executors.newCachedThreadPool( factory ); - if ( executorService instanceof ThreadPoolExecutor ) - { + ExecutorService executorService = Executors.newCachedThreadPool(factory); + if (executorService instanceof ThreadPoolExecutor) { ThreadPoolExecutor threadPoolExecutor = (ThreadPoolExecutor) executorService; - threadPoolExecutor.setCorePoolSize( Math.min( forks, Runtime.getRuntime().availableProcessors() ) ); + threadPoolExecutor.setCorePoolSize( + Math.min(forks, Runtime.getRuntime().availableProcessors())); threadPoolExecutor.prestartCoreThread(); } - AsynchronousChannelGroup group = AsynchronousChannelGroup.withThreadPool( executorService ); - AsynchronousServerSocketChannel server = AsynchronousServerSocketChannel.open( group ); - setTrueOptions( server, SO_REUSEADDR, TCP_NODELAY, SO_KEEPALIVE ); + AsynchronousChannelGroup group = AsynchronousChannelGroup.withThreadPool(executorService); + AsynchronousServerSocketChannel server = AsynchronousServerSocketChannel.open(group); + setTrueOptions(server, SO_REUSEADDR, TCP_NODELAY, SO_KEEPALIVE); InetAddress ip = InetAddress.getLoopbackAddress(); - server.bind( new InetSocketAddress( ip, 0 ), 1 ); + server.bind(new InetSocketAddress(ip, 0), 1); address = (InetSocketAddress) server.getLocalAddress(); System.gc(); - TimeUnit.SECONDS.sleep( 3L ); + TimeUnit.SECONDS.sleep(3L); - Thread tc = new Thread() - { + Thread tc = new Thread() { @Override - public void run() - { - try - { + public void run() { + try { client(); - } - catch ( Exception e ) - { + } catch (Exception e) { e.printStackTrace(); } } }; - tc.setDaemon( true ); + tc.setDaemon(true); tc.start(); Future acceptFuture = server.accept(); AsynchronousSocketChannel worker = acceptFuture.get(); - if ( !worker.isOpen() ) - { - throw new IOException( "client socket closed" ); + if (!worker.isOpen()) { + throw new IOException("client socket closed"); } - final InputStream is = newInputStream( worker ); - final OutputStream os = new BufferedOutputStream( newOutputStream( worker ), 64 * 1024 ); - - Thread tt = new Thread() - { - public void run() - { - try - { + final InputStream is = newInputStream(worker); + final OutputStream os = new BufferedOutputStream(newOutputStream(worker), 64 * 1024); + + Thread tt = new Thread() { + public void run() { + try { byte[] b = new byte[1024]; - is.read( b ); - } - catch ( Exception e ) - { - //e.printStackTrace(); + is.read(b); + } catch (Exception e) { + // e.printStackTrace(); } - } }; - tt.setName( "fork-1-event-thread-" ); - tt.setDaemon( true ); + tt.setName("fork-1-event-thread-"); + tt.setDaemon(true); tt.start(); - Thread t = new Thread() - { - @SuppressWarnings( "checkstyle:magicnumber" ) - public void run() - { - try - { - byte[] data = LONG_STRING.getBytes( StandardCharsets.US_ASCII ); + Thread t = new Thread() { + @SuppressWarnings("checkstyle:magicnumber") + public void run() { + try { + byte[] data = LONG_STRING.getBytes(StandardCharsets.US_ASCII); long t1 = System.currentTimeMillis(); int i = 0; - for ( ; i < 320_000; i++ ) - { - os.write( data ); + for (; i < 320_000; i++) { + os.write(data); long t2 = System.currentTimeMillis(); long spent = t2 - t1; - if ( i % 100_000 == 0 ) - { - System.out.println( spent + "ms: " + i ); + if (i % 100_000 == 0) { + System.out.println(spent + "ms: " + i); } } os.flush(); long spent = System.currentTimeMillis() - t1; - writeTime.set( spent ); - System.out.println( spent + "ms: " + i ); - } - catch ( IOException e ) - { + writeTime.set(spent); + System.out.println(spent + "ms: " + i); + } catch (IOException e) { e.printStackTrace(); } - } }; - t.setName( "commands-fork-1" ); - t.setDaemon( true ); + t.setName("commands-fork-1"); + t.setDaemon(true); t.start(); barrier.await(); @@ -181,48 +158,41 @@ public void run() // 160 millis on write using the asynchronous sockets // 320 millis on NIO blocking sockets - assertThat( writeTime.get() ) - .isLessThan( 1000L ); + assertThat(writeTime.get()).isLessThan(1000L); // 160 millis on read using the asynchronous sockets // 320 millis on NIO blocking sockets - assertThat( readTime.get() ) - .isLessThan( 1000L ); + assertThat(readTime.get()).isLessThan(1000L); } - @SuppressWarnings( "checkstyle:magicnumber" ) - private void client() throws Exception - { - InetSocketAddress hostAddress = new InetSocketAddress( InetAddress.getLoopbackAddress(), address.getPort() ); + @SuppressWarnings("checkstyle:magicnumber") + private void client() throws Exception { + InetSocketAddress hostAddress = new InetSocketAddress(InetAddress.getLoopbackAddress(), address.getPort()); AsynchronousSocketChannel clientSocketChannel = AsynchronousSocketChannel.open(); - clientSocketChannel.connect( hostAddress ).get(); // Wait until connection is done. - InputStream is = new BufferedInputStream( newInputStream( clientSocketChannel ), 64 * 1024 ); + clientSocketChannel.connect(hostAddress).get(); // Wait until connection is done. + InputStream is = new BufferedInputStream(newInputStream(clientSocketChannel), 64 * 1024); List bytes = new ArrayList<>(); long t1 = System.currentTimeMillis(); - for ( int i = 0; i < 320_000; i++ ) - { + for (int i = 0; i < 320_000; i++) { byte[] b = new byte[100]; - is.read( b ); - bytes.add( b ); + is.read(b); + bytes.add(b); } long t2 = System.currentTimeMillis(); long spent = t2 - t1; - readTime.set( spent ); - System.out.println( new String( bytes.get( bytes.size() - 1 ) ) ); - System.out.println( "received within " + spent + "ms" ); + readTime.set(spent); + System.out.println(new String(bytes.get(bytes.size() - 1))); + System.out.println("received within " + spent + "ms"); clientSocketChannel.close(); barrier.countDown(); } @SafeVarargs - private static void setTrueOptions( AsynchronousServerSocketChannel server, SocketOption... options ) - throws IOException - { - for ( SocketOption option : options ) - { - if ( server.supportedOptions().contains( option ) ) - { - server.setOption( option, true ); + private static void setTrueOptions(AsynchronousServerSocketChannel server, SocketOption... options) + throws IOException { + for (SocketOption option : options) { + if (server.supportedOptions().contains(option)) { + server.setOption(option, true); } } } diff --git a/surefire-api/src/test/java/org/apache/maven/surefire/api/util/internal/ChannelsReaderTest.java b/surefire-api/src/test/java/org/apache/maven/surefire/api/util/internal/ChannelsReaderTest.java index 78260d2ab4..8ed934b126 100644 --- a/surefire-api/src/test/java/org/apache/maven/surefire/api/util/internal/ChannelsReaderTest.java +++ b/surefire-api/src/test/java/org/apache/maven/surefire/api/util/internal/ChannelsReaderTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.api.util.internal; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,14 +16,7 @@ * specific language governing permissions and limitations * under the License. */ - -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.rules.TemporaryFolder; -import org.mockito.ArgumentCaptor; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; +package org.apache.maven.surefire.api.util.internal; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; @@ -45,6 +36,14 @@ import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.junit.rules.TemporaryFolder; +import org.mockito.ArgumentCaptor; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; + import static java.nio.file.Files.write; import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.Matchers.instanceOf; @@ -62,518 +61,407 @@ /** * The tests for {@link Channels#newChannel(InputStream)} and {@link Channels#newBufferedChannel(InputStream)}. */ -public class ChannelsReaderTest -{ +public class ChannelsReaderTest { @Rule public final ExpectedException ee = ExpectedException.none(); @Rule - public final TemporaryFolder tmp = TemporaryFolder.builder() - .assureDeletion() - .build(); + public final TemporaryFolder tmp = + TemporaryFolder.builder().assureDeletion().build(); @Test - public void shouldOverflowBuffer() throws Exception - { + public void shouldOverflowBuffer() throws Exception { ByteArrayOutputStream out = new ByteArrayOutputStream(); - WritableBufferedByteChannel channel = invokeMethod( Channels.class, "newChannel", - new Class[] {OutputStream.class, int.class}, new Object[] {out, 8} ); + WritableBufferedByteChannel channel = invokeMethod( + Channels.class, "newChannel", new Class[] {OutputStream.class, int.class}, new Object[] {out, 8}); - assertThat( channel.countBufferOverflows() ) - .isEqualTo( 0 ); + assertThat(channel.countBufferOverflows()).isEqualTo(0); - channel.write( ByteBuffer.wrap( new byte[] {1, 2, 3} ) ); + channel.write(ByteBuffer.wrap(new byte[] {1, 2, 3})); - assertThat( channel.countBufferOverflows() ) - .isEqualTo( 0 ); + assertThat(channel.countBufferOverflows()).isEqualTo(0); - channel.write( ByteBuffer.wrap( new byte[] {4, 5, 6, 7, 8} ) ); + channel.write(ByteBuffer.wrap(new byte[] {4, 5, 6, 7, 8})); - assertThat( channel.countBufferOverflows() ) - .isEqualTo( 0 ); + assertThat(channel.countBufferOverflows()).isEqualTo(0); - channel.write( ByteBuffer.wrap( new byte[] {9} ) ); + channel.write(ByteBuffer.wrap(new byte[] {9})); - assertThat( channel.countBufferOverflows() ) - .isEqualTo( 1 ); + assertThat(channel.countBufferOverflows()).isEqualTo(1); - assertThat( out.toByteArray() ) - .isEqualTo( new byte[] {1, 2, 3, 4, 5, 6, 7, 8, 9} ); + assertThat(out.toByteArray()).isEqualTo(new byte[] {1, 2, 3, 4, 5, 6, 7, 8, 9}); } @Test - public void exactBufferSize() throws Exception - { - ByteArrayInputStream is = new ByteArrayInputStream( new byte[] {1, 2, 3} ); - ReadableByteChannel channel = Channels.newChannel( is ); - ByteBuffer bb = ByteBuffer.allocate( 3 ); + public void exactBufferSize() throws Exception { + ByteArrayInputStream is = new ByteArrayInputStream(new byte[] {1, 2, 3}); + ReadableByteChannel channel = Channels.newChannel(is); + ByteBuffer bb = ByteBuffer.allocate(3); - int countWritten = channel.read( bb ); + int countWritten = channel.read(bb); - assertThat( countWritten ) - .isEqualTo( 3 ); + assertThat(countWritten).isEqualTo(3); - assertThat( bb.arrayOffset() ) - .isEqualTo( 0 ); + assertThat(bb.arrayOffset()).isEqualTo(0); - assertThat( ( (Buffer) bb ).position() ) - .isEqualTo( 3 ); + assertThat(((Buffer) bb).position()).isEqualTo(3); - assertThat( bb.remaining() ) - .isEqualTo( 0 ); + assertThat(bb.remaining()).isEqualTo(0); - assertThat( ( (Buffer) bb ).limit() ) - .isEqualTo( 3 ); + assertThat(((Buffer) bb).limit()).isEqualTo(3); - assertThat( bb.capacity() ) - .isEqualTo( 3 ); + assertThat(bb.capacity()).isEqualTo(3); - ( (Buffer) bb ).flip(); + ((Buffer) bb).flip(); - assertThat( bb.arrayOffset() ) - .isEqualTo( 0 ); + assertThat(bb.arrayOffset()).isEqualTo(0); - assertThat( ( (Buffer) bb ).position() ) - .isEqualTo( 0 ); + assertThat(((Buffer) bb).position()).isEqualTo(0); - assertThat( bb.remaining() ) - .isEqualTo( 3 ); + assertThat(bb.remaining()).isEqualTo(3); - assertThat( ( (Buffer) bb ).limit() ) - .isEqualTo( 3 ); + assertThat(((Buffer) bb).limit()).isEqualTo(3); - assertThat( bb.capacity() ) - .isEqualTo( 3 ); + assertThat(bb.capacity()).isEqualTo(3); - assertThat( bb.array() ) - .isEqualTo( new byte[] {1, 2, 3} ); + assertThat(bb.array()).isEqualTo(new byte[] {1, 2, 3}); - assertThat( channel.isOpen() ) - .isTrue(); + assertThat(channel.isOpen()).isTrue(); channel.close(); - assertThat( channel.isOpen() ) - .isFalse(); + assertThat(channel.isOpen()).isFalse(); } @Test - public void bufferedChannel() throws Exception - { - ByteArrayInputStream is = new ByteArrayInputStream( new byte[] {1, 2, 3} ); - ReadableByteChannel channel = Channels.newBufferedChannel( is ); - ByteBuffer bb = ByteBuffer.allocate( 4 ); + public void bufferedChannel() throws Exception { + ByteArrayInputStream is = new ByteArrayInputStream(new byte[] {1, 2, 3}); + ReadableByteChannel channel = Channels.newBufferedChannel(is); + ByteBuffer bb = ByteBuffer.allocate(4); - int countWritten = channel.read( bb ); + int countWritten = channel.read(bb); - assertThat( countWritten ) - .isEqualTo( 3 ); + assertThat(countWritten).isEqualTo(3); - assertThat( bb.arrayOffset() ) - .isEqualTo( 0 ); + assertThat(bb.arrayOffset()).isEqualTo(0); - assertThat( ( (Buffer) bb ).position() ) - .isEqualTo( 3 ); + assertThat(((Buffer) bb).position()).isEqualTo(3); - assertThat( bb.remaining() ) - .isEqualTo( 1 ); + assertThat(bb.remaining()).isEqualTo(1); - assertThat( ( (Buffer) bb ).limit() ) - .isEqualTo( 4 ); + assertThat(((Buffer) bb).limit()).isEqualTo(4); - assertThat( bb.capacity() ) - .isEqualTo( 4 ); + assertThat(bb.capacity()).isEqualTo(4); - ( (Buffer) bb ).flip(); + ((Buffer) bb).flip(); - assertThat( bb.arrayOffset() ) - .isEqualTo( 0 ); + assertThat(bb.arrayOffset()).isEqualTo(0); - assertThat( ( (Buffer) bb ).position() ) - .isEqualTo( 0 ); + assertThat(((Buffer) bb).position()).isEqualTo(0); - assertThat( bb.remaining() ) - .isEqualTo( 3 ); + assertThat(bb.remaining()).isEqualTo(3); - assertThat( ( (Buffer) bb ).limit() ) - .isEqualTo( 3 ); + assertThat(((Buffer) bb).limit()).isEqualTo(3); - assertThat( bb.capacity() ) - .isEqualTo( 4 ); + assertThat(bb.capacity()).isEqualTo(4); - assertThat( bb.array() ) - .isEqualTo( new byte[] {1, 2, 3, 0} ); + assertThat(bb.array()).isEqualTo(new byte[] {1, 2, 3, 0}); - assertThat( channel.isOpen() ) - .isTrue(); + assertThat(channel.isOpen()).isTrue(); channel.close(); - assertThat( channel.isOpen() ) - .isFalse(); + assertThat(channel.isOpen()).isFalse(); } @Test - public void biggerBuffer() throws Exception - { - ByteArrayInputStream is = new ByteArrayInputStream( new byte[] {1, 2, 3} ); - ReadableByteChannel channel = Channels.newChannel( is ); - ByteBuffer bb = ByteBuffer.allocate( 4 ); + public void biggerBuffer() throws Exception { + ByteArrayInputStream is = new ByteArrayInputStream(new byte[] {1, 2, 3}); + ReadableByteChannel channel = Channels.newChannel(is); + ByteBuffer bb = ByteBuffer.allocate(4); - int countWritten = channel.read( bb ); + int countWritten = channel.read(bb); - assertThat( countWritten ) - .isEqualTo( 3 ); + assertThat(countWritten).isEqualTo(3); - assertThat( bb.arrayOffset() ) - .isEqualTo( 0 ); + assertThat(bb.arrayOffset()).isEqualTo(0); - assertThat( ( (Buffer) bb ).position() ) - .isEqualTo( 3 ); + assertThat(((Buffer) bb).position()).isEqualTo(3); - assertThat( bb.remaining() ) - .isEqualTo( 1 ); + assertThat(bb.remaining()).isEqualTo(1); - assertThat( ( (Buffer) bb ).limit() ) - .isEqualTo( 4 ); + assertThat(((Buffer) bb).limit()).isEqualTo(4); - assertThat( bb.capacity() ) - .isEqualTo( 4 ); + assertThat(bb.capacity()).isEqualTo(4); - ( (Buffer) bb ).flip(); + ((Buffer) bb).flip(); - assertThat( bb.arrayOffset() ) - .isEqualTo( 0 ); + assertThat(bb.arrayOffset()).isEqualTo(0); - assertThat( ( (Buffer) bb ).position() ) - .isEqualTo( 0 ); + assertThat(((Buffer) bb).position()).isEqualTo(0); - assertThat( bb.remaining() ) - .isEqualTo( 3 ); + assertThat(bb.remaining()).isEqualTo(3); - assertThat( ( (Buffer) bb ).limit() ) - .isEqualTo( 3 ); + assertThat(((Buffer) bb).limit()).isEqualTo(3); - assertThat( bb.capacity() ) - .isEqualTo( 4 ); + assertThat(bb.capacity()).isEqualTo(4); - assertThat( bb.array() ) - .isEqualTo( new byte[] {1, 2, 3, 0} ); + assertThat(bb.array()).isEqualTo(new byte[] {1, 2, 3, 0}); - assertThat( channel.isOpen() ) - .isTrue(); + assertThat(channel.isOpen()).isTrue(); channel.close(); - assertThat( channel.isOpen() ) - .isFalse(); + assertThat(channel.isOpen()).isFalse(); } @Test - public void shouldFailAfterClosed() throws IOException - { - ByteArrayInputStream is = new ByteArrayInputStream( new byte[] {1, 2, 3} ); - ReadableByteChannel channel = Channels.newChannel( is ); + public void shouldFailAfterClosed() throws IOException { + ByteArrayInputStream is = new ByteArrayInputStream(new byte[] {1, 2, 3}); + ReadableByteChannel channel = Channels.newChannel(is); channel.close(); - assertThat( channel.isOpen() ).isFalse(); - ee.expect( ClosedChannelException.class ); - channel.read( ByteBuffer.allocate( 0 ) ); + assertThat(channel.isOpen()).isFalse(); + ee.expect(ClosedChannelException.class); + channel.read(ByteBuffer.allocate(0)); } @Test - public void shouldFailIfNotReadable() throws IOException - { - ByteArrayInputStream is = new ByteArrayInputStream( new byte[] {1, 2, 3} ); - ReadableByteChannel channel = Channels.newChannel( is ); - ee.expect( NonReadableChannelException.class ); - channel.read( ByteBuffer.allocate( 0 ).asReadOnlyBuffer() ); + public void shouldFailIfNotReadable() throws IOException { + ByteArrayInputStream is = new ByteArrayInputStream(new byte[] {1, 2, 3}); + ReadableByteChannel channel = Channels.newChannel(is); + ee.expect(NonReadableChannelException.class); + channel.read(ByteBuffer.allocate(0).asReadOnlyBuffer()); } @Test - public void shouldFailIOnDirectBuffer() throws IOException - { - ByteArrayInputStream is = new ByteArrayInputStream( new byte[] {1, 2, 3} ); - ReadableByteChannel channel = Channels.newChannel( is ); - ee.expect( NonReadableChannelException.class ); - channel.read( ByteBuffer.allocateDirect( 0 ) ); + public void shouldFailIOnDirectBuffer() throws IOException { + ByteArrayInputStream is = new ByteArrayInputStream(new byte[] {1, 2, 3}); + ReadableByteChannel channel = Channels.newChannel(is); + ee.expect(NonReadableChannelException.class); + channel.read(ByteBuffer.allocateDirect(0)); } @Test - public void shouldUseFileChannel() throws IOException - { + public void shouldUseFileChannel() throws IOException { File f = tmp.newFile(); - write( f.toPath(), new byte[] {1, 2, 3} ); - FileInputStream is = new FileInputStream( f ); - ReadableByteChannel channel = Channels.newChannel( is ); - ByteBuffer bb = ByteBuffer.allocate( 4 ); - int countWritten = channel.read( bb ); + write(f.toPath(), new byte[] {1, 2, 3}); + FileInputStream is = new FileInputStream(f); + ReadableByteChannel channel = Channels.newChannel(is); + ByteBuffer bb = ByteBuffer.allocate(4); + int countWritten = channel.read(bb); - assertThat( channel.isOpen() ) - .isTrue(); + assertThat(channel.isOpen()).isTrue(); channel.close(); - assertThat( channel.isOpen() ) - .isFalse(); + assertThat(channel.isOpen()).isFalse(); - assertThat( countWritten ) - .isEqualTo( 3 ); + assertThat(countWritten).isEqualTo(3); - assertThat( bb.arrayOffset() ) - .isEqualTo( 0 ); + assertThat(bb.arrayOffset()).isEqualTo(0); - assertThat( ( (Buffer) bb ).position() ) - .isEqualTo( 3 ); + assertThat(((Buffer) bb).position()).isEqualTo(3); - assertThat( bb.remaining() ) - .isEqualTo( 1 ); + assertThat(bb.remaining()).isEqualTo(1); - assertThat( ( (Buffer) bb ).limit() ) - .isEqualTo( 4 ); + assertThat(((Buffer) bb).limit()).isEqualTo(4); - assertThat( bb.capacity() ) - .isEqualTo( 4 ); + assertThat(bb.capacity()).isEqualTo(4); - ( (Buffer) bb ).flip(); + ((Buffer) bb).flip(); - assertThat( bb.arrayOffset() ) - .isEqualTo( 0 ); + assertThat(bb.arrayOffset()).isEqualTo(0); - assertThat( ( (Buffer) bb ).position() ) - .isEqualTo( 0 ); + assertThat(((Buffer) bb).position()).isEqualTo(0); - assertThat( bb.remaining() ) - .isEqualTo( 3 ); + assertThat(bb.remaining()).isEqualTo(3); - assertThat( ( (Buffer) bb ).limit() ) - .isEqualTo( 3 ); + assertThat(((Buffer) bb).limit()).isEqualTo(3); - assertThat( bb.capacity() ) - .isEqualTo( 4 ); + assertThat(bb.capacity()).isEqualTo(4); - assertThat( bb.array() ) - .isEqualTo( new byte[] {1, 2, 3, 0} ); + assertThat(bb.array()).isEqualTo(new byte[] {1, 2, 3, 0}); } - @Test( expected = IndexOutOfBoundsException.class ) - public void shouldValidateInput1() throws Exception - { - AsynchronousByteChannel channel = mock( AsynchronousByteChannel.class ); - InputStream is = Channels.newInputStream( channel ); - is.read( new byte[0], -1, 0 ); + @Test(expected = IndexOutOfBoundsException.class) + public void shouldValidateInput1() throws Exception { + AsynchronousByteChannel channel = mock(AsynchronousByteChannel.class); + InputStream is = Channels.newInputStream(channel); + is.read(new byte[0], -1, 0); } - @Test( expected = IndexOutOfBoundsException.class ) - public void shouldValidateInput2() throws Exception - { - AsynchronousByteChannel channel = mock( AsynchronousByteChannel.class ); - InputStream is = Channels.newInputStream( channel ); - is.read( new byte[0], 0, -1 ); + @Test(expected = IndexOutOfBoundsException.class) + public void shouldValidateInput2() throws Exception { + AsynchronousByteChannel channel = mock(AsynchronousByteChannel.class); + InputStream is = Channels.newInputStream(channel); + is.read(new byte[0], 0, -1); } - @Test( expected = IndexOutOfBoundsException.class ) - public void shouldValidateInput3() throws Exception - { - AsynchronousByteChannel channel = mock( AsynchronousByteChannel.class ); - InputStream is = Channels.newInputStream( channel ); - is.read( new byte[0], 1, 0 ); + @Test(expected = IndexOutOfBoundsException.class) + public void shouldValidateInput3() throws Exception { + AsynchronousByteChannel channel = mock(AsynchronousByteChannel.class); + InputStream is = Channels.newInputStream(channel); + is.read(new byte[0], 1, 0); } - @Test( expected = IndexOutOfBoundsException.class ) - public void shouldValidateInput4() throws Exception - { - AsynchronousByteChannel channel = mock( AsynchronousByteChannel.class ); - InputStream is = Channels.newInputStream( channel ); - is.read( new byte[0], 0, 1 ); + @Test(expected = IndexOutOfBoundsException.class) + public void shouldValidateInput4() throws Exception { + AsynchronousByteChannel channel = mock(AsynchronousByteChannel.class); + InputStream is = Channels.newInputStream(channel); + is.read(new byte[0], 0, 1); } @Test - public void shouldClose() throws Exception - { - AsynchronousByteChannel channel = mock( AsynchronousByteChannel.class ); - when( channel.isOpen() ).thenReturn( true ); - InputStream is = Channels.newInputStream( channel ); + public void shouldClose() throws Exception { + AsynchronousByteChannel channel = mock(AsynchronousByteChannel.class); + when(channel.isOpen()).thenReturn(true); + InputStream is = Channels.newInputStream(channel); is.close(); - verify( channel, times( 1 ) ).close(); + verify(channel, times(1)).close(); } @Test - public void shouldNotClose() throws Exception - { - AsynchronousByteChannel channel = mock( AsynchronousByteChannel.class ); - when( channel.isOpen() ).thenReturn( false ); - InputStream is = Channels.newInputStream( channel ); + public void shouldNotClose() throws Exception { + AsynchronousByteChannel channel = mock(AsynchronousByteChannel.class); + when(channel.isOpen()).thenReturn(false); + InputStream is = Channels.newInputStream(channel); is.close(); - verify( channel, never() ).close(); + verify(channel, never()).close(); } @Test - public void shouldAlreadyClosed() throws Exception - { - AsynchronousByteChannel channel = mock( AsynchronousByteChannel.class ); - when( channel.isOpen() ).thenReturn( true ); - doThrow( ClosedChannelException.class ).when( channel ).close(); - InputStream is = Channels.newInputStream( channel ); + public void shouldAlreadyClosed() throws Exception { + AsynchronousByteChannel channel = mock(AsynchronousByteChannel.class); + when(channel.isOpen()).thenReturn(true); + doThrow(ClosedChannelException.class).when(channel).close(); + InputStream is = Channels.newInputStream(channel); is.close(); - verify( channel ).close(); + verify(channel).close(); } @Test - public void shouldReadZeroLength() throws Exception - { - AsynchronousByteChannel channel = mock( AsynchronousByteChannel.class ); - InputStream is = Channels.newInputStream( channel ); - is.read( new byte[] { 5 }, 0, 0 ); - verifyZeroInteractions( channel ); + public void shouldReadZeroLength() throws Exception { + AsynchronousByteChannel channel = mock(AsynchronousByteChannel.class); + InputStream is = Channels.newInputStream(channel); + is.read(new byte[] {5}, 0, 0); + verifyZeroInteractions(channel); } @Test - public void shouldReadArray() throws Exception - { - AsynchronousByteChannel channel = mock( AsynchronousByteChannel.class ); - when( channel.read( any( ByteBuffer.class ) ) ) - .thenAnswer( new Answer>() - { - @Override - public Future answer( InvocationOnMock invocation ) throws Throwable - { - ByteBuffer bb = (ByteBuffer) invocation.getArguments()[0]; - bb.put( (byte) 3 ); - bb.put( (byte) 4 ); - Future future = mock( Future.class ); - when( future.get() ).thenReturn( 2 ); - return future; - } - } ); - - InputStream is = Channels.newInputStream( channel ); - ArgumentCaptor captured = ArgumentCaptor.forClass( ByteBuffer.class ); - byte[] b = new byte[] { 1, 2, 0, 0, 5 }; - is.read( b, 2, 2 ); - - verify( channel ).read( captured.capture() ); - verifyNoMoreInteractions( channel ); - - assertThat( captured.getAllValues() ) - .hasSize( 1 ); - - assertThat( captured.getAllValues().get( 0 ).array() ) - .containsOnly( new byte[] { 1, 2, 3, 4, 5 } ); - - assertThat( captured.getAllValues().get( 0 ).arrayOffset() ) - .isEqualTo( 0 ); - - assertThat( captured.getAllValues().get( 0 ).position() ) - .isEqualTo( 4 ); - - assertThat( captured.getAllValues().get( 0 ).limit() ) - .isEqualTo( 4 ); - - assertThat( captured.getAllValues().get( 0 ).capacity() ) - .isEqualTo( 5 ); + public void shouldReadArray() throws Exception { + AsynchronousByteChannel channel = mock(AsynchronousByteChannel.class); + when(channel.read(any(ByteBuffer.class))).thenAnswer(new Answer>() { + @Override + public Future answer(InvocationOnMock invocation) throws Throwable { + ByteBuffer bb = (ByteBuffer) invocation.getArguments()[0]; + bb.put((byte) 3); + bb.put((byte) 4); + Future future = mock(Future.class); + when(future.get()).thenReturn(2); + return future; + } + }); + + InputStream is = Channels.newInputStream(channel); + ArgumentCaptor captured = ArgumentCaptor.forClass(ByteBuffer.class); + byte[] b = new byte[] {1, 2, 0, 0, 5}; + is.read(b, 2, 2); + + verify(channel).read(captured.capture()); + verifyNoMoreInteractions(channel); + + assertThat(captured.getAllValues()).hasSize(1); + + assertThat(captured.getAllValues().get(0).array()).containsOnly(new byte[] {1, 2, 3, 4, 5}); + + assertThat(captured.getAllValues().get(0).arrayOffset()).isEqualTo(0); + + assertThat(captured.getAllValues().get(0).position()).isEqualTo(4); + + assertThat(captured.getAllValues().get(0).limit()).isEqualTo(4); + + assertThat(captured.getAllValues().get(0).capacity()).isEqualTo(5); } @Test - public void shouldRead() throws Exception - { - AsynchronousByteChannel channel = mock( AsynchronousByteChannel.class ); - when( channel.read( any( ByteBuffer.class ) ) ) - .thenAnswer( new Answer>() - { - @Override - public Future answer( InvocationOnMock invocation ) throws Throwable - { - ByteBuffer bb = (ByteBuffer) invocation.getArguments()[0]; - bb.put( (byte) 3 ); - Future future = mock( Future.class ); - when( future.get() ).thenReturn( 1 ); - return future; - } - } ); - - InputStream is = Channels.newInputStream( channel ); - ArgumentCaptor captured = ArgumentCaptor.forClass( ByteBuffer.class ); + public void shouldRead() throws Exception { + AsynchronousByteChannel channel = mock(AsynchronousByteChannel.class); + when(channel.read(any(ByteBuffer.class))).thenAnswer(new Answer>() { + @Override + public Future answer(InvocationOnMock invocation) throws Throwable { + ByteBuffer bb = (ByteBuffer) invocation.getArguments()[0]; + bb.put((byte) 3); + Future future = mock(Future.class); + when(future.get()).thenReturn(1); + return future; + } + }); + + InputStream is = Channels.newInputStream(channel); + ArgumentCaptor captured = ArgumentCaptor.forClass(ByteBuffer.class); int b = is.read(); - assertThat( b ) - .isEqualTo( 3 ); + assertThat(b).isEqualTo(3); - verify( channel ).read( captured.capture() ); - verifyNoMoreInteractions( channel ); + verify(channel).read(captured.capture()); + verifyNoMoreInteractions(channel); - assertThat( captured.getAllValues() ) - .hasSize( 1 ); + assertThat(captured.getAllValues()).hasSize(1); - assertThat( captured.getAllValues().get( 0 ).array() ) - .containsOnly( new byte[] { 3 } ); + assertThat(captured.getAllValues().get(0).array()).containsOnly(new byte[] {3}); - assertThat( captured.getAllValues().get( 0 ).arrayOffset() ) - .isEqualTo( 0 ); + assertThat(captured.getAllValues().get(0).arrayOffset()).isEqualTo(0); - assertThat( captured.getAllValues().get( 0 ).position() ) - .isEqualTo( 1 ); + assertThat(captured.getAllValues().get(0).position()).isEqualTo(1); - assertThat( captured.getAllValues().get( 0 ).limit() ) - .isEqualTo( 1 ); + assertThat(captured.getAllValues().get(0).limit()).isEqualTo(1); - assertThat( captured.getAllValues().get( 0 ).capacity() ) - .isEqualTo( 1 ); + assertThat(captured.getAllValues().get(0).capacity()).isEqualTo(1); } @Test - public void shouldThrowExceptionOnRead() throws Exception - { - AsynchronousByteChannel channel = mock( AsynchronousByteChannel.class ); - when( channel.read( any( ByteBuffer.class ) ) ) - .thenThrow( ShutdownChannelGroupException.class ); - InputStream is = Channels.newInputStream( channel ); - ee.expect( IOException.class ); - ee.expectCause( instanceOf( ShutdownChannelGroupException.class ) ); - is.read( new byte[1], 0, 1 ); + public void shouldThrowExceptionOnRead() throws Exception { + AsynchronousByteChannel channel = mock(AsynchronousByteChannel.class); + when(channel.read(any(ByteBuffer.class))).thenThrow(ShutdownChannelGroupException.class); + InputStream is = Channels.newInputStream(channel); + ee.expect(IOException.class); + ee.expectCause(instanceOf(ShutdownChannelGroupException.class)); + is.read(new byte[1], 0, 1); } @Test - public void shouldThrowExceptionOnFuture1() throws Exception - { - AsynchronousByteChannel channel = mock( AsynchronousByteChannel.class ); - Future future = mock( Future.class ); - when( future.get() ) - .thenThrow( new ExecutionException( new InterruptedIOException() ) ); - when( channel.read( any( ByteBuffer.class ) ) ) - .thenReturn( future ); - InputStream is = Channels.newInputStream( channel ); - ee.expect( InterruptedIOException.class ); - is.read( new byte[1], 0, 1 ); + public void shouldThrowExceptionOnFuture1() throws Exception { + AsynchronousByteChannel channel = mock(AsynchronousByteChannel.class); + Future future = mock(Future.class); + when(future.get()).thenThrow(new ExecutionException(new InterruptedIOException())); + when(channel.read(any(ByteBuffer.class))).thenReturn(future); + InputStream is = Channels.newInputStream(channel); + ee.expect(InterruptedIOException.class); + is.read(new byte[1], 0, 1); } @Test - public void shouldThrowExceptionOnFuture2() throws Exception - { - AsynchronousByteChannel channel = mock( AsynchronousByteChannel.class ); - Future future = mock( Future.class ); - when( future.get() ) - .thenThrow( new ExecutionException( new RuntimeException( "msg" ) ) ); - when( channel.read( any( ByteBuffer.class ) ) ) - .thenReturn( future ); - InputStream is = Channels.newInputStream( channel ); - ee.expect( IOException.class ); - ee.expectCause( instanceOf( RuntimeException.class ) ); - ee.expectMessage( "msg" ); - is.read( new byte[1], 0, 1 ); + public void shouldThrowExceptionOnFuture2() throws Exception { + AsynchronousByteChannel channel = mock(AsynchronousByteChannel.class); + Future future = mock(Future.class); + when(future.get()).thenThrow(new ExecutionException(new RuntimeException("msg"))); + when(channel.read(any(ByteBuffer.class))).thenReturn(future); + InputStream is = Channels.newInputStream(channel); + ee.expect(IOException.class); + ee.expectCause(instanceOf(RuntimeException.class)); + ee.expectMessage("msg"); + is.read(new byte[1], 0, 1); } @Test - public void shouldThrowExceptionOnFuture3() throws Exception - { - AsynchronousByteChannel channel = mock( AsynchronousByteChannel.class ); - Future future = mock( Future.class ); - when( future.get() ) - .thenThrow( new ExecutionException( "msg", null ) ); - when( channel.read( any( ByteBuffer.class ) ) ) - .thenReturn( future ); - InputStream is = Channels.newInputStream( channel ); - ee.expect( IOException.class ); - ee.expectMessage( "msg" ); - is.read( new byte[1], 0, 1 ); + public void shouldThrowExceptionOnFuture3() throws Exception { + AsynchronousByteChannel channel = mock(AsynchronousByteChannel.class); + Future future = mock(Future.class); + when(future.get()).thenThrow(new ExecutionException("msg", null)); + when(channel.read(any(ByteBuffer.class))).thenReturn(future); + InputStream is = Channels.newInputStream(channel); + ee.expect(IOException.class); + ee.expectMessage("msg"); + is.read(new byte[1], 0, 1); } } diff --git a/surefire-api/src/test/java/org/apache/maven/surefire/api/util/internal/ChannelsWriterTest.java b/surefire-api/src/test/java/org/apache/maven/surefire/api/util/internal/ChannelsWriterTest.java index 21d4877db1..9a854256ff 100644 --- a/surefire-api/src/test/java/org/apache/maven/surefire/api/util/internal/ChannelsWriterTest.java +++ b/surefire-api/src/test/java/org/apache/maven/surefire/api/util/internal/ChannelsWriterTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.api.util.internal; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,14 +16,7 @@ * specific language governing permissions and limitations * under the License. */ - -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.rules.TemporaryFolder; -import org.mockito.ArgumentCaptor; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; +package org.apache.maven.surefire.api.util.internal; import java.io.ByteArrayOutputStream; import java.io.File; @@ -43,6 +34,14 @@ import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.junit.rules.TemporaryFolder; +import org.mockito.ArgumentCaptor; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; + import static java.nio.file.Files.readAllBytes; import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.Matchers.instanceOf; @@ -59,433 +58,346 @@ /** * The tests for {@link Channels#newChannel(OutputStream)} and {@link Channels#newBufferedChannel(OutputStream)}. */ -public class ChannelsWriterTest -{ +public class ChannelsWriterTest { @Rule public final ExpectedException ee = ExpectedException.none(); @Rule - public final TemporaryFolder tmp = TemporaryFolder.builder() - .assureDeletion() - .build(); + public final TemporaryFolder tmp = + TemporaryFolder.builder().assureDeletion().build(); @Test - public void wrappedBuffer() throws Exception - { + public void wrappedBuffer() throws Exception { final boolean[] isFlush = {false}; - ByteArrayOutputStream out = new ByteArrayOutputStream() - { + ByteArrayOutputStream out = new ByteArrayOutputStream() { @Override - public void flush() throws IOException - { + public void flush() throws IOException { isFlush[0] = true; super.flush(); } }; - WritableByteChannel channel = Channels.newBufferedChannel( out ); - ByteBuffer bb = ByteBuffer.wrap( new byte[] {1, 2, 3} ); - int countWritten = channel.write( bb ); - assertThat( countWritten ) - .isEqualTo( 3 ); + WritableByteChannel channel = Channels.newBufferedChannel(out); + ByteBuffer bb = ByteBuffer.wrap(new byte[] {1, 2, 3}); + int countWritten = channel.write(bb); + assertThat(countWritten).isEqualTo(3); - assertThat( out.toByteArray() ) - .hasSize( 3 ) - .isEqualTo( new byte[] {1, 2, 3} ); + assertThat(out.toByteArray()).hasSize(3).isEqualTo(new byte[] {1, 2, 3}); - assertThat( isFlush ) - .hasSize( 1 ) - .containsOnly( true ); + assertThat(isFlush).hasSize(1).containsOnly(true); - assertThat( ( (Buffer) bb ).position() ) - .isEqualTo( 3 ); + assertThat(((Buffer) bb).position()).isEqualTo(3); - assertThat( ( (Buffer) bb ).limit() ) - .isEqualTo( 3 ); + assertThat(((Buffer) bb).limit()).isEqualTo(3); - assertThat( bb.capacity() ) - .isEqualTo( 3 ); + assertThat(bb.capacity()).isEqualTo(3); - assertThat( channel.isOpen() ) - .isTrue(); + assertThat(channel.isOpen()).isTrue(); } @Test - public void bigBuffer() throws Exception - { + public void bigBuffer() throws Exception { ByteArrayOutputStream out = new ByteArrayOutputStream(); - WritableByteChannel channel = Channels.newChannel( out ); - ByteBuffer bb = ByteBuffer.allocate( 4 ); - bb.put( (byte) 1 ); - bb.put( (byte) 2 ); - bb.put( (byte) 3 ); - int countWritten = channel.write( bb ); - assertThat( countWritten ).isEqualTo( 3 ); - assertThat( out.toByteArray() ) - .hasSize( 3 ) - .isEqualTo( new byte[] {1, 2, 3} ); - - assertThat( ( (Buffer) bb ).position() ) - .isEqualTo( 3 ); - - assertThat( ( (Buffer) bb ).limit() ) - .isEqualTo( 3 ); - - assertThat( bb.capacity() ) - .isEqualTo( 4 ); - - assertThat( channel.isOpen() ) - .isTrue(); + WritableByteChannel channel = Channels.newChannel(out); + ByteBuffer bb = ByteBuffer.allocate(4); + bb.put((byte) 1); + bb.put((byte) 2); + bb.put((byte) 3); + int countWritten = channel.write(bb); + assertThat(countWritten).isEqualTo(3); + assertThat(out.toByteArray()).hasSize(3).isEqualTo(new byte[] {1, 2, 3}); + + assertThat(((Buffer) bb).position()).isEqualTo(3); + + assertThat(((Buffer) bb).limit()).isEqualTo(3); + + assertThat(bb.capacity()).isEqualTo(4); + + assertThat(channel.isOpen()).isTrue(); } @Test - public void shouldFlushWhenEmptyBuffer() throws Exception - { + public void shouldFlushWhenEmptyBuffer() throws Exception { final boolean[] flushed = {false}; - ByteArrayOutputStream out = new ByteArrayOutputStream() - { + ByteArrayOutputStream out = new ByteArrayOutputStream() { @Override - public void flush() throws IOException - { + public void flush() throws IOException { flushed[0] = true; super.flush(); } }; - WritableByteChannel channel = Channels.newChannel( out ); - ByteBuffer bb = ByteBuffer.allocate( 0 ); - int countWritten = channel.write( bb ); - assertThat( countWritten ) - .isEqualTo( 0 ); - assertThat( flushed[0] ) - .isTrue(); + WritableByteChannel channel = Channels.newChannel(out); + ByteBuffer bb = ByteBuffer.allocate(0); + int countWritten = channel.write(bb); + assertThat(countWritten).isEqualTo(0); + assertThat(flushed[0]).isTrue(); } @Test - public void shouldFlushWhenEmptyBufferOnBufferedWrites() throws Exception - { + public void shouldFlushWhenEmptyBufferOnBufferedWrites() throws Exception { final boolean[] flushed = {false}; - ByteArrayOutputStream out = new ByteArrayOutputStream() - { + ByteArrayOutputStream out = new ByteArrayOutputStream() { @Override - public void flush() throws IOException - { + public void flush() throws IOException { flushed[0] = true; super.flush(); } }; - WritableBufferedByteChannel channel = Channels.newBufferedChannel( out ); - ByteBuffer bb = ByteBuffer.allocate( 0 ); - channel.writeBuffered( bb ); - assertThat( flushed[0] ) - .isFalse(); + WritableBufferedByteChannel channel = Channels.newBufferedChannel(out); + ByteBuffer bb = ByteBuffer.allocate(0); + channel.writeBuffered(bb); + assertThat(flushed[0]).isFalse(); } @Test - public void bufferedChannel() throws Exception - { + public void bufferedChannel() throws Exception { ByteArrayOutputStream out = new ByteArrayOutputStream(); - WritableBufferedByteChannel channel = Channels.newBufferedChannel( out ); - ByteBuffer bb = ByteBuffer.allocate( 5 ); - bb.put( (byte) 1 ); - bb.put( (byte) 2 ); - bb.put( (byte) 3 ); + WritableBufferedByteChannel channel = Channels.newBufferedChannel(out); + ByteBuffer bb = ByteBuffer.allocate(5); + bb.put((byte) 1); + bb.put((byte) 2); + bb.put((byte) 3); - channel.writeBuffered( bb ); + channel.writeBuffered(bb); - assertThat( out.toByteArray() ) - .isEmpty(); + assertThat(out.toByteArray()).isEmpty(); - channel.write( ByteBuffer.wrap( new byte[] {4} ) ); + channel.write(ByteBuffer.wrap(new byte[] {4})); - assertThat( out.toByteArray() ) - .hasSize( 4 ) - .isEqualTo( new byte[] {1, 2, 3, 4} ); + assertThat(out.toByteArray()).hasSize(4).isEqualTo(new byte[] {1, 2, 3, 4}); - assertThat( ( (Buffer) bb ).position() ) - .isEqualTo( 3 ); + assertThat(((Buffer) bb).position()).isEqualTo(3); - assertThat( ( (Buffer) bb ).limit() ) - .isEqualTo( 3 ); + assertThat(((Buffer) bb).limit()).isEqualTo(3); - assertThat( bb.capacity() ) - .isEqualTo( 5 ); + assertThat(bb.capacity()).isEqualTo(5); - assertThat( channel.isOpen() ) - .isTrue(); + assertThat(channel.isOpen()).isTrue(); } @Test - public void shouldFailAfterClosed() throws IOException - { + public void shouldFailAfterClosed() throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); - WritableByteChannel channel = Channels.newChannel( out ); + WritableByteChannel channel = Channels.newChannel(out); channel.close(); - assertThat( channel.isOpen() ).isFalse(); - ee.expect( ClosedChannelException.class ); - channel.write( ByteBuffer.allocate( 0 ) ); + assertThat(channel.isOpen()).isFalse(); + ee.expect(ClosedChannelException.class); + channel.write(ByteBuffer.allocate(0)); } @Test - public void shouldFailIfNotReadable() throws IOException - { + public void shouldFailIfNotReadable() throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); - WritableByteChannel channel = Channels.newChannel( out ); - ee.expect( NonWritableChannelException.class ); - channel.write( ByteBuffer.allocate( 0 ).asReadOnlyBuffer() ); + WritableByteChannel channel = Channels.newChannel(out); + ee.expect(NonWritableChannelException.class); + channel.write(ByteBuffer.allocate(0).asReadOnlyBuffer()); } @Test - public void shouldFailIOnDirectBuffer() throws IOException - { + public void shouldFailIOnDirectBuffer() throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); - WritableByteChannel channel = Channels.newChannel( out ); - ee.expect( NonWritableChannelException.class ); - channel.write( ByteBuffer.allocateDirect( 0 ) ); + WritableByteChannel channel = Channels.newChannel(out); + ee.expect(NonWritableChannelException.class); + channel.write(ByteBuffer.allocateDirect(0)); } @Test - public void shouldUseFileChannel() throws IOException - { + public void shouldUseFileChannel() throws IOException { File f = tmp.newFile(); - FileOutputStream os = new FileOutputStream( f ); - WritableByteChannel channel = Channels.newChannel( os ); - ByteBuffer bb = ByteBuffer.wrap( new byte[] {1, 2, 3} ); - channel.write( bb ); + FileOutputStream os = new FileOutputStream(f); + WritableByteChannel channel = Channels.newChannel(os); + ByteBuffer bb = ByteBuffer.wrap(new byte[] {1, 2, 3}); + channel.write(bb); - assertThat( channel.isOpen() ) - .isTrue(); + assertThat(channel.isOpen()).isTrue(); channel.close(); - assertThat( channel.isOpen() ) - .isFalse(); + assertThat(channel.isOpen()).isFalse(); - assertThat( readAllBytes( f.toPath() ) ) - .hasSize( 3 ) - .isEqualTo( new byte[] {1, 2, 3} ); + assertThat(readAllBytes(f.toPath())).hasSize(3).isEqualTo(new byte[] {1, 2, 3}); } - @Test( expected = IndexOutOfBoundsException.class ) - public void shouldValidateInput1() throws Exception - { - AsynchronousByteChannel channel = mock( AsynchronousByteChannel.class ); - OutputStream os = Channels.newOutputStream( channel ); - os.write( new byte[0], -1, 0 ); + @Test(expected = IndexOutOfBoundsException.class) + public void shouldValidateInput1() throws Exception { + AsynchronousByteChannel channel = mock(AsynchronousByteChannel.class); + OutputStream os = Channels.newOutputStream(channel); + os.write(new byte[0], -1, 0); } - @Test( expected = IndexOutOfBoundsException.class ) - public void shouldValidateInput2() throws Exception - { - AsynchronousByteChannel channel = mock( AsynchronousByteChannel.class ); - OutputStream os = Channels.newOutputStream( channel ); - os.write( new byte[0], 0, -1 ); + @Test(expected = IndexOutOfBoundsException.class) + public void shouldValidateInput2() throws Exception { + AsynchronousByteChannel channel = mock(AsynchronousByteChannel.class); + OutputStream os = Channels.newOutputStream(channel); + os.write(new byte[0], 0, -1); } - @Test( expected = IndexOutOfBoundsException.class ) - public void shouldValidateInput3() throws Exception - { - AsynchronousByteChannel channel = mock( AsynchronousByteChannel.class ); - OutputStream os = Channels.newOutputStream( channel ); - os.write( new byte[0], 1, 0 ); + @Test(expected = IndexOutOfBoundsException.class) + public void shouldValidateInput3() throws Exception { + AsynchronousByteChannel channel = mock(AsynchronousByteChannel.class); + OutputStream os = Channels.newOutputStream(channel); + os.write(new byte[0], 1, 0); } - @Test( expected = IndexOutOfBoundsException.class ) - public void shouldValidateInput4() throws Exception - { - AsynchronousByteChannel channel = mock( AsynchronousByteChannel.class ); - OutputStream os = Channels.newOutputStream( channel ); - os.write( new byte[0], 0, 1 ); + @Test(expected = IndexOutOfBoundsException.class) + public void shouldValidateInput4() throws Exception { + AsynchronousByteChannel channel = mock(AsynchronousByteChannel.class); + OutputStream os = Channels.newOutputStream(channel); + os.write(new byte[0], 0, 1); } @Test - public void shouldClose() throws Exception - { - AsynchronousByteChannel channel = mock( AsynchronousByteChannel.class ); - when( channel.isOpen() ).thenReturn( true ); - OutputStream os = Channels.newOutputStream( channel ); + public void shouldClose() throws Exception { + AsynchronousByteChannel channel = mock(AsynchronousByteChannel.class); + when(channel.isOpen()).thenReturn(true); + OutputStream os = Channels.newOutputStream(channel); os.close(); - verify( channel, times( 1 ) ).close(); + verify(channel, times(1)).close(); } @Test - public void shouldNotClose() throws Exception - { - AsynchronousByteChannel channel = mock( AsynchronousByteChannel.class ); - when( channel.isOpen() ).thenReturn( false ); - OutputStream os = Channels.newOutputStream( channel ); + public void shouldNotClose() throws Exception { + AsynchronousByteChannel channel = mock(AsynchronousByteChannel.class); + when(channel.isOpen()).thenReturn(false); + OutputStream os = Channels.newOutputStream(channel); os.close(); - verify( channel, never() ).close(); + verify(channel, never()).close(); } @Test - public void shouldAlreadyClosed() throws Exception - { - AsynchronousByteChannel channel = mock( AsynchronousByteChannel.class ); - when( channel.isOpen() ).thenReturn( true ); - doThrow( ClosedChannelException.class ).when( channel ).close(); - OutputStream os = Channels.newOutputStream( channel ); + public void shouldAlreadyClosed() throws Exception { + AsynchronousByteChannel channel = mock(AsynchronousByteChannel.class); + when(channel.isOpen()).thenReturn(true); + doThrow(ClosedChannelException.class).when(channel).close(); + OutputStream os = Channels.newOutputStream(channel); os.close(); - verify( channel ).close(); + verify(channel).close(); } @Test - public void shouldWriteZeroLength() throws Exception - { - AsynchronousByteChannel channel = mock( AsynchronousByteChannel.class ); - OutputStream os = Channels.newOutputStream( channel ); - os.write( new byte[] { 5 }, 0, 0 ); - verifyZeroInteractions( channel ); + public void shouldWriteZeroLength() throws Exception { + AsynchronousByteChannel channel = mock(AsynchronousByteChannel.class); + OutputStream os = Channels.newOutputStream(channel); + os.write(new byte[] {5}, 0, 0); + verifyZeroInteractions(channel); } @Test - public void shouldWriteArray() throws Exception - { - AsynchronousByteChannel channel = mock( AsynchronousByteChannel.class ); - when( channel.write( any( ByteBuffer.class ) ) ) - .thenAnswer( new Answer>() - { - @Override - public Future answer( InvocationOnMock invocation ) throws Throwable - { - ByteBuffer bb = (ByteBuffer) invocation.getArguments()[0]; - int i = 0; - for ( ; bb.hasRemaining(); i++ ) - { - bb.get(); - } - Future future = mock( Future.class ); - when( future.get() ).thenReturn( i ); - return future; + public void shouldWriteArray() throws Exception { + AsynchronousByteChannel channel = mock(AsynchronousByteChannel.class); + when(channel.write(any(ByteBuffer.class))).thenAnswer(new Answer>() { + @Override + public Future answer(InvocationOnMock invocation) throws Throwable { + ByteBuffer bb = (ByteBuffer) invocation.getArguments()[0]; + int i = 0; + for (; bb.hasRemaining(); i++) { + bb.get(); } - } ); + Future future = mock(Future.class); + when(future.get()).thenReturn(i); + return future; + } + }); - OutputStream os = Channels.newOutputStream( channel ); - ArgumentCaptor captured = ArgumentCaptor.forClass( ByteBuffer.class ); - os.write( new byte[] { 1, 2, 3, 4, 5 }, 2, 2 ); + OutputStream os = Channels.newOutputStream(channel); + ArgumentCaptor captured = ArgumentCaptor.forClass(ByteBuffer.class); + os.write(new byte[] {1, 2, 3, 4, 5}, 2, 2); - verify( channel ).write( captured.capture() ); - verifyNoMoreInteractions( channel ); + verify(channel).write(captured.capture()); + verifyNoMoreInteractions(channel); - assertThat( captured.getAllValues() ) - .hasSize( 1 ); + assertThat(captured.getAllValues()).hasSize(1); - assertThat( captured.getAllValues().get( 0 ).array() ) - .containsOnly( new byte[] { 1, 2, 3, 4, 5 } ); + assertThat(captured.getAllValues().get(0).array()).containsOnly(new byte[] {1, 2, 3, 4, 5}); - assertThat( captured.getAllValues().get( 0 ).arrayOffset() ) - .isEqualTo( 0 ); + assertThat(captured.getAllValues().get(0).arrayOffset()).isEqualTo(0); - assertThat( captured.getAllValues().get( 0 ).position() ) - .isEqualTo( 4 ); + assertThat(captured.getAllValues().get(0).position()).isEqualTo(4); - assertThat( captured.getAllValues().get( 0 ).limit() ) - .isEqualTo( 4 ); + assertThat(captured.getAllValues().get(0).limit()).isEqualTo(4); - assertThat( captured.getAllValues().get( 0 ).capacity() ) - .isEqualTo( 5 ); + assertThat(captured.getAllValues().get(0).capacity()).isEqualTo(5); } @Test - public void shouldWrite() throws Exception - { - AsynchronousByteChannel channel = mock( AsynchronousByteChannel.class ); - when( channel.write( any( ByteBuffer.class ) ) ) - .thenAnswer( new Answer>() - { - @Override - public Future answer( InvocationOnMock invocation ) throws Throwable - { - ByteBuffer bb = (ByteBuffer) invocation.getArguments()[0]; - int i = 0; - for ( ; bb.hasRemaining(); i++ ) - { - bb.get(); - } - Future future = mock( Future.class ); - when( future.get() ).thenReturn( i ); - return future; + public void shouldWrite() throws Exception { + AsynchronousByteChannel channel = mock(AsynchronousByteChannel.class); + when(channel.write(any(ByteBuffer.class))).thenAnswer(new Answer>() { + @Override + public Future answer(InvocationOnMock invocation) throws Throwable { + ByteBuffer bb = (ByteBuffer) invocation.getArguments()[0]; + int i = 0; + for (; bb.hasRemaining(); i++) { + bb.get(); } - } ); + Future future = mock(Future.class); + when(future.get()).thenReturn(i); + return future; + } + }); - OutputStream os = Channels.newOutputStream( channel ); - ArgumentCaptor captured = ArgumentCaptor.forClass( ByteBuffer.class ); - os.write( 3 ); + OutputStream os = Channels.newOutputStream(channel); + ArgumentCaptor captured = ArgumentCaptor.forClass(ByteBuffer.class); + os.write(3); - verify( channel ).write( captured.capture() ); - verifyNoMoreInteractions( channel ); + verify(channel).write(captured.capture()); + verifyNoMoreInteractions(channel); - assertThat( captured.getAllValues() ) - .hasSize( 1 ); + assertThat(captured.getAllValues()).hasSize(1); - assertThat( captured.getAllValues().get( 0 ).array() ) - .containsOnly( new byte[] { 3 } ); + assertThat(captured.getAllValues().get(0).array()).containsOnly(new byte[] {3}); - assertThat( captured.getAllValues().get( 0 ).arrayOffset() ) - .isEqualTo( 0 ); + assertThat(captured.getAllValues().get(0).arrayOffset()).isEqualTo(0); - assertThat( captured.getAllValues().get( 0 ).position() ) - .isEqualTo( 1 ); + assertThat(captured.getAllValues().get(0).position()).isEqualTo(1); - assertThat( captured.getAllValues().get( 0 ).limit() ) - .isEqualTo( 1 ); + assertThat(captured.getAllValues().get(0).limit()).isEqualTo(1); - assertThat( captured.getAllValues().get( 0 ).capacity() ) - .isEqualTo( 1 ); + assertThat(captured.getAllValues().get(0).capacity()).isEqualTo(1); } @Test - public void shouldThrowExceptionOnWrite() throws Exception - { - AsynchronousByteChannel channel = mock( AsynchronousByteChannel.class ); - when( channel.write( any( ByteBuffer.class ) ) ) - .thenThrow( ShutdownChannelGroupException.class ); - OutputStream os = Channels.newOutputStream( channel ); - ee.expect( IOException.class ); - ee.expectCause( instanceOf( ShutdownChannelGroupException.class ) ); - os.write( new byte[1], 0, 1 ); + public void shouldThrowExceptionOnWrite() throws Exception { + AsynchronousByteChannel channel = mock(AsynchronousByteChannel.class); + when(channel.write(any(ByteBuffer.class))).thenThrow(ShutdownChannelGroupException.class); + OutputStream os = Channels.newOutputStream(channel); + ee.expect(IOException.class); + ee.expectCause(instanceOf(ShutdownChannelGroupException.class)); + os.write(new byte[1], 0, 1); } @Test - public void shouldThrowExceptionOnFuture1() throws Exception - { - AsynchronousByteChannel channel = mock( AsynchronousByteChannel.class ); - Future future = mock( Future.class ); - when( future.get() ) - .thenThrow( new ExecutionException( new InterruptedIOException() ) ); - when( channel.write( any( ByteBuffer.class ) ) ) - .thenReturn( future ); - OutputStream os = Channels.newOutputStream( channel ); - ee.expect( InterruptedIOException.class ); - os.write( new byte[1], 0, 1 ); + public void shouldThrowExceptionOnFuture1() throws Exception { + AsynchronousByteChannel channel = mock(AsynchronousByteChannel.class); + Future future = mock(Future.class); + when(future.get()).thenThrow(new ExecutionException(new InterruptedIOException())); + when(channel.write(any(ByteBuffer.class))).thenReturn(future); + OutputStream os = Channels.newOutputStream(channel); + ee.expect(InterruptedIOException.class); + os.write(new byte[1], 0, 1); } @Test - public void shouldThrowExceptionOnFuture2() throws Exception - { - AsynchronousByteChannel channel = mock( AsynchronousByteChannel.class ); - Future future = mock( Future.class ); - when( future.get() ) - .thenThrow( new ExecutionException( new RuntimeException( "msg" ) ) ); - when( channel.write( any( ByteBuffer.class ) ) ) - .thenReturn( future ); - OutputStream os = Channels.newOutputStream( channel ); - ee.expect( IOException.class ); - ee.expectCause( instanceOf( RuntimeException.class ) ); - ee.expectMessage( "msg" ); - os.write( new byte[1], 0, 1 ); + public void shouldThrowExceptionOnFuture2() throws Exception { + AsynchronousByteChannel channel = mock(AsynchronousByteChannel.class); + Future future = mock(Future.class); + when(future.get()).thenThrow(new ExecutionException(new RuntimeException("msg"))); + when(channel.write(any(ByteBuffer.class))).thenReturn(future); + OutputStream os = Channels.newOutputStream(channel); + ee.expect(IOException.class); + ee.expectCause(instanceOf(RuntimeException.class)); + ee.expectMessage("msg"); + os.write(new byte[1], 0, 1); } @Test - public void shouldThrowExceptionOnFuture3() throws Exception - { - AsynchronousByteChannel channel = mock( AsynchronousByteChannel.class ); - Future future = mock( Future.class ); - when( future.get() ) - .thenThrow( new ExecutionException( "msg", null ) ); - when( channel.write( any( ByteBuffer.class ) ) ) - .thenReturn( future ); - OutputStream os = Channels.newOutputStream( channel ); - ee.expect( IOException.class ); - ee.expectMessage( "msg" ); - os.write( new byte[1], 0, 1 ); + public void shouldThrowExceptionOnFuture3() throws Exception { + AsynchronousByteChannel channel = mock(AsynchronousByteChannel.class); + Future future = mock(Future.class); + when(future.get()).thenThrow(new ExecutionException("msg", null)); + when(channel.write(any(ByteBuffer.class))).thenReturn(future); + OutputStream os = Channels.newOutputStream(channel); + ee.expect(IOException.class); + ee.expectMessage("msg"); + os.write(new byte[1], 0, 1); } } diff --git a/surefire-api/src/test/java/org/apache/maven/surefire/api/util/internal/ConcurrencyUtilsTest.java b/surefire-api/src/test/java/org/apache/maven/surefire/api/util/internal/ConcurrencyUtilsTest.java index 10c03e3618..a24157f9ad 100644 --- a/surefire-api/src/test/java/org/apache/maven/surefire/api/util/internal/ConcurrencyUtilsTest.java +++ b/surefire-api/src/test/java/org/apache/maven/surefire/api/util/internal/ConcurrencyUtilsTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.api.util.internal; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,19 +16,20 @@ * specific language governing permissions and limitations * under the License. */ - -import org.junit.Test; +package org.apache.maven.surefire.api.util.internal; import java.util.concurrent.ExecutionException; import java.util.concurrent.FutureTask; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; +import org.junit.Test; + import static org.apache.maven.surefire.api.util.internal.ConcurrencyUtils.runIfZeroCountDown; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; /** * Concurrency utilities. @@ -38,77 +37,68 @@ * @author Tibor Digana (tibor17) * @since 2.19 */ -public class ConcurrencyUtilsTest -{ +public class ConcurrencyUtilsTest { @Test - public void countDownShouldBeUnchangedAsZeroNegativeTest() - { - AtomicInteger atomicCounter = new AtomicInteger( 0 ); + public void countDownShouldBeUnchangedAsZeroNegativeTest() { + AtomicInteger atomicCounter = new AtomicInteger(0); AtomicBoolean runner = new AtomicBoolean(); - runIfZeroCountDown( () -> runner.set( true ), atomicCounter ); - assertFalse( runner.get() ); - assertThat( atomicCounter.get(), is( 0 ) ); + runIfZeroCountDown(() -> runner.set(true), atomicCounter); + assertFalse(runner.get()); + assertThat(atomicCounter.get(), is(0)); } @Test - public void countDownShouldBeUnchangedAsNegativeNegativeTest() - { - AtomicInteger atomicCounter = new AtomicInteger( -1 ); + public void countDownShouldBeUnchangedAsNegativeNegativeTest() { + AtomicInteger atomicCounter = new AtomicInteger(-1); AtomicBoolean runner = new AtomicBoolean(); - runIfZeroCountDown( () -> runner.set( true ), atomicCounter ); - assertFalse( runner.get() ); - assertThat( atomicCounter.get(), is( -1 ) ); + runIfZeroCountDown(() -> runner.set(true), atomicCounter); + assertFalse(runner.get()); + assertThat(atomicCounter.get(), is(-1)); } @Test - public void countDownShouldBeDecreasedByOneThreadModification() - { - AtomicInteger atomicCounter = new AtomicInteger( 10 ); + public void countDownShouldBeDecreasedByOneThreadModification() { + AtomicInteger atomicCounter = new AtomicInteger(10); AtomicBoolean runner = new AtomicBoolean(); - runIfZeroCountDown( () -> runner.set( true ), atomicCounter ); - assertFalse( runner.get() ); - assertThat( atomicCounter.get(), is( 9 ) ); + runIfZeroCountDown(() -> runner.set(true), atomicCounter); + assertFalse(runner.get()); + assertThat(atomicCounter.get(), is(9)); } @Test - public void countDownToZeroShouldBeDecreasedByOneThreadModification() - { - AtomicInteger atomicCounter = new AtomicInteger( 1 ); + public void countDownToZeroShouldBeDecreasedByOneThreadModification() { + AtomicInteger atomicCounter = new AtomicInteger(1); AtomicBoolean runner = new AtomicBoolean(); - runIfZeroCountDown( () -> runner.set( true ), atomicCounter ); - assertTrue( runner.get() ); - assertThat( atomicCounter.get(), is( 0 ) ); + runIfZeroCountDown(() -> runner.set(true), atomicCounter); + assertTrue(runner.get()); + assertThat(atomicCounter.get(), is(0)); } @Test - public void countDownShouldBeDecreasedByTwoThreadsModification() - throws ExecutionException, InterruptedException - { - AtomicInteger atomicCounter = new AtomicInteger( 3 ); + public void countDownShouldBeDecreasedByTwoThreadsModification() throws ExecutionException, InterruptedException { + AtomicInteger atomicCounter = new AtomicInteger(3); - FutureTask task = new FutureTask<>( () -> - { + FutureTask task = new FutureTask<>(() -> { AtomicBoolean runner = new AtomicBoolean(); - runIfZeroCountDown( () -> runner.set( true ), atomicCounter ); + runIfZeroCountDown(() -> runner.set(true), atomicCounter); return runner.get(); - } ); - Thread t = new Thread( task ); + }); + Thread t = new Thread(task); t.start(); AtomicBoolean runner = new AtomicBoolean(); - runIfZeroCountDown( () -> runner.set( true ), atomicCounter ); - assertFalse( runner.get() ); + runIfZeroCountDown(() -> runner.set(true), atomicCounter); + assertFalse(runner.get()); - assertFalse( task.get() ); + assertFalse(task.get()); - assertThat( atomicCounter.get(), is( 1 ) ); + assertThat(atomicCounter.get(), is(1)); - runner.set( false ); - runIfZeroCountDown( () -> runner.set( true ), atomicCounter ); - assertTrue( runner.get() ); + runner.set(false); + runIfZeroCountDown(() -> runner.set(true), atomicCounter); + assertTrue(runner.get()); - assertThat( atomicCounter.get(), is( 0 ) ); + assertThat(atomicCounter.get(), is(0)); } - } diff --git a/surefire-api/src/test/java/org/apache/maven/surefire/api/util/internal/ImmutableMapTest.java b/surefire-api/src/test/java/org/apache/maven/surefire/api/util/internal/ImmutableMapTest.java index 8c64ecd478..2d16bff735 100644 --- a/surefire-api/src/test/java/org/apache/maven/surefire/api/util/internal/ImmutableMapTest.java +++ b/surefire-api/src/test/java/org/apache/maven/surefire/api/util/internal/ImmutableMapTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.api.util.internal; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,10 +16,7 @@ * specific language governing permissions and limitations * under the License. */ - -import org.apache.maven.surefire.api.util.internal.ImmutableMap.Node; -import org.junit.Before; -import org.junit.Test; +package org.apache.maven.surefire.api.util.internal; import java.util.Collections; import java.util.Iterator; @@ -30,6 +25,10 @@ import java.util.Map.Entry; import java.util.Set; +import org.apache.maven.surefire.api.util.internal.ImmutableMap.Node; +import org.junit.Before; +import org.junit.Test; + import static org.hamcrest.Matchers.hasItem; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.is; @@ -40,125 +39,114 @@ /** * @since 2.20 */ -public class ImmutableMapTest -{ +public class ImmutableMapTest { private ImmutableMap map; @Before - public void setUp() - { + public void setUp() { Map backingMap = new LinkedHashMap<>(); - backingMap.put( "a", "1" ); - backingMap.put( "x", null ); - backingMap.put( "b", "2" ); - backingMap.put( "c", "3" ); - backingMap.put( "", "" ); - backingMap.put( null, "1" ); - map = new ImmutableMap<>( backingMap ); + backingMap.put("a", "1"); + backingMap.put("x", null); + backingMap.put("b", "2"); + backingMap.put("c", "3"); + backingMap.put("", ""); + backingMap.put(null, "1"); + map = new ImmutableMap<>(backingMap); } @Test - public void testEntrySet() - { + public void testEntrySet() { Set> entries = map.entrySet(); - assertThat( entries, hasSize( 6 ) ); - assertThat( entries, hasItem( new Node<>( "a", "1" ) ) ); - assertThat( entries, hasItem( new Node<>( "x", (String) null ) ) ); - assertThat( entries, hasItem( new Node<>( "b", "2" ) ) ); - assertThat( entries, hasItem( new Node<>( "c", "3" ) ) ); - assertThat( entries, hasItem( new Node<>( "", "" ) ) ); - assertThat( entries, hasItem( new Node<>( (String) null, "1" ) ) ); + assertThat(entries, hasSize(6)); + assertThat(entries, hasItem(new Node<>("a", "1"))); + assertThat(entries, hasItem(new Node<>("x", (String) null))); + assertThat(entries, hasItem(new Node<>("b", "2"))); + assertThat(entries, hasItem(new Node<>("c", "3"))); + assertThat(entries, hasItem(new Node<>("", ""))); + assertThat(entries, hasItem(new Node<>((String) null, "1"))); } @Test - public void testGetter() - { - assertThat( map.size(), is( 6 ) ); - assertThat( map.get( "a" ), is( "1" ) ); - assertThat( map.get( "x" ), is( (String) null ) ); - assertThat( map.get( "b" ), is( "2" ) ); - assertThat( map.get( "c" ), is( "3" ) ); - assertThat( map.get( "" ), is( "" ) ); - assertThat( map.get( null ), is( "1" ) ); + public void testGetter() { + assertThat(map.size(), is(6)); + assertThat(map.get("a"), is("1")); + assertThat(map.get("x"), is((String) null)); + assertThat(map.get("b"), is("2")); + assertThat(map.get("c"), is("3")); + assertThat(map.get(""), is("")); + assertThat(map.get(null), is("1")); } - @Test( expected = UnsupportedOperationException.class ) - public void shouldNotModifyEntries() - { + @Test(expected = UnsupportedOperationException.class) + public void shouldNotModifyEntries() { map.entrySet().clear(); } @Test - public void shouldSafelyEnumerateEntries() - { + public void shouldSafelyEnumerateEntries() { Iterator> it = map.entrySet().iterator(); - assertThat( it.hasNext(), is( true ) ); + assertThat(it.hasNext(), is(true)); Entry val = it.next(); - assertThat( val.getKey(), is( "a" ) ); - assertThat( val.getValue(), is( "1" ) ); + assertThat(val.getKey(), is("a")); + assertThat(val.getValue(), is("1")); - assertThat( it.hasNext(), is( true ) ); + assertThat(it.hasNext(), is(true)); val = it.next(); - assertThat( val.getKey(), is( "x" ) ); - assertThat( val.getValue(), is( nullValue() ) ); + assertThat(val.getKey(), is("x")); + assertThat(val.getValue(), is(nullValue())); - assertThat( it.hasNext(), is( true ) ); + assertThat(it.hasNext(), is(true)); val = it.next(); - assertThat( val.getKey(), is( "b" ) ); - assertThat( val.getValue(), is( "2" ) ); + assertThat(val.getKey(), is("b")); + assertThat(val.getValue(), is("2")); - assertThat( it.hasNext(), is( true ) ); + assertThat(it.hasNext(), is(true)); val = it.next(); - assertThat( val.getKey(), is( "c" ) ); - assertThat( val.getValue(), is( "3" ) ); + assertThat(val.getKey(), is("c")); + assertThat(val.getValue(), is("3")); - assertThat( it.hasNext(), is( true ) ); + assertThat(it.hasNext(), is(true)); val = it.next(); - assertThat( val.getKey(), is( "" ) ); - assertThat( val.getValue(), is( "" ) ); + assertThat(val.getKey(), is("")); + assertThat(val.getValue(), is("")); - assertThat( it.hasNext(), is( true ) ); + assertThat(it.hasNext(), is(true)); val = it.next(); - assertThat( val.getKey(), is( nullValue() ) ); - assertThat( val.getValue(), is( "1" ) ); + assertThat(val.getKey(), is(nullValue())); + assertThat(val.getValue(), is("1")); - assertThat( it.hasNext(), is( false ) ); + assertThat(it.hasNext(), is(false)); } - @Test( expected = UnsupportedOperationException.class ) - public void shouldNotSetEntries() - { - map.entrySet().iterator().next().setValue( "" ); + @Test(expected = UnsupportedOperationException.class) + public void shouldNotSetEntries() { + map.entrySet().iterator().next().setValue(""); } - @Test( expected = UnsupportedOperationException.class ) - public void shouldNotRemove() - { - map.remove( "a" ); + @Test(expected = UnsupportedOperationException.class) + public void shouldNotRemove() { + map.remove("a"); } - @Test( expected = UnsupportedOperationException.class ) - public void shouldNotRemoveNull() - { - map.remove( null ); + @Test(expected = UnsupportedOperationException.class) + public void shouldNotRemoveNull() { + map.remove(null); } @Test - public void shouldNotHaveEqualEntry() - { - Map map = new ImmutableMap<>( Collections.singletonMap( "k", "v" ) ); + public void shouldNotHaveEqualEntry() { + Map map = new ImmutableMap<>(Collections.singletonMap("k", "v")); Entry e = map.entrySet().iterator().next(); - assertThat( e, is( not( (Entry) null ) ) ); - assertThat( e, is( not( new Object() ) ) ); + assertThat(e, is(not((Entry) null))); + assertThat(e, is(not(new Object()))); } @Test - public void shouldHaveEqualEntry() - { - Map map = new ImmutableMap<>( Collections.singletonMap( "k", "v" ) ); + public void shouldHaveEqualEntry() { + Map map = new ImmutableMap<>(Collections.singletonMap("k", "v")); Entry e = map.entrySet().iterator().next(); - assertThat( e, is( e ) ); - assertThat( e, is( (Entry) new Node<>( "k", "v" ) ) ); + assertThat(e, is(e)); + assertThat(e, is((Entry) new Node<>("k", "v"))); } } diff --git a/surefire-api/src/test/java/org/apache/maven/surefire/api/util/internal/ObjectUtilsTest.java b/surefire-api/src/test/java/org/apache/maven/surefire/api/util/internal/ObjectUtilsTest.java index ef5035ec47..9e1640b6a0 100644 --- a/surefire-api/src/test/java/org/apache/maven/surefire/api/util/internal/ObjectUtilsTest.java +++ b/surefire-api/src/test/java/org/apache/maven/surefire/api/util/internal/ObjectUtilsTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.api.util.internal; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.api.util.internal; import org.junit.Test; @@ -28,12 +27,9 @@ /** * @since 3.0.0-M6 */ -public class ObjectUtilsTest -{ +public class ObjectUtilsTest { @Test - public void shouldSupportSecurityManager() - { - assertThat( ObjectUtils.isSecurityManagerSupported() ) - .isEqualTo( JAVA_RECENT.atMost( JAVA_17 ) ); + public void shouldSupportSecurityManager() { + assertThat(ObjectUtils.isSecurityManagerSupported()).isEqualTo(JAVA_RECENT.atMost(JAVA_17)); } } diff --git a/surefire-booter/pom.xml b/surefire-booter/pom.xml index 209c6c5867..89b0e71a23 100644 --- a/surefire-booter/pom.xml +++ b/surefire-booter/pom.xml @@ -76,10 +76,10 @@ build-test-classpath - generate-sources build-classpath + generate-sources test target/test-classpath/cp.txt @@ -90,6 +90,9 @@ org.jacoco jacoco-maven-plugin + + jacoco.agent + jacoco-agent @@ -98,27 +101,25 @@ - - jacoco.agent - maven-surefire-plugin - - - org.apache.maven.surefire - surefire-shadefire - 3.0.0-M7 - - ${jvm.args.tests} ${jacoco.agent} - true - true + true + true **/JUnit4SuiteTest.java + + + org.apache.maven.surefire + surefire-shadefire + 3.0.0-M7 + + + diff --git a/surefire-booter/src/main/java/org/apache/maven/surefire/booter/AbstractPathConfiguration.java b/surefire-booter/src/main/java/org/apache/maven/surefire/booter/AbstractPathConfiguration.java index bc07d21c37..d02a3ba7cb 100644 --- a/surefire-booter/src/main/java/org/apache/maven/surefire/booter/AbstractPathConfiguration.java +++ b/surefire-booter/src/main/java/org/apache/maven/surefire/booter/AbstractPathConfiguration.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.booter; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.booter; import javax.annotation.Nonnull; @@ -27,8 +26,7 @@ * @author Tibor Digana (tibor17) * @since 2.21.0.Jigsaw */ -public abstract class AbstractPathConfiguration -{ +public abstract class AbstractPathConfiguration { public static final String CHILD_DELEGATION = "childDelegation"; public static final String ENABLE_ASSERTIONS = "enableAssertions"; @@ -48,12 +46,10 @@ public abstract class AbstractPathConfiguration // todo: @deprecated because the IsolatedClassLoader is really isolated - no parent. private final boolean childDelegation; - protected AbstractPathConfiguration( @Nonnull Classpath surefireClasspathUrls, - boolean enableAssertions, boolean childDelegation ) - { - if ( isClassPathConfig() == isModularPathConfig() ) - { - throw new IllegalStateException( "modular path and class path should be exclusive" ); + protected AbstractPathConfiguration( + @Nonnull Classpath surefireClasspathUrls, boolean enableAssertions, boolean childDelegation) { + if (isClassPathConfig() == isModularPathConfig()) { + throw new IllegalStateException("modular path and class path should be exclusive"); } this.surefireClasspathUrls = surefireClasspathUrls; this.enableAssertions = enableAssertions; @@ -78,46 +74,36 @@ protected AbstractPathConfiguration( @Nonnull Classpath surefireClasspathUrls, protected abstract Classpath getInprocClasspath(); - public T toRealPath( Class type ) - { - if ( isClassPathConfig() && type == ClasspathConfiguration.class - || isModularPathConfig() && type == ModularClasspathConfiguration.class ) - { - return type.cast( this ); + public T toRealPath(Class type) { + if (isClassPathConfig() && type == ClasspathConfiguration.class + || isModularPathConfig() && type == ModularClasspathConfiguration.class) { + return type.cast(this); } - throw new IllegalStateException( "no target matched " + type ); + throw new IllegalStateException("no target matched " + type); } - public ClassLoader createMergedClassLoader() - throws SurefireExecutionException - { - return createMergedClassLoader( getInprocTestClasspath() ); + public ClassLoader createMergedClassLoader() throws SurefireExecutionException { + return createMergedClassLoader(getInprocTestClasspath()); } - public Classpath getProviderClasspath() - { + public Classpath getProviderClasspath() { return surefireClasspathUrls; } - public boolean isEnableAssertions() - { + public boolean isEnableAssertions() { return enableAssertions; } @Deprecated - public boolean isChildDelegation() - { + public boolean isChildDelegation() { return childDelegation; } - final Classpath getInprocTestClasspath() - { - return join( getInprocClasspath(), getTestClasspath() ); + final Classpath getInprocTestClasspath() { + return join(getInprocClasspath(), getTestClasspath()); } - final ClassLoader createMergedClassLoader( Classpath cp ) - throws SurefireExecutionException - { - return cp.createClassLoader( isChildDelegation(), isEnableAssertions(), "test" ); + final ClassLoader createMergedClassLoader(Classpath cp) throws SurefireExecutionException { + return cp.createClassLoader(isChildDelegation(), isEnableAssertions(), "test"); } } diff --git a/surefire-booter/src/main/java/org/apache/maven/surefire/booter/BooterConstants.java b/surefire-booter/src/main/java/org/apache/maven/surefire/booter/BooterConstants.java index dcf73615da..4fd1f693cb 100644 --- a/surefire-booter/src/main/java/org/apache/maven/surefire/booter/BooterConstants.java +++ b/surefire-booter/src/main/java/org/apache/maven/surefire/booter/BooterConstants.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.booter; /* @@ -19,17 +37,13 @@ * under the License. */ - /** * Constants used by the serializer/deserializer * * @author Kristian Rosenvold */ -public final class BooterConstants -{ - private BooterConstants() - { - } +public final class BooterConstants { + private BooterConstants() {} public static final String SPECIFIC_TEST_PROPERTY_PREFIX = "specificTest"; public static final String INCLUDES_PROPERTY_PREFIX = "includes"; diff --git a/surefire-booter/src/main/java/org/apache/maven/surefire/booter/BooterDeserializer.java b/surefire-booter/src/main/java/org/apache/maven/surefire/booter/BooterDeserializer.java index 2b365ad89a..8cf0e84bab 100644 --- a/surefire-booter/src/main/java/org/apache/maven/surefire/booter/BooterDeserializer.java +++ b/surefire-booter/src/main/java/org/apache/maven/surefire/booter/BooterDeserializer.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.booter; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,9 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.booter; + +import javax.annotation.Nonnull; import java.io.File; import java.io.IOException; @@ -33,11 +34,8 @@ import org.apache.maven.surefire.api.testset.TestListResolver; import org.apache.maven.surefire.api.testset.TestRequest; -// CHECKSTYLE_OFF: imports -import javax.annotation.Nonnull; - -import static org.apache.maven.surefire.booter.BooterConstants.*; import static org.apache.maven.surefire.api.cli.CommandLineOption.*; +import static org.apache.maven.surefire.booter.BooterConstants.*; /** * Knows how to serialize and deserialize the booter configuration. @@ -52,19 +50,15 @@ * @author Emmanuel Venisse * @author Kristian Rosenvold */ -public class BooterDeserializer -{ +public class BooterDeserializer { private final PropertiesWrapper properties; - public BooterDeserializer( InputStream inputStream ) - throws IOException - { - properties = SystemPropertyManager.loadProperties( inputStream ); + public BooterDeserializer(InputStream inputStream) throws IOException { + properties = SystemPropertyManager.loadProperties(inputStream); } - public int getForkNumber() - { - return properties.getIntProperty( FORK_NUMBER ); + public int getForkNumber() { + return properties.getIntProperty(FORK_NUMBER); } /** @@ -74,90 +68,93 @@ public int getForkNumber() * @return connection string (must not be null) */ @Nonnull - public String getConnectionString() - { - return properties.getProperty( FORK_NODE_CONNECTION_STRING ); + public String getConnectionString() { + return properties.getProperty(FORK_NODE_CONNECTION_STRING); } /** * @return PID of Maven process where plugin is executed; or null if PID could not be determined. */ - public String getPluginPid() - { - return properties.getProperty( PLUGIN_PID ); + public String getPluginPid() { + return properties.getProperty(PLUGIN_PID); } - public ProviderConfiguration deserialize() - { - final File reportsDirectory = new File( properties.getProperty( REPORTSDIRECTORY ) ); - final String testNgVersion = properties.getProperty( TESTARTIFACT_VERSION ); - final String testArtifactClassifier = properties.getProperty( TESTARTIFACT_CLASSIFIER ); + public ProviderConfiguration deserialize() { + final File reportsDirectory = new File(properties.getProperty(REPORTSDIRECTORY)); + final String testNgVersion = properties.getProperty(TESTARTIFACT_VERSION); + final String testArtifactClassifier = properties.getProperty(TESTARTIFACT_CLASSIFIER); - final TypeEncodedValue typeEncodedTestForFork = properties.getTypeEncodedValue( FORKTESTSET ); - final boolean preferTestsFromInStream = - properties.getBooleanProperty( FORKTESTSET_PREFER_TESTS_FROM_IN_STREAM ); + final TypeEncodedValue typeEncodedTestForFork = properties.getTypeEncodedValue(FORKTESTSET); + final boolean preferTestsFromInStream = properties.getBooleanProperty(FORKTESTSET_PREFER_TESTS_FROM_IN_STREAM); - final String requestedTest = properties.getProperty( REQUESTEDTEST ); - final File sourceDirectory = properties.getFileProperty( SOURCE_DIRECTORY ); + final String requestedTest = properties.getProperty(REQUESTEDTEST); + final File sourceDirectory = properties.getFileProperty(SOURCE_DIRECTORY); - final List excludes = properties.getStringList( EXCLUDES_PROPERTY_PREFIX ); - final List includes = properties.getStringList( INCLUDES_PROPERTY_PREFIX ); - final List specificTests = properties.getStringList( SPECIFIC_TEST_PROPERTY_PREFIX ); + final List excludes = properties.getStringList(EXCLUDES_PROPERTY_PREFIX); + final List includes = properties.getStringList(INCLUDES_PROPERTY_PREFIX); + final List specificTests = properties.getStringList(SPECIFIC_TEST_PROPERTY_PREFIX); - final List testSuiteXmlFiles = properties.getStringList( TEST_SUITE_XML_FILES ); - final File testClassesDirectory = properties.getFileProperty( TEST_CLASSES_DIRECTORY ); - final String runOrder = properties.getProperty( RUN_ORDER ); - final Long runOrderRandomSeed = properties.getLongProperty( RUN_ORDER_RANDOM_SEED ); - final String runStatisticsFile = properties.getProperty( RUN_STATISTICS_FILE ); + final List testSuiteXmlFiles = properties.getStringList(TEST_SUITE_XML_FILES); + final File testClassesDirectory = properties.getFileProperty(TEST_CLASSES_DIRECTORY); + final String runOrder = properties.getProperty(RUN_ORDER); + final Long runOrderRandomSeed = properties.getLongProperty(RUN_ORDER_RANDOM_SEED); + final String runStatisticsFile = properties.getProperty(RUN_STATISTICS_FILE); - final int rerunFailingTestsCount = properties.getIntProperty( RERUN_FAILING_TESTS_COUNT ); + final int rerunFailingTestsCount = properties.getIntProperty(RERUN_FAILING_TESTS_COUNT); DirectoryScannerParameters dirScannerParams = - new DirectoryScannerParameters( testClassesDirectory, includes, excludes, specificTests, runOrder ); + new DirectoryScannerParameters(testClassesDirectory, includes, excludes, specificTests, runOrder); - RunOrderParameters runOrderParameters - = new RunOrderParameters( runOrder, runStatisticsFile == null ? null : new File( runStatisticsFile ), - runOrderRandomSeed ); + RunOrderParameters runOrderParameters = new RunOrderParameters( + runOrder, runStatisticsFile == null ? null : new File(runStatisticsFile), runOrderRandomSeed); - TestArtifactInfo testNg = new TestArtifactInfo( testNgVersion, testArtifactClassifier ); - TestRequest testSuiteDefinition = - new TestRequest( testSuiteXmlFiles, sourceDirectory, new TestListResolver( requestedTest ), - rerunFailingTestsCount ); + TestArtifactInfo testNg = new TestArtifactInfo(testNgVersion, testArtifactClassifier); + TestRequest testSuiteDefinition = new TestRequest( + testSuiteXmlFiles, sourceDirectory, new TestListResolver(requestedTest), rerunFailingTestsCount); ReporterConfiguration reporterConfiguration = - new ReporterConfiguration( reportsDirectory, properties.getBooleanProperty( ISTRIMSTACKTRACE ) ); + new ReporterConfiguration(reportsDirectory, properties.getBooleanProperty(ISTRIMSTACKTRACE)); - Collection cli = properties.getStringList( MAIN_CLI_OPTIONS ); + Collection cli = properties.getStringList(MAIN_CLI_OPTIONS); - int failFastCount = properties.getIntProperty( FAIL_FAST_COUNT ); + int failFastCount = properties.getIntProperty(FAIL_FAST_COUNT); - Shutdown shutdown = Shutdown.valueOf( properties.getProperty( SHUTDOWN ) ); + Shutdown shutdown = Shutdown.valueOf(properties.getProperty(SHUTDOWN)); - String systemExitTimeoutAsString = properties.getProperty( SYSTEM_EXIT_TIMEOUT ); + String systemExitTimeoutAsString = properties.getProperty(SYSTEM_EXIT_TIMEOUT); Integer systemExitTimeout = - systemExitTimeoutAsString == null ? null : Integer.valueOf( systemExitTimeoutAsString ); - - return new ProviderConfiguration( dirScannerParams, runOrderParameters, reporterConfiguration, testNg, - testSuiteDefinition, properties.getProperties(), typeEncodedTestForFork, - preferTestsFromInStream, fromStrings( cli ), failFastCount, shutdown, - systemExitTimeout ); + systemExitTimeoutAsString == null ? null : Integer.valueOf(systemExitTimeoutAsString); + + return new ProviderConfiguration( + dirScannerParams, + runOrderParameters, + reporterConfiguration, + testNg, + testSuiteDefinition, + properties.getProperties(), + typeEncodedTestForFork, + preferTestsFromInStream, + fromStrings(cli), + failFastCount, + shutdown, + systemExitTimeout); } - public StartupConfiguration getStartupConfiguration() - { - boolean useSystemClassLoader = properties.getBooleanProperty( USESYSTEMCLASSLOADER ); - boolean useManifestOnlyJar = properties.getBooleanProperty( USEMANIFESTONLYJAR ); - String providerConfiguration = properties.getProperty( PROVIDER_CONFIGURATION ); + public StartupConfiguration getStartupConfiguration() { + boolean useSystemClassLoader = properties.getBooleanProperty(USESYSTEMCLASSLOADER); + boolean useManifestOnlyJar = properties.getBooleanProperty(USEMANIFESTONLYJAR); + String providerConfiguration = properties.getProperty(PROVIDER_CONFIGURATION); ClassLoaderConfiguration classLoaderConfiguration = - new ClassLoaderConfiguration( useSystemClassLoader, useManifestOnlyJar ); + new ClassLoaderConfiguration(useSystemClassLoader, useManifestOnlyJar); - ClasspathConfiguration classpathConfiguration = new ClasspathConfiguration( properties ); + ClasspathConfiguration classpathConfiguration = new ClasspathConfiguration(properties); - String processChecker = properties.getProperty( PROCESS_CHECKER ); - ProcessCheckerType processCheckerType = ProcessCheckerType.toEnum( processChecker ); + String processChecker = properties.getProperty(PROCESS_CHECKER); + ProcessCheckerType processCheckerType = ProcessCheckerType.toEnum(processChecker); - return StartupConfiguration.inForkedVm( providerConfiguration, classpathConfiguration, - classLoaderConfiguration, processCheckerType ); + return StartupConfiguration.inForkedVm( + providerConfiguration, classpathConfiguration, + classLoaderConfiguration, processCheckerType); } } diff --git a/surefire-booter/src/main/java/org/apache/maven/surefire/booter/ClassLoaderConfiguration.java b/surefire-booter/src/main/java/org/apache/maven/surefire/booter/ClassLoaderConfiguration.java index 12262bb5df..540c57501b 100644 --- a/surefire-booter/src/main/java/org/apache/maven/surefire/booter/ClassLoaderConfiguration.java +++ b/surefire-booter/src/main/java/org/apache/maven/surefire/booter/ClassLoaderConfiguration.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.booter; /* @@ -25,31 +43,26 @@ * @author Brett Porter * @author Kenney Westerhof */ -public class ClassLoaderConfiguration -{ +public class ClassLoaderConfiguration { private final boolean useSystemClassLoader; private final boolean useManifestOnlyJar; - public ClassLoaderConfiguration( boolean useSystemClassLoader, boolean useManifestOnlyJar ) - { + public ClassLoaderConfiguration(boolean useSystemClassLoader, boolean useManifestOnlyJar) { this.useSystemClassLoader = useSystemClassLoader; this.useManifestOnlyJar = useManifestOnlyJar; } - public boolean isUseSystemClassLoader() - { + public boolean isUseSystemClassLoader() { return useSystemClassLoader; } - public boolean isUseManifestOnlyJar() - { + public boolean isUseManifestOnlyJar() { return useManifestOnlyJar; } - public boolean isManifestOnlyJarRequestedAndUsable() - { + public boolean isManifestOnlyJarRequestedAndUsable() { return isUseSystemClassLoader() && useManifestOnlyJar; } } diff --git a/surefire-booter/src/main/java/org/apache/maven/surefire/booter/Classpath.java b/surefire-booter/src/main/java/org/apache/maven/surefire/booter/Classpath.java index ef5265c63e..e340903ddd 100644 --- a/surefire-booter/src/main/java/org/apache/maven/surefire/booter/Classpath.java +++ b/surefire-booter/src/main/java/org/apache/maven/surefire/booter/Classpath.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.booter; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,8 +16,10 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.booter; import javax.annotation.Nonnull; + import java.io.File; import java.net.MalformedURLException; import java.util.ArrayList; @@ -40,165 +40,131 @@ * * @author Kristian Rosenvold */ -public final class Classpath implements Iterable, Cloneable -{ +public final class Classpath implements Iterable, Cloneable { private final List unmodifiableElements; - public static Classpath join( Classpath firstClasspath, Classpath secondClasspath ) - { - LinkedHashSet accumulated = new LinkedHashSet<>(); - if ( firstClasspath != null ) - { - firstClasspath.addTo( accumulated ); + public static Classpath join(Classpath firstClasspath, Classpath secondClasspath) { + LinkedHashSet accumulated = new LinkedHashSet<>(); + if (firstClasspath != null) { + firstClasspath.addTo(accumulated); } - if ( secondClasspath != null ) - { - secondClasspath.addTo( accumulated ); + if (secondClasspath != null) { + secondClasspath.addTo(accumulated); } - return new Classpath( accumulated ); + return new Classpath(accumulated); } - private void addTo( @Nonnull Collection c ) - { - c.addAll( unmodifiableElements ); + private void addTo(@Nonnull Collection c) { + c.addAll(unmodifiableElements); } - private Classpath() - { + private Classpath() { unmodifiableElements = Collections.emptyList(); } - public Classpath( @Nonnull Classpath other, @Nonnull String additionalElement ) - { - ArrayList elems = new ArrayList<>( other.unmodifiableElements ); - elems.add( additionalElement ); - unmodifiableElements = Collections.unmodifiableList( elems ); + public Classpath(@Nonnull Classpath other, @Nonnull String additionalElement) { + ArrayList elems = new ArrayList<>(other.unmodifiableElements); + elems.add(additionalElement); + unmodifiableElements = Collections.unmodifiableList(elems); } - public Classpath( @Nonnull Collection elements ) - { - List newCp = new ArrayList<>( elements.size() ); - for ( String element : elements ) - { + public Classpath(@Nonnull Collection elements) { + List newCp = new ArrayList<>(elements.size()); + for (String element : elements) { element = element.trim(); - if ( !element.isEmpty() ) - { - newCp.add( element ); + if (!element.isEmpty()) { + newCp.add(element); } } - unmodifiableElements = Collections.unmodifiableList( newCp ); + unmodifiableElements = Collections.unmodifiableList(newCp); } - public static Classpath emptyClasspath() - { + public static Classpath emptyClasspath() { return new Classpath(); } - public Classpath addClassPathElementUrl( String path ) - { - if ( path == null ) - { - throw new IllegalArgumentException( "Null is not a valid class path element url." ); + public Classpath addClassPathElementUrl(String path) { + if (path == null) { + throw new IllegalArgumentException("Null is not a valid class path element url."); } - return unmodifiableElements.contains( path ) ? this : new Classpath( this, path ); + return unmodifiableElements.contains(path) ? this : new Classpath(this, path); } @Nonnull - public List getClassPath() - { + public List getClassPath() { return unmodifiableElements; } - public void writeToSystemProperty( @Nonnull String propertyName ) - { + public void writeToSystemProperty(@Nonnull String propertyName) { StringBuilder sb = new StringBuilder(); - for ( String element : unmodifiableElements ) - { - sb.append( element ) - .append( pathSeparatorChar ); + for (String element : unmodifiableElements) { + sb.append(element).append(pathSeparatorChar); } - System.setProperty( propertyName, sb.toString() ); + System.setProperty(propertyName, sb.toString()); } @Override - public boolean equals( Object o ) - { - if ( this == o ) - { + public boolean equals(Object o) { + if (this == o) { return true; } - if ( o == null || getClass() != o.getClass() ) - { + if (o == null || getClass() != o.getClass()) { return false; } Classpath classpath = (Classpath) o; - return unmodifiableElements.equals( classpath.unmodifiableElements ); + return unmodifiableElements.equals(classpath.unmodifiableElements); } - public ClassLoader createClassLoader( boolean childDelegation, boolean enableAssertions, @Nonnull String roleName ) - throws SurefireExecutionException - { - try - { + public ClassLoader createClassLoader(boolean childDelegation, boolean enableAssertions, @Nonnull String roleName) + throws SurefireExecutionException { + try { ClassLoader parent = SystemUtils.platformClassLoader(); - IsolatedClassLoader classLoader = new IsolatedClassLoader( parent, childDelegation, roleName ); - for ( String classPathElement : unmodifiableElements ) - { - classLoader.addURL( new File( classPathElement ).toURI().toURL() ); + IsolatedClassLoader classLoader = new IsolatedClassLoader(parent, childDelegation, roleName); + for (String classPathElement : unmodifiableElements) { + classLoader.addURL(new File(classPathElement).toURI().toURL()); } - if ( parent != null ) - { - parent.setDefaultAssertionStatus( enableAssertions ); + if (parent != null) { + parent.setDefaultAssertionStatus(enableAssertions); } - classLoader.setDefaultAssertionStatus( enableAssertions ); + classLoader.setDefaultAssertionStatus(enableAssertions); return classLoader; - } - catch ( MalformedURLException e ) - { - throw new SurefireExecutionException( "When creating classloader", e ); + } catch (MalformedURLException e) { + throw new SurefireExecutionException("When creating classloader", e); } } @Override - public int hashCode() - { + public int hashCode() { return unmodifiableElements.hashCode(); } - public String getLogMessage( @Nonnull String descriptor ) - { - StringBuilder result = new StringBuilder( descriptor ); - for ( String element : unmodifiableElements ) - { - result.append( " " ) - .append( element ); + public String getLogMessage(@Nonnull String descriptor) { + StringBuilder result = new StringBuilder(descriptor); + for (String element : unmodifiableElements) { + result.append(" ").append(element); } return result.toString(); } - public String getCompactLogMessage( @Nonnull String descriptor ) - { - StringBuilder result = new StringBuilder( descriptor ); - for ( String element : unmodifiableElements ) - { - result.append( " " ); - int pos = element.lastIndexOf( File.separatorChar ); - result.append( pos == -1 ? element : element.substring( pos + 1 ) ); + public String getCompactLogMessage(@Nonnull String descriptor) { + StringBuilder result = new StringBuilder(descriptor); + for (String element : unmodifiableElements) { + result.append(" "); + int pos = element.lastIndexOf(File.separatorChar); + result.append(pos == -1 ? element : element.substring(pos + 1)); } return result.toString(); } @Override - public Iterator iterator() - { + public Iterator iterator() { return unmodifiableElements.iterator(); } @Override - public Classpath clone() - { - return new Classpath( unmodifiableElements ); + public Classpath clone() { + return new Classpath(unmodifiableElements); } } diff --git a/surefire-booter/src/main/java/org/apache/maven/surefire/booter/ClasspathConfiguration.java b/surefire-booter/src/main/java/org/apache/maven/surefire/booter/ClasspathConfiguration.java index 21cb82c17a..069a08d0dd 100644 --- a/surefire-booter/src/main/java/org/apache/maven/surefire/booter/ClasspathConfiguration.java +++ b/surefire-booter/src/main/java/org/apache/maven/surefire/booter/ClasspathConfiguration.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.booter; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.booter; import javax.annotation.Nonnull; @@ -31,8 +30,7 @@ * @author Emmanuel Venisse * @author Kristian Rosenvold */ -public class ClasspathConfiguration extends AbstractPathConfiguration -{ +public class ClasspathConfiguration extends AbstractPathConfiguration { private final Classpath testClasspathUrls; /** @@ -40,52 +38,51 @@ public class ClasspathConfiguration extends AbstractPathConfiguration */ private final Classpath inprocClasspath; - public ClasspathConfiguration( boolean enableAssertions, boolean childDelegation ) - { - this( emptyClasspath(), emptyClasspath(), emptyClasspath(), enableAssertions, childDelegation ); + public ClasspathConfiguration(boolean enableAssertions, boolean childDelegation) { + this(emptyClasspath(), emptyClasspath(), emptyClasspath(), enableAssertions, childDelegation); } - ClasspathConfiguration( @Nonnull PropertiesWrapper properties ) - { - this( properties.getClasspath( CLASSPATH ), properties.getClasspath( SUREFIRE_CLASSPATH ), emptyClasspath(), - properties.getBooleanProperty( ENABLE_ASSERTIONS ), properties.getBooleanProperty( CHILD_DELEGATION ) ); + ClasspathConfiguration(@Nonnull PropertiesWrapper properties) { + this( + properties.getClasspath(CLASSPATH), + properties.getClasspath(SUREFIRE_CLASSPATH), + emptyClasspath(), + properties.getBooleanProperty(ENABLE_ASSERTIONS), + properties.getBooleanProperty(CHILD_DELEGATION)); } - public ClasspathConfiguration( @Nonnull Classpath testClasspathUrls, @Nonnull Classpath surefireClassPathUrls, - @Nonnull Classpath inprocClasspath, boolean enableAssertions, - boolean childDelegation ) - { - super( surefireClassPathUrls, enableAssertions, childDelegation ); + public ClasspathConfiguration( + @Nonnull Classpath testClasspathUrls, + @Nonnull Classpath surefireClassPathUrls, + @Nonnull Classpath inprocClasspath, + boolean enableAssertions, + boolean childDelegation) { + super(surefireClassPathUrls, enableAssertions, childDelegation); this.testClasspathUrls = testClasspathUrls; this.inprocClasspath = inprocClasspath; } @Override - protected Classpath getInprocClasspath() - { + protected Classpath getInprocClasspath() { return inprocClasspath; } - public Classpath getTestClasspath() - { + public Classpath getTestClasspath() { return testClasspathUrls; } @Override - public final boolean isModularPathConfig() - { + public final boolean isModularPathConfig() { return !isClassPathConfig(); } @Override - public final boolean isClassPathConfig() - { + public final boolean isClassPathConfig() { return true; } - public void trickClassPathWhenManifestOnlyClasspath() - { - System.setProperty( "surefire.real.class.path", System.getProperty( "java.class.path" ) ); - getTestClasspath().writeToSystemProperty( "java.class.path" ); + public void trickClassPathWhenManifestOnlyClasspath() { + System.setProperty("surefire.real.class.path", System.getProperty("java.class.path")); + getTestClasspath().writeToSystemProperty("java.class.path"); } } diff --git a/surefire-booter/src/main/java/org/apache/maven/surefire/booter/CommandReader.java b/surefire-booter/src/main/java/org/apache/maven/surefire/booter/CommandReader.java index 609327ccfd..b1dba3bb51 100644 --- a/surefire-booter/src/main/java/org/apache/maven/surefire/booter/CommandReader.java +++ b/surefire-booter/src/main/java/org/apache/maven/surefire/booter/CommandReader.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.booter; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,18 +16,7 @@ * specific language governing permissions and limitations * under the License. */ - -import org.apache.maven.plugin.surefire.log.api.ConsoleLogger; -import org.apache.maven.surefire.api.booter.BiProperty; -import org.apache.maven.surefire.api.booter.Command; -import org.apache.maven.surefire.api.booter.DumpErrorSingleton; -import org.apache.maven.surefire.api.booter.MasterProcessChannelDecoder; -import org.apache.maven.surefire.api.booter.MasterProcessChannelEncoder; -import org.apache.maven.surefire.api.booter.MasterProcessCommand; -import org.apache.maven.surefire.api.booter.Shutdown; -import org.apache.maven.surefire.api.provider.CommandChainReader; -import org.apache.maven.surefire.api.provider.CommandListener; -import org.apache.maven.surefire.api.testset.TestSetFailedException; +package org.apache.maven.surefire.booter; import java.io.EOFException; import java.io.IOException; @@ -44,6 +31,18 @@ import java.util.concurrent.Semaphore; import java.util.concurrent.atomic.AtomicReference; +import org.apache.maven.plugin.surefire.log.api.ConsoleLogger; +import org.apache.maven.surefire.api.booter.BiProperty; +import org.apache.maven.surefire.api.booter.Command; +import org.apache.maven.surefire.api.booter.DumpErrorSingleton; +import org.apache.maven.surefire.api.booter.MasterProcessChannelDecoder; +import org.apache.maven.surefire.api.booter.MasterProcessChannelEncoder; +import org.apache.maven.surefire.api.booter.MasterProcessCommand; +import org.apache.maven.surefire.api.booter.Shutdown; +import org.apache.maven.surefire.api.provider.CommandChainReader; +import org.apache.maven.surefire.api.provider.CommandListener; +import org.apache.maven.surefire.api.testset.TestSetFailedException; + import static java.lang.StrictMath.max; import static java.lang.Thread.State.NEW; import static java.lang.Thread.State.RUNNABLE; @@ -54,9 +53,9 @@ import static org.apache.maven.surefire.api.booter.MasterProcessCommand.NOOP; import static org.apache.maven.surefire.api.booter.MasterProcessCommand.SHUTDOWN; import static org.apache.maven.surefire.api.booter.MasterProcessCommand.SKIP_SINCE_NEXT_TEST; +import static org.apache.maven.surefire.api.util.internal.DaemonThreadFactory.newDaemonThread; import static org.apache.maven.surefire.shared.utils.StringUtils.isBlank; import static org.apache.maven.surefire.shared.utils.StringUtils.isNotBlank; -import static org.apache.maven.surefire.api.util.internal.DaemonThreadFactory.newDaemonThread; /** * Reader of commands coming from plugin(master) process. @@ -64,19 +63,18 @@ * @author Tibor Digana (tibor17) * @since 2.19 */ -public final class CommandReader implements CommandChainReader -{ +public final class CommandReader implements CommandChainReader { private static final String LAST_TEST_SYMBOL = ""; private final Queue> listeners = new ConcurrentLinkedQueue<>(); - private final Thread commandThread = newDaemonThread( new CommandRunnable(), "surefire-forkedjvm-command-thread" ); + private final Thread commandThread = newDaemonThread(new CommandRunnable(), "surefire-forkedjvm-command-thread"); - private final AtomicReference state = new AtomicReference<>( NEW ); + private final AtomicReference state = new AtomicReference<>(NEW); - private final CountDownLatch startMonitor = new CountDownLatch( 1 ); + private final CountDownLatch startMonitor = new CountDownLatch(1); - private final Semaphore nextCommandNotifier = new Semaphore( 0 ); + private final Semaphore nextCommandNotifier = new Semaphore(0); private final CopyOnWriteArrayList testClasses = new CopyOnWriteArrayList<>(); @@ -88,72 +86,57 @@ public final class CommandReader implements CommandChainReader private int iteratedCount; - public CommandReader( MasterProcessChannelDecoder decoder, Shutdown shutdown, ConsoleLogger logger ) - { - this.decoder = requireNonNull( decoder, "null decoder" ); - this.shutdown = requireNonNull( shutdown, "null Shutdown config" ); - this.logger = requireNonNull( logger, "null logger" ); - state.set( RUNNABLE ); + public CommandReader(MasterProcessChannelDecoder decoder, Shutdown shutdown, ConsoleLogger logger) { + this.decoder = requireNonNull(decoder, "null decoder"); + this.shutdown = requireNonNull(shutdown, "null Shutdown config"); + this.logger = requireNonNull(logger, "null logger"); + state.set(RUNNABLE); commandThread.start(); } @Override - public boolean awaitStarted() - throws TestSetFailedException - { - if ( state.get() == RUNNABLE ) - { - try - { + public boolean awaitStarted() throws TestSetFailedException { + if (state.get() == RUNNABLE) { + try { startMonitor.await(); return true; + } catch (InterruptedException e) { + DumpErrorSingleton.getSingleton().dumpException(e); + throw new TestSetFailedException(e.getLocalizedMessage()); } - catch ( InterruptedException e ) - { - DumpErrorSingleton.getSingleton().dumpException( e ); - throw new TestSetFailedException( e.getLocalizedMessage() ); - } - } - else - { + } else { return false; } } @Override - public void addSkipNextTestsListener( CommandListener listener ) - { - addListener( SKIP_SINCE_NEXT_TEST, listener ); + public void addSkipNextTestsListener(CommandListener listener) { + addListener(SKIP_SINCE_NEXT_TEST, listener); } @Override - public void addShutdownListener( CommandListener listener ) - { - addListener( SHUTDOWN, listener ); + public void addShutdownListener(CommandListener listener) { + addListener(SHUTDOWN, listener); } - public void addNoopListener( CommandListener listener ) - { - addListener( NOOP, listener ); + public void addNoopListener(CommandListener listener) { + addListener(NOOP, listener); } - public void addByeAckListener( CommandListener listener ) - { - addListener( BYE_ACK, listener ); + public void addByeAckListener(CommandListener listener) { + addListener(BYE_ACK, listener); } - private void addListener( MasterProcessCommand cmd, CommandListener listener ) - { - listeners.add( new BiProperty<>( cmd, listener ) ); + private void addListener(MasterProcessCommand cmd, CommandListener listener) { + listeners.add(new BiProperty<>(cmd, listener)); } /** * @return test classes which have been retrieved by * {@link CommandReader#getIterableClasses(MasterProcessChannelEncoder)}. */ - Iterator iterated() - { - return testClasses.subList( 0, iteratedCount ).iterator(); + Iterator iterated() { + return testClasses.subList(0, iteratedCount).iterator(); } /** @@ -163,32 +146,27 @@ Iterator iterated() * @param eventChannel original stream in current JVM process * @return Iterator with test classes lazily loaded as commands from the main process */ - Iterable getIterableClasses( MasterProcessChannelEncoder eventChannel ) - { - return new ClassesIterable( eventChannel ); + Iterable getIterableClasses(MasterProcessChannelEncoder eventChannel) { + return new ClassesIterable(eventChannel); } - public void stop() - { - if ( !isStopped() ) - { - state.set( TERMINATED ); + public void stop() { + if (!isStopped()) { + state.set(TERMINATED); makeQueueFull(); listeners.clear(); commandThread.interrupt(); } } - private boolean isStopped() - { + private boolean isStopped() { return state.get() == TERMINATED; } /** * @return {@code true} if {@link #LAST_TEST_SYMBOL} found at the last index in {@link #testClasses}. */ - private boolean isQueueFull() - { + private boolean isQueueFull() { // The problem with COWAL is that such collection doe not have operation getLast, however it has get(int) // and we need both atomic. // @@ -197,245 +175,196 @@ private boolean isQueueFull() // The insert operation is concurrent with this method. // Prerequisite: The strings are added but never removed and the method insertToQueue() does not // allow adding a string after LAST_TEST_SYMBOL. - int searchFrom = max( 0, testClasses.size() - 1 ); - return testClasses.indexOf( LAST_TEST_SYMBOL, searchFrom ) != -1; + int searchFrom = max(0, testClasses.size() - 1); + return testClasses.indexOf(LAST_TEST_SYMBOL, searchFrom) != -1; } - private void makeQueueFull() - { - testClasses.addIfAbsent( LAST_TEST_SYMBOL ); + private void makeQueueFull() { + testClasses.addIfAbsent(LAST_TEST_SYMBOL); } - private boolean insertToQueue( String test ) - { - return isNotBlank( test ) && !isQueueFull() && testClasses.add( test ); + private boolean insertToQueue(String test) { + return isNotBlank(test) && !isQueueFull() && testClasses.add(test); } - private final class ClassesIterable - implements Iterable - { + private final class ClassesIterable implements Iterable { private final MasterProcessChannelEncoder eventChannel; - ClassesIterable( MasterProcessChannelEncoder eventChannel ) - { + ClassesIterable(MasterProcessChannelEncoder eventChannel) { this.eventChannel = eventChannel; } @Override - public Iterator iterator() - { - return new ClassesIterator( eventChannel ); + public Iterator iterator() { + return new ClassesIterator(eventChannel); } } - private final class ClassesIterator - implements Iterator - { + private final class ClassesIterator implements Iterator { private final MasterProcessChannelEncoder eventChannel; private String clazz; private int nextQueueIndex; - private ClassesIterator( MasterProcessChannelEncoder eventChannel ) - { + private ClassesIterator(MasterProcessChannelEncoder eventChannel) { this.eventChannel = eventChannel; } @Override - public boolean hasNext() - { + public boolean hasNext() { popUnread(); - return isNotBlank( clazz ); + return isNotBlank(clazz); } @Override - public String next() - { + public String next() { popUnread(); - try - { - if ( isBlank( clazz ) ) - { - throw new NoSuchElementException( CommandReader.this.isStopped() ? "stream was stopped" : "" ); - } - else - { + try { + if (isBlank(clazz)) { + throw new NoSuchElementException(CommandReader.this.isStopped() ? "stream was stopped" : ""); + } else { return clazz; } - } - finally - { + } finally { clazz = null; } } @Override - public void remove() - { + public void remove() { throw new UnsupportedOperationException(); } - private void popUnread() - { - if ( shouldFinish() ) - { + private void popUnread() { + if (shouldFinish()) { clazz = null; return; } - if ( isBlank( clazz ) ) - { + if (isBlank(clazz)) { requestNextTest(); CommandReader.this.awaitNextTest(); - if ( shouldFinish() ) - { + if (shouldFinish()) { clazz = null; return; } - clazz = CommandReader.this.testClasses.get( nextQueueIndex++ ); + clazz = CommandReader.this.testClasses.get(nextQueueIndex++); CommandReader.this.iteratedCount = nextQueueIndex; } - if ( CommandReader.this.isStopped() ) - { + if (CommandReader.this.isStopped()) { clazz = null; } } - private void requestNextTest() - { + private void requestNextTest() { eventChannel.acquireNextTest(); } - private boolean shouldFinish() - { - boolean wasLastTestRead = isEndSymbolAt( nextQueueIndex ); + private boolean shouldFinish() { + boolean wasLastTestRead = isEndSymbolAt(nextQueueIndex); return CommandReader.this.isStopped() || wasLastTestRead; } - private boolean isEndSymbolAt( int index ) - { + private boolean isEndSymbolAt(int index) { return CommandReader.this.isQueueFull() && 1 + index == CommandReader.this.testClasses.size(); } } - private void awaitNextTest() - { + private void awaitNextTest() { nextCommandNotifier.acquireUninterruptibly(); } - private void wakeupIterator() - { + private void wakeupIterator() { nextCommandNotifier.release(); } - private final class CommandRunnable - implements Runnable - { + private final class CommandRunnable implements Runnable { @Override - public void run() - { + public void run() { CommandReader.this.startMonitor.countDown(); boolean isTestSetFinished = false; - try ( MasterProcessChannelDecoder commandReader = CommandReader.this.decoder ) - { - while ( CommandReader.this.state.get() == RUNNABLE ) - { + try (MasterProcessChannelDecoder commandReader = CommandReader.this.decoder) { + while (CommandReader.this.state.get() == RUNNABLE) { Command command = commandReader.decode(); - switch ( command.getCommandType() ) - { + switch (command.getCommandType()) { case RUN_CLASS: String test = command.getData(); - boolean inserted = CommandReader.this.insertToQueue( test ); - if ( inserted ) - { + boolean inserted = CommandReader.this.insertToQueue(test); + if (inserted) { CommandReader.this.wakeupIterator(); - callListeners( command ); + callListeners(command); } break; case TEST_SET_FINISHED: CommandReader.this.makeQueueFull(); isTestSetFinished = true; CommandReader.this.wakeupIterator(); - callListeners( command ); + callListeners(command); break; case SHUTDOWN: CommandReader.this.makeQueueFull(); CommandReader.this.wakeupIterator(); - callListeners( command ); - break; + callListeners(command); + break; case BYE_ACK: - callListeners( command ); + callListeners(command); // After SHUTDOWN no more commands can come. // Hence, do NOT go back to blocking in I/O. - CommandReader.this.state.set( TERMINATED ); + CommandReader.this.state.set(TERMINATED); break; default: - callListeners( command ); + callListeners(command); break; } } - } - catch ( EOFException | ClosedChannelException e ) - { - CommandReader.this.state.set( TERMINATED ); - if ( !isTestSetFinished ) - { + } catch (EOFException | ClosedChannelException e) { + CommandReader.this.state.set(TERMINATED); + if (!isTestSetFinished) { String msg = "TestSet has not finished before stream error has appeared >> " - + "initializing exit by non-null configuration: " - + CommandReader.this.shutdown; - DumpErrorSingleton.getSingleton().dumpStreamException( e, msg ); + + "initializing exit by non-null configuration: " + + CommandReader.this.shutdown; + DumpErrorSingleton.getSingleton().dumpStreamException(e, msg); exitByConfiguration(); // does not go to finally for non-default config: Shutdown.EXIT or Shutdown.KILL } - } - catch ( IOException e ) - { - CommandReader.this.state.set( TERMINATED ); + } catch (IOException e) { + CommandReader.this.state.set(TERMINATED); // If #stop() method is called, reader thread is interrupted // and exception is InterruptedIOException or its cause is InterruptedException. - if ( !( e instanceof InterruptedIOException || e.getCause() instanceof InterruptedException ) ) - { + if (!(e instanceof InterruptedIOException || e.getCause() instanceof InterruptedException)) { String msg = "[SUREFIRE] std/in stream corrupted"; - DumpErrorSingleton.getSingleton().dumpStreamException( e, msg ); - CommandReader.this.logger.error( msg, e ); + DumpErrorSingleton.getSingleton().dumpStreamException(e, msg); + CommandReader.this.logger.error(msg, e); } - } - finally - { + } finally { // ensure fail-safe iterator as well as safe to finish in for-each loop using ClassesIterator - if ( !isTestSetFinished ) - { + if (!isTestSetFinished) { CommandReader.this.makeQueueFull(); } CommandReader.this.wakeupIterator(); } } - private void callListeners( Command cmd ) - { + private void callListeners(Command cmd) { MasterProcessCommand expectedCommandType = cmd.getCommandType(); - for ( BiProperty listenerWrapper : CommandReader.this.listeners ) - { + for (BiProperty listenerWrapper : CommandReader.this.listeners) { MasterProcessCommand commandType = listenerWrapper.getP1(); CommandListener listener = listenerWrapper.getP2(); - if ( commandType == null || commandType == expectedCommandType ) - { - listener.update( cmd ); + if (commandType == null || commandType == expectedCommandType) { + listener.update(cmd); } } } - private void exitByConfiguration() - { + private void exitByConfiguration() { Shutdown shutdown = CommandReader.this.shutdown; // won't read inconsistent changes through the stack - if ( shutdown != null ) - { + if (shutdown != null) { CommandReader.this.makeQueueFull(); CommandReader.this.wakeupIterator(); - callListeners( toShutdown( shutdown ) ); + callListeners(toShutdown(shutdown)); } } } diff --git a/surefire-booter/src/main/java/org/apache/maven/surefire/booter/ForkedBooter.java b/surefire-booter/src/main/java/org/apache/maven/surefire/booter/ForkedBooter.java index bd44d55c4b..1bcdc8b09f 100644 --- a/surefire-booter/src/main/java/org/apache/maven/surefire/booter/ForkedBooter.java +++ b/surefire-booter/src/main/java/org/apache/maven/surefire/booter/ForkedBooter.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.booter; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,24 +16,7 @@ * specific language governing permissions and limitations * under the License. */ - -import org.apache.maven.plugin.surefire.log.api.ConsoleLogger; -import org.apache.maven.surefire.api.booter.BaseProviderFactory; -import org.apache.maven.surefire.api.booter.Command; -import org.apache.maven.surefire.api.booter.DumpErrorSingleton; -import org.apache.maven.surefire.api.booter.ForkingReporterFactory; -import org.apache.maven.surefire.api.booter.MasterProcessChannelDecoder; -import org.apache.maven.surefire.api.booter.MasterProcessChannelEncoder; -import org.apache.maven.surefire.api.booter.Shutdown; -import org.apache.maven.surefire.api.fork.ForkNodeArguments; -import org.apache.maven.surefire.api.provider.CommandListener; -import org.apache.maven.surefire.api.provider.ProviderParameters; -import org.apache.maven.surefire.api.provider.SurefireProvider; -import org.apache.maven.surefire.api.testset.TestSetFailedException; -import org.apache.maven.surefire.booter.spi.LegacyMasterProcessChannelProcessorFactory; -import org.apache.maven.surefire.booter.spi.SurefireMasterProcessChannelProcessorFactory; -import org.apache.maven.surefire.shared.utils.cli.ShutdownHookUtils; -import org.apache.maven.surefire.spi.MasterProcessChannelProcessorFactory; +package org.apache.maven.surefire.booter; import java.io.File; import java.io.FileInputStream; @@ -55,6 +36,24 @@ import java.util.concurrent.ThreadFactory; import java.util.concurrent.atomic.AtomicBoolean; +import org.apache.maven.plugin.surefire.log.api.ConsoleLogger; +import org.apache.maven.surefire.api.booter.BaseProviderFactory; +import org.apache.maven.surefire.api.booter.Command; +import org.apache.maven.surefire.api.booter.DumpErrorSingleton; +import org.apache.maven.surefire.api.booter.ForkingReporterFactory; +import org.apache.maven.surefire.api.booter.MasterProcessChannelDecoder; +import org.apache.maven.surefire.api.booter.MasterProcessChannelEncoder; +import org.apache.maven.surefire.api.booter.Shutdown; +import org.apache.maven.surefire.api.fork.ForkNodeArguments; +import org.apache.maven.surefire.api.provider.CommandListener; +import org.apache.maven.surefire.api.provider.ProviderParameters; +import org.apache.maven.surefire.api.provider.SurefireProvider; +import org.apache.maven.surefire.api.testset.TestSetFailedException; +import org.apache.maven.surefire.booter.spi.LegacyMasterProcessChannelProcessorFactory; +import org.apache.maven.surefire.booter.spi.SurefireMasterProcessChannelProcessorFactory; +import org.apache.maven.surefire.shared.utils.cli.ShutdownHookUtils; +import org.apache.maven.surefire.spi.MasterProcessChannelProcessorFactory; + import static java.lang.Thread.currentThread; import static java.util.ServiceLoader.load; import static java.util.concurrent.TimeUnit.SECONDS; @@ -77,17 +76,16 @@ * @author Emmanuel Venisse * @author Kristian Rosenvold */ -public final class ForkedBooter -{ +public final class ForkedBooter { private static final long DEFAULT_SYSTEM_EXIT_TIMEOUT_IN_SECONDS = 30L; private static final long PING_TIMEOUT_IN_SECONDS = 30L; private static final String LAST_DITCH_SHUTDOWN_THREAD = "surefire-forkedjvm-last-ditch-daemon-shutdown-thread-"; private static final String PING_THREAD = "surefire-forkedjvm-ping-"; private static final String PROCESS_CHECKER_THREAD = "surefire-process-checker"; private static final String PROCESS_PIPES_ERROR = - "The channel (std/out or TCP/IP) failed to send a stream from this subprocess."; + "The channel (std/out or TCP/IP) failed to send a stream from this subprocess."; - private final Semaphore exitBarrier = new Semaphore( 0 ); + private final Semaphore exitBarrier = new Semaphore(0); private volatile MasterProcessChannelEncoder eventChannel; private volatile ConsoleLogger logger; @@ -102,88 +100,78 @@ public final class ForkedBooter private StartupConfiguration startupConfiguration; private Object testSet; - private void setupBooter( String tmpDir, String dumpFileName, String surefirePropsFileName, - String effectiveSystemPropertiesFileName ) - throws IOException - { + private void setupBooter( + String tmpDir, String dumpFileName, String surefirePropsFileName, String effectiveSystemPropertiesFileName) + throws IOException { BooterDeserializer booterDeserializer = - new BooterDeserializer( createSurefirePropertiesIfFileExists( tmpDir, surefirePropsFileName ) ); - setSystemProperties( new File( tmpDir, effectiveSystemPropertiesFileName ) ); + new BooterDeserializer(createSurefirePropertiesIfFileExists(tmpDir, surefirePropsFileName)); + setSystemProperties(new File(tmpDir, effectiveSystemPropertiesFileName)); providerConfiguration = booterDeserializer.deserialize(); DumpErrorSingleton.getSingleton() - .init( providerConfiguration.getReporterConfiguration().getReportsDirectory(), dumpFileName ); + .init(providerConfiguration.getReporterConfiguration().getReportsDirectory(), dumpFileName); int forkNumber = booterDeserializer.getForkNumber(); - if ( isDebugging() ) - { + if (isDebugging()) { DumpErrorSingleton.getSingleton() - .dumpText( "Found Maven process ID " + booterDeserializer.getPluginPid() - + " for the fork " + forkNumber + "." ); + .dumpText("Found Maven process ID " + booterDeserializer.getPluginPid() + " for the fork " + + forkNumber + "."); } startupConfiguration = booterDeserializer.getStartupConfiguration(); String channelConfig = booterDeserializer.getConnectionString(); - channelProcessorFactory = lookupDecoderFactory( channelConfig ); - channelProcessorFactory.connect( channelConfig ); + channelProcessorFactory = lookupDecoderFactory(channelConfig); + channelProcessorFactory.connect(channelConfig); boolean isDebugging = isDebugging(); - boolean debug = isDebugging || providerConfiguration.getMainCliOptions().contains( LOGGING_LEVEL_DEBUG ); - ForkNodeArguments args = new ForkedNodeArg( forkNumber, debug ); - eventChannel = channelProcessorFactory.createEncoder( args ); - MasterProcessChannelDecoder decoder = channelProcessorFactory.createDecoder( args ); + boolean debug = isDebugging || providerConfiguration.getMainCliOptions().contains(LOGGING_LEVEL_DEBUG); + ForkNodeArguments args = new ForkedNodeArg(forkNumber, debug); + eventChannel = channelProcessorFactory.createEncoder(args); + MasterProcessChannelDecoder decoder = channelProcessorFactory.createDecoder(args); flushEventChannelOnExit(); forkingReporterFactory = createForkingReporterFactory(); logger = forkingReporterFactory.createTestReportListener(); - commandReader = new CommandReader( decoder, providerConfiguration.getShutdown(), logger ); + commandReader = new CommandReader(decoder, providerConfiguration.getShutdown(), logger); - pingScheduler = isDebugging ? null : listenToShutdownCommands( booterDeserializer.getPluginPid() ); + pingScheduler = isDebugging ? null : listenToShutdownCommands(booterDeserializer.getPluginPid()); - systemExitTimeoutInSeconds = providerConfiguration.systemExitTimeout( DEFAULT_SYSTEM_EXIT_TIMEOUT_IN_SECONDS ); + systemExitTimeoutInSeconds = providerConfiguration.systemExitTimeout(DEFAULT_SYSTEM_EXIT_TIMEOUT_IN_SECONDS); AbstractPathConfiguration classpathConfiguration = startupConfiguration.getClasspathConfiguration(); - if ( classpathConfiguration.isClassPathConfig() ) - { - if ( startupConfiguration.isManifestOnlyJarRequestedAndUsable() ) - { - classpathConfiguration.toRealPath( ClasspathConfiguration.class ) + if (classpathConfiguration.isClassPathConfig()) { + if (startupConfiguration.isManifestOnlyJarRequestedAndUsable()) { + classpathConfiguration + .toRealPath(ClasspathConfiguration.class) .trickClassPathWhenManifestOnlyClasspath(); } startupConfiguration.writeSurefireTestClasspathProperty(); } ClassLoader classLoader = currentThread().getContextClassLoader(); - classLoader.setDefaultAssertionStatus( classpathConfiguration.isEnableAssertions() ); + classLoader.setDefaultAssertionStatus(classpathConfiguration.isEnableAssertions()); boolean readTestsFromCommandReader = providerConfiguration.isReadTestsFromInStream(); - testSet = createTestSet( providerConfiguration.getTestForFork(), readTestsFromCommandReader, classLoader ); + testSet = createTestSet(providerConfiguration.getTestForFork(), readTestsFromCommandReader, classLoader); } - private void execute() - { - try - { + private void execute() { + try { runSuitesInProcess(); - } - catch ( Throwable t ) - { + } catch (Throwable t) { Throwable e = - t instanceof InvocationTargetException ? ( (InvocationTargetException) t ).getTargetException() : t; - DumpErrorSingleton.getSingleton().dumpException( e ); - logger.error( e.getLocalizedMessage(), e ); - } - finally - { + t instanceof InvocationTargetException ? ((InvocationTargetException) t).getTargetException() : t; + DumpErrorSingleton.getSingleton().dumpException(e); + logger.error(e.getLocalizedMessage(), e); + } finally { //noinspection ResultOfMethodCallIgnored Thread.interrupted(); - if ( eventChannel.checkError() ) - { - DumpErrorSingleton.getSingleton().dumpText( PROCESS_PIPES_ERROR ); - logger.error( PROCESS_PIPES_ERROR ); + if (eventChannel.checkError()) { + DumpErrorSingleton.getSingleton().dumpText(PROCESS_PIPES_ERROR); + logger.error(PROCESS_PIPES_ERROR); } // process pipes are closed far here @@ -191,215 +179,166 @@ private void execute() } } - private Object createTestSet( TypeEncodedValue forkedTestSet, boolean readTestsFromCommandReader, ClassLoader cl ) - { - if ( forkedTestSet != null ) - { - return forkedTestSet.getDecodedValue( cl ); - } - else if ( readTestsFromCommandReader ) - { - return new LazyTestsToRun( eventChannel, commandReader ); + private Object createTestSet(TypeEncodedValue forkedTestSet, boolean readTestsFromCommandReader, ClassLoader cl) { + if (forkedTestSet != null) { + return forkedTestSet.getDecodedValue(cl); + } else if (readTestsFromCommandReader) { + return new LazyTestsToRun(eventChannel, commandReader); } return null; } - private void cancelPingScheduler() - { - if ( pingScheduler != null ) - { - try - { - AccessController.doPrivileged( new PrivilegedAction() - { - @Override - public Object run() - { - pingScheduler.shutdown(); - return null; - } - } - ); - } - catch ( AccessControlException e ) - { + private void cancelPingScheduler() { + if (pingScheduler != null) { + try { + AccessController.doPrivileged(new PrivilegedAction() { + @Override + public Object run() { + pingScheduler.shutdown(); + return null; + } + }); + } catch (AccessControlException e) { // ignore } } } - private void closeForkChannel() - { - if ( channelProcessorFactory != null ) - { - try - { + private void closeForkChannel() { + if (channelProcessorFactory != null) { + try { channelProcessorFactory.close(); - } - catch ( IOException e ) - { + } catch (IOException e) { e.printStackTrace(); } } } - private PingScheduler listenToShutdownCommands( String ppid ) - { - PpidChecker ppidChecker = ppid == null ? null : new PpidChecker( ppid ); - commandReader.addShutdownListener( createExitHandler( ppidChecker ) ); - AtomicBoolean pingDone = new AtomicBoolean( true ); - commandReader.addNoopListener( createPingHandler( pingDone ) ); + private PingScheduler listenToShutdownCommands(String ppid) { + PpidChecker ppidChecker = ppid == null ? null : new PpidChecker(ppid); + commandReader.addShutdownListener(createExitHandler(ppidChecker)); + AtomicBoolean pingDone = new AtomicBoolean(true); + commandReader.addNoopListener(createPingHandler(pingDone)); PingScheduler pingMechanisms = new PingScheduler( - createScheduler( PING_THREAD + PING_TIMEOUT_IN_SECONDS + "s" ), - createScheduler( PROCESS_CHECKER_THREAD ), - ppidChecker ); + createScheduler(PING_THREAD + PING_TIMEOUT_IN_SECONDS + "s"), + createScheduler(PROCESS_CHECKER_THREAD), + ppidChecker); ProcessCheckerType checkerType = startupConfiguration.getProcessChecker(); - if ( ( checkerType == ALL || checkerType == NATIVE ) && pingMechanisms.processChecker != null ) - { - logger.debug( pingMechanisms.processChecker.toString() ); - if ( pingMechanisms.processChecker.canUse() ) - { - Runnable checkerJob = processCheckerJob( pingMechanisms ); - pingMechanisms.processCheckerScheduler.scheduleWithFixedDelay( checkerJob, 0L, 1L, SECONDS ); - } - else if ( !pingMechanisms.processChecker.isStopped() ) - { - logger.warning( "Cannot use process checker with configuration " + checkerType - + ". Platform not supported." ); + if ((checkerType == ALL || checkerType == NATIVE) && pingMechanisms.processChecker != null) { + logger.debug(pingMechanisms.processChecker.toString()); + if (pingMechanisms.processChecker.canUse()) { + Runnable checkerJob = processCheckerJob(pingMechanisms); + pingMechanisms.processCheckerScheduler.scheduleWithFixedDelay(checkerJob, 0L, 1L, SECONDS); + } else if (!pingMechanisms.processChecker.isStopped()) { + logger.warning( + "Cannot use process checker with configuration " + checkerType + ". Platform not supported."); } } - if ( checkerType == ALL || checkerType == PING ) - { - Runnable pingJob = createPingJob( pingDone, pingMechanisms.processChecker ); - pingMechanisms.pingScheduler.scheduleWithFixedDelay( pingJob, 0L, PING_TIMEOUT_IN_SECONDS, SECONDS ); + if (checkerType == ALL || checkerType == PING) { + Runnable pingJob = createPingJob(pingDone, pingMechanisms.processChecker); + pingMechanisms.pingScheduler.scheduleWithFixedDelay(pingJob, 0L, PING_TIMEOUT_IN_SECONDS, SECONDS); } return pingMechanisms; } - private Runnable processCheckerJob( final PingScheduler pingMechanism ) - { - return new Runnable() - { + private Runnable processCheckerJob(final PingScheduler pingMechanism) { + return new Runnable() { @Override - public void run() - { - try - { - if ( pingMechanism.processChecker.canUse() - && !pingMechanism.processChecker.isProcessAlive() - && !pingMechanism.pingScheduler.isShutdown() ) - { - logger.error( "Surefire is going to kill self fork JVM. Maven process died." ); + public void run() { + try { + if (pingMechanism.processChecker.canUse() + && !pingMechanism.processChecker.isProcessAlive() + && !pingMechanism.pingScheduler.isShutdown()) { + logger.error("Surefire is going to kill self fork JVM. Maven process died."); DumpErrorSingleton.getSingleton() - .dumpText( "Killing self fork JVM. Maven process died." + .dumpText("Killing self fork JVM. Maven process died." + NL + "Thread dump before killing the process (" + getProcessName() + "):" + NL - + generateThreadDump() ); + + generateThreadDump()); kill(); } - } - catch ( RuntimeException e ) - { + } catch (RuntimeException e) { DumpErrorSingleton.getSingleton() - .dumpException( e, "System.exit() or native command error interrupted process checker." ); + .dumpException(e, "System.exit() or native command error interrupted process checker."); } } }; } - private CommandListener createPingHandler( final AtomicBoolean pingDone ) - { - return new CommandListener() - { + private CommandListener createPingHandler(final AtomicBoolean pingDone) { + return new CommandListener() { @Override - public void update( Command command ) - { - pingDone.set( true ); + public void update(Command command) { + pingDone.set(true); } }; } - private CommandListener createExitHandler( final PpidChecker ppidChecker ) - { - return new CommandListener() - { + private CommandListener createExitHandler(final PpidChecker ppidChecker) { + return new CommandListener() { @Override - public void update( Command command ) - { + public void update(Command command) { Shutdown shutdown = command.toShutdownData(); - if ( shutdown.isKill() ) - { - if ( ppidChecker != null ) - { + if (shutdown.isKill()) { + if (ppidChecker != null) { ppidChecker.stop(); } - logger.error( "Surefire is going to kill self fork JVM. " - + "Received SHUTDOWN {" + shutdown + "} command from Maven shutdown hook." ); + logger.error("Surefire is going to kill self fork JVM. " + "Received SHUTDOWN {" + shutdown + + "} command from Maven shutdown hook."); DumpErrorSingleton.getSingleton() - .dumpText( "Killing self fork JVM. Received SHUTDOWN command from Maven shutdown hook." + .dumpText("Killing self fork JVM. Received SHUTDOWN command from Maven shutdown hook." + NL + "Thread dump before killing the process (" + getProcessName() + "):" + NL - + generateThreadDump() ); + + generateThreadDump()); kill(); - } - else if ( shutdown.isExit() ) - { - if ( ppidChecker != null ) - { + } else if (shutdown.isExit()) { + if (ppidChecker != null) { ppidChecker.stop(); } cancelPingScheduler(); - logger.error( "Surefire is going to exit self fork JVM. " - + "Received SHUTDOWN {" + shutdown + "} command from Maven shutdown hook." ); + logger.error("Surefire is going to exit self fork JVM. " + "Received SHUTDOWN {" + shutdown + + "} command from Maven shutdown hook."); DumpErrorSingleton.getSingleton() - .dumpText( "Exiting self fork JVM. Received SHUTDOWN command from Maven shutdown hook." + .dumpText("Exiting self fork JVM. Received SHUTDOWN command from Maven shutdown hook." + NL + "Thread dump before exiting the process (" + getProcessName() + "):" + NL - + generateThreadDump() ); + + generateThreadDump()); exitBarrier.release(); exit1(); - } - else - { + } else { // else refers to shutdown=testset, but not used now, keeping reader open DumpErrorSingleton.getSingleton() - .dumpText( "Thread dump for process (" + getProcessName() + "):" - + NL - + generateThreadDump() ); + .dumpText( + "Thread dump for process (" + getProcessName() + "):" + NL + generateThreadDump()); } } }; } - private Runnable createPingJob( final AtomicBoolean pingDone, final PpidChecker pluginProcessChecker ) - { - return new Runnable() - { + private Runnable createPingJob(final AtomicBoolean pingDone, final PpidChecker pluginProcessChecker) { + return new Runnable() { @Override - public void run() - { - if ( !canUseNewPingMechanism( pluginProcessChecker ) ) - { - boolean hasPing = pingDone.getAndSet( false ); - if ( !hasPing ) - { - logger.error( "Killing self fork JVM. PING timeout elapsed." ); + public void run() { + if (!canUseNewPingMechanism(pluginProcessChecker)) { + boolean hasPing = pingDone.getAndSet(false); + if (!hasPing) { + logger.error("Killing self fork JVM. PING timeout elapsed."); DumpErrorSingleton.getSingleton() - .dumpText( "Killing self fork JVM. PING timeout elapsed." + .dumpText("Killing self fork JVM. PING timeout elapsed." + NL + "Thread dump before killing the process (" + getProcessName() + "):" + NL - + generateThreadDump() ); + + generateThreadDump()); kill(); } @@ -408,161 +347,137 @@ public void run() }; } - private void kill() - { - kill( 1 ); + private void kill() { + kill(1); } - private void kill( int returnCode ) - { + private void kill(int returnCode) { commandReader.stop(); closeForkChannel(); - Runtime.getRuntime().halt( returnCode ); + Runtime.getRuntime().halt(returnCode); } - private void exit1() - { - launchLastDitchDaemonShutdownThread( 1 ); - System.exit( 1 ); + private void exit1() { + launchLastDitchDaemonShutdownThread(1); + System.exit(1); } - private void acknowledgedExit() - { - commandReader.addByeAckListener( new CommandListener() - { - @Override - public void update( Command command ) - { - exitBarrier.release(); - } - } - ); + private void acknowledgedExit() { + commandReader.addByeAckListener(new CommandListener() { + @Override + public void update(Command command) { + exitBarrier.release(); + } + }); eventChannel.bye(); - launchLastDitchDaemonShutdownThread( 0 ); - boolean byeAckReceived = acquireOnePermit( exitBarrier ); - if ( !byeAckReceived && !eventChannel.checkError() ) - { - eventChannel.sendExitError( null, false ); + launchLastDitchDaemonShutdownThread(0); + boolean byeAckReceived = acquireOnePermit(exitBarrier); + if (!byeAckReceived && !eventChannel.checkError()) { + eventChannel.sendExitError(null, false); } cancelPingScheduler(); commandReader.stop(); closeForkChannel(); - System.exit( 0 ); + System.exit(0); } - private void runSuitesInProcess() - throws TestSetFailedException, InvocationTargetException - { - createProviderInCurrentClassloader().invoke( testSet ); + private void runSuitesInProcess() throws TestSetFailedException, InvocationTargetException { + createProviderInCurrentClassloader().invoke(testSet); } - private ForkingReporterFactory createForkingReporterFactory() - { - final boolean trimStackTrace = providerConfiguration.getReporterConfiguration().isTrimStackTrace(); - return new ForkingReporterFactory( trimStackTrace, eventChannel ); + private ForkingReporterFactory createForkingReporterFactory() { + final boolean trimStackTrace = + providerConfiguration.getReporterConfiguration().isTrimStackTrace(); + return new ForkingReporterFactory(trimStackTrace, eventChannel); } - private synchronized ScheduledThreadPoolExecutor getJvmTerminator() - { - if ( jvmTerminator == null ) - { + private synchronized ScheduledThreadPoolExecutor getJvmTerminator() { + if (jvmTerminator == null) { ThreadFactory threadFactory = - newDaemonThreadFactory( LAST_DITCH_SHUTDOWN_THREAD + systemExitTimeoutInSeconds + "s" ); - jvmTerminator = new ScheduledThreadPoolExecutor( 1, threadFactory ); - jvmTerminator.setMaximumPoolSize( 1 ); + newDaemonThreadFactory(LAST_DITCH_SHUTDOWN_THREAD + systemExitTimeoutInSeconds + "s"); + jvmTerminator = new ScheduledThreadPoolExecutor(1, threadFactory); + jvmTerminator.setMaximumPoolSize(1); } return jvmTerminator; } - @SuppressWarnings( "checkstyle:emptyblock" ) - private void launchLastDitchDaemonShutdownThread( final int returnCode ) - { + @SuppressWarnings("checkstyle:emptyblock") + private void launchLastDitchDaemonShutdownThread(final int returnCode) { getJvmTerminator() - .schedule( new Runnable() - { - @Override - public void run() - { - if ( logger != null ) - { - logger.error( "Surefire is going to kill self fork JVM. The exit has elapsed " - + systemExitTimeoutInSeconds + " seconds after System.exit(" + returnCode + ")." ); - } - - DumpErrorSingleton.getSingleton() - .dumpText( "Thread dump for process (" - + getProcessName() - + ") after " - + systemExitTimeoutInSeconds - + " seconds shutdown timeout:" - + NL - + generateThreadDump() ); - - kill( returnCode ); - } - }, systemExitTimeoutInSeconds, SECONDS - ); + .schedule( + new Runnable() { + @Override + public void run() { + if (logger != null) { + logger.error("Surefire is going to kill self fork JVM. The exit has elapsed " + + systemExitTimeoutInSeconds + " seconds after System.exit(" + returnCode + + ")."); + } + + DumpErrorSingleton.getSingleton() + .dumpText("Thread dump for process (" + + getProcessName() + + ") after " + + systemExitTimeoutInSeconds + + " seconds shutdown timeout:" + + NL + + generateThreadDump()); + + kill(returnCode); + } + }, + systemExitTimeoutInSeconds, + SECONDS); } - private SurefireProvider createProviderInCurrentClassloader() - { - BaseProviderFactory bpf = new BaseProviderFactory( true ); - bpf.setReporterFactory( forkingReporterFactory ); - bpf.setCommandReader( commandReader ); - bpf.setTestRequest( providerConfiguration.getTestSuiteDefinition() ); - bpf.setReporterConfiguration( providerConfiguration.getReporterConfiguration() ); + private SurefireProvider createProviderInCurrentClassloader() { + BaseProviderFactory bpf = new BaseProviderFactory(true); + bpf.setReporterFactory(forkingReporterFactory); + bpf.setCommandReader(commandReader); + bpf.setTestRequest(providerConfiguration.getTestSuiteDefinition()); + bpf.setReporterConfiguration(providerConfiguration.getReporterConfiguration()); ClassLoader classLoader = currentThread().getContextClassLoader(); - bpf.setClassLoaders( classLoader ); - bpf.setTestArtifactInfo( providerConfiguration.getTestArtifact() ); - bpf.setProviderProperties( providerConfiguration.getProviderProperties() ); - bpf.setRunOrderParameters( providerConfiguration.getRunOrderParameters() ); - bpf.setDirectoryScannerParameters( providerConfiguration.getDirScannerParams() ); - bpf.setMainCliOptions( providerConfiguration.getMainCliOptions() ); - bpf.setSkipAfterFailureCount( providerConfiguration.getSkipAfterFailureCount() ); - bpf.setSystemExitTimeout( providerConfiguration.getSystemExitTimeout() ); + bpf.setClassLoaders(classLoader); + bpf.setTestArtifactInfo(providerConfiguration.getTestArtifact()); + bpf.setProviderProperties(providerConfiguration.getProviderProperties()); + bpf.setRunOrderParameters(providerConfiguration.getRunOrderParameters()); + bpf.setDirectoryScannerParameters(providerConfiguration.getDirScannerParams()); + bpf.setMainCliOptions(providerConfiguration.getMainCliOptions()); + bpf.setSkipAfterFailureCount(providerConfiguration.getSkipAfterFailureCount()); + bpf.setSystemExitTimeout(providerConfiguration.getSystemExitTimeout()); String providerClass = startupConfiguration.getActualClassName(); - return instantiateOneArg( classLoader, providerClass, ProviderParameters.class, bpf ); + return instantiateOneArg(classLoader, providerClass, ProviderParameters.class, bpf); } /** * Necessary for the Surefire817SystemExitIT. */ - private void flushEventChannelOnExit() - { - Runnable target = new Runnable() - { + private void flushEventChannelOnExit() { + Runnable target = new Runnable() { @Override - public void run() - { + public void run() { eventChannel.onJvmExit(); } }; - Thread t = new Thread( target ); - t.setDaemon( true ); - ShutdownHookUtils.addShutDownHook( t ); + Thread t = new Thread(target); + t.setDaemon(true); + ShutdownHookUtils.addShutDownHook(t); } - private static MasterProcessChannelProcessorFactory lookupDecoderFactory( String channelConfig ) - { + private static MasterProcessChannelProcessorFactory lookupDecoderFactory(String channelConfig) { MasterProcessChannelProcessorFactory defaultFactory = null; MasterProcessChannelProcessorFactory customFactory = null; - for ( MasterProcessChannelProcessorFactory factory : load( MasterProcessChannelProcessorFactory.class ) ) - { + for (MasterProcessChannelProcessorFactory factory : load(MasterProcessChannelProcessorFactory.class)) { Class cls = factory.getClass(); - boolean isSurefireFactory = - cls == LegacyMasterProcessChannelProcessorFactory.class + boolean isSurefireFactory = cls == LegacyMasterProcessChannelProcessorFactory.class || cls == SurefireMasterProcessChannelProcessorFactory.class; - if ( isSurefireFactory ) - { - if ( factory.canUse( channelConfig ) ) - { + if (isSurefireFactory) { + if (factory.canUse(channelConfig)) { defaultFactory = factory; } - } - else - { + } else { customFactory = factory; } } @@ -575,10 +490,9 @@ private static MasterProcessChannelProcessorFactory lookupDecoderFactory( String * * @param args Commandline arguments */ - public static void main( String[] args ) - { + public static void main(String[] args) { ForkedBooter booter = new ForkedBooter(); - run( booter, args ); + run(booter, args); } /** @@ -587,122 +501,100 @@ public static void main( String[] args ) * @param booter booter in JVM * @param args arguments passed to JVM */ - private static void run( ForkedBooter booter, String[] args ) - { - try - { - booter.setupBooter( args[0], args[1], args[2], args.length > 3 ? args[3] : null ); + private static void run(ForkedBooter booter, String[] args) { + try { + booter.setupBooter(args[0], args[1], args[2], args.length > 3 ? args[3] : null); booter.execute(); - } - catch ( Throwable t ) - { - DumpErrorSingleton.getSingleton().dumpException( t ); - if ( booter.logger != null ) - { - booter.logger.error( t.getLocalizedMessage(), t ); + } catch (Throwable t) { + DumpErrorSingleton.getSingleton().dumpException(t); + if (booter.logger != null) { + booter.logger.error(t.getLocalizedMessage(), t); } booter.cancelPingScheduler(); booter.exit1(); } } - private static boolean canUseNewPingMechanism( PpidChecker pluginProcessChecker ) - { + private static boolean canUseNewPingMechanism(PpidChecker pluginProcessChecker) { return pluginProcessChecker != null && pluginProcessChecker.canUse(); } - private static boolean acquireOnePermit( Semaphore barrier ) - { - try - { - return barrier.tryAcquire( Integer.MAX_VALUE, SECONDS ); - } - catch ( InterruptedException e ) - { + private static boolean acquireOnePermit(Semaphore barrier) { + try { + return barrier.tryAcquire(Integer.MAX_VALUE, SECONDS); + } catch (InterruptedException e) { // cancel schedulers, stop the command reader and exit 0 return false; } } - private static ScheduledExecutorService createScheduler( String threadName ) - { - ThreadFactory threadFactory = newDaemonThreadFactory( threadName ); - ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor( 1, threadFactory ); - executor.setMaximumPoolSize( executor.getCorePoolSize() ); + private static ScheduledExecutorService createScheduler(String threadName) { + ThreadFactory threadFactory = newDaemonThreadFactory(threadName); + ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1, threadFactory); + executor.setMaximumPoolSize(executor.getCorePoolSize()); return executor; } - private static InputStream createSurefirePropertiesIfFileExists( String tmpDir, String propFileName ) - throws FileNotFoundException - { - File surefirePropertiesFile = new File( tmpDir, propFileName ); - return surefirePropertiesFile.exists() ? new FileInputStream( surefirePropertiesFile ) : null; + private static InputStream createSurefirePropertiesIfFileExists(String tmpDir, String propFileName) + throws FileNotFoundException { + File surefirePropertiesFile = new File(tmpDir, propFileName); + return surefirePropertiesFile.exists() ? new FileInputStream(surefirePropertiesFile) : null; } - private static boolean isDebugging() - { - for ( String argument : ManagementFactory.getRuntimeMXBean().getInputArguments() ) - { - if ( "-Xdebug".equals( argument ) || argument.startsWith( "-agentlib:jdwp" ) ) - { + private static boolean isDebugging() { + for (String argument : ManagementFactory.getRuntimeMXBean().getInputArguments()) { + if ("-Xdebug".equals(argument) || argument.startsWith("-agentlib:jdwp")) { return true; } } return false; } - private static class PingScheduler - { + private static class PingScheduler { private final ScheduledExecutorService pingScheduler; private final ScheduledExecutorService processCheckerScheduler; private final PpidChecker processChecker; - PingScheduler( ScheduledExecutorService pingScheduler, ScheduledExecutorService processCheckerScheduler, - PpidChecker processChecker ) - { + PingScheduler( + ScheduledExecutorService pingScheduler, + ScheduledExecutorService processCheckerScheduler, + PpidChecker processChecker) { this.pingScheduler = pingScheduler; this.processCheckerScheduler = processCheckerScheduler; this.processChecker = processChecker; } - void shutdown() - { + void shutdown() { pingScheduler.shutdown(); processCheckerScheduler.shutdown(); - if ( processChecker != null ) - { + if (processChecker != null) { processChecker.destroyActiveCommands(); } } } - private static String generateThreadDump() - { + private static String generateThreadDump() { StringBuilder dump = new StringBuilder(); ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean(); - ThreadInfo[] threadInfos = threadMXBean.getThreadInfo( threadMXBean.getAllThreadIds(), 100 ); - for ( ThreadInfo threadInfo : threadInfos ) - { - dump.append( '"' ); - dump.append( threadInfo.getThreadName() ); - dump.append( "\" " ); + ThreadInfo[] threadInfos = threadMXBean.getThreadInfo(threadMXBean.getAllThreadIds(), 100); + for (ThreadInfo threadInfo : threadInfos) { + dump.append('"'); + dump.append(threadInfo.getThreadName()); + dump.append("\" "); Thread.State state = threadInfo.getThreadState(); - dump.append( "\n java.lang.Thread.State: " ); - dump.append( state ); + dump.append("\n java.lang.Thread.State: "); + dump.append(state); StackTraceElement[] stackTraceElements = threadInfo.getStackTrace(); - for ( StackTraceElement stackTraceElement : stackTraceElements ) - { - dump.append( "\n at " ); - dump.append( stackTraceElement ); + for (StackTraceElement stackTraceElement : stackTraceElements) { + dump.append("\n at "); + dump.append(stackTraceElement); } - dump.append( "\n\n" ); + dump.append("\n\n"); } return dump.toString(); } - private static String getProcessName() - { - return ManagementFactory.getRuntimeMXBean() - .getName(); + private static String getProcessName() { + return ManagementFactory.getRuntimeMXBean().getName(); } } diff --git a/surefire-booter/src/main/java/org/apache/maven/surefire/booter/ForkedNodeArg.java b/surefire-booter/src/main/java/org/apache/maven/surefire/booter/ForkedNodeArg.java index c7c9c57900..c30aa7e345 100644 --- a/surefire-booter/src/main/java/org/apache/maven/surefire/booter/ForkedNodeArg.java +++ b/surefire-booter/src/main/java/org/apache/maven/surefire/booter/ForkedNodeArg.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.booter; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,26 +16,26 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.booter; + +import javax.annotation.Nonnull; + +import java.io.File; import org.apache.maven.plugin.surefire.log.api.ConsoleLogger; import org.apache.maven.plugin.surefire.log.api.NullConsoleLogger; import org.apache.maven.surefire.api.booter.DumpErrorSingleton; import org.apache.maven.surefire.api.fork.ForkNodeArguments; -import javax.annotation.Nonnull; -import java.io.File; - /** * */ -public final class ForkedNodeArg implements ForkNodeArguments -{ +public final class ForkedNodeArg implements ForkNodeArguments { private final int forkChannelId; private final ConsoleLogger logger; private final boolean isDebug; - public ForkedNodeArg( int forkChannelId, boolean isDebug ) - { + public ForkedNodeArg(int forkChannelId, boolean isDebug) { this.forkChannelId = forkChannelId; logger = new NullConsoleLogger(); this.isDebug = isDebug; @@ -45,60 +43,51 @@ public ForkedNodeArg( int forkChannelId, boolean isDebug ) @Nonnull @Override - public String getSessionId() - { + public String getSessionId() { throw new UnsupportedOperationException(); } @Override - public int getForkChannelId() - { + public int getForkChannelId() { return forkChannelId; } @Override @Nonnull - public File dumpStreamText( @Nonnull String text ) - { - return DumpErrorSingleton.getSingleton().dumpStreamText( text ); + public File dumpStreamText(@Nonnull String text) { + return DumpErrorSingleton.getSingleton().dumpStreamText(text); } @Nonnull @Override - public File dumpStreamException( @Nonnull Throwable t ) - { - return DumpErrorSingleton.getSingleton().dumpStreamException( t, t.getLocalizedMessage() ); + public File dumpStreamException(@Nonnull Throwable t) { + return DumpErrorSingleton.getSingleton().dumpStreamException(t, t.getLocalizedMessage()); } @Override - public void logWarningAtEnd( @Nonnull String text ) - { + public void logWarningAtEnd(@Nonnull String text) { // do nothing - the log message of forked VM already goes to the dump file } @Nonnull @Override - public ConsoleLogger getConsoleLogger() - { + public ConsoleLogger getConsoleLogger() { return logger; } @Nonnull @Override - public Object getConsoleLock() - { + public Object getConsoleLock() { return logger; } @Override - public File getEventStreamBinaryFile() - { + public File getEventStreamBinaryFile() { throw new UnsupportedOperationException(); } @Override - public File getCommandStreamBinaryFile() - { + public File getCommandStreamBinaryFile() { return isDebug ? DumpErrorSingleton.getSingleton().getCommandStreamBinaryFile() : null; } } diff --git a/surefire-booter/src/main/java/org/apache/maven/surefire/booter/IsolatedClassLoader.java b/surefire-booter/src/main/java/org/apache/maven/surefire/booter/IsolatedClassLoader.java index d67eed2438..a748ca748b 100644 --- a/surefire-booter/src/main/java/org/apache/maven/surefire/booter/IsolatedClassLoader.java +++ b/surefire-booter/src/main/java/org/apache/maven/surefire/booter/IsolatedClassLoader.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.booter; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.booter; import java.net.URL; import java.net.URLClassLoader; @@ -27,9 +26,7 @@ /** * Loads classes from jar files added via {@link #addURL(URL)}. */ -public class IsolatedClassLoader - extends URLClassLoader -{ +public class IsolatedClassLoader extends URLClassLoader { private final ClassLoader parent = ClassLoader.getSystemClassLoader(); private final Set urls = new HashSet<>(); @@ -40,9 +37,8 @@ public class IsolatedClassLoader private static final URL[] EMPTY_URL_ARRAY = new URL[0]; - public IsolatedClassLoader( ClassLoader parent, boolean childDelegation, String roleName ) - { - super( EMPTY_URL_ARRAY, parent ); + public IsolatedClassLoader(ClassLoader parent, boolean childDelegation, String roleName) { + super(EMPTY_URL_ARRAY, parent); this.childDelegation = childDelegation; @@ -55,55 +51,40 @@ public IsolatedClassLoader( ClassLoader parent, boolean childDelegation, String */ @Override @Deprecated - public void addURL( URL url ) - { + public void addURL(URL url) { // avoid duplicates // todo avoid URL due to calling equals method may cause some overhead due to resolving host or file. - if ( !urls.contains( url ) ) - { - super.addURL( url ); - urls.add( url ); + if (!urls.contains(url)) { + super.addURL(url); + urls.add(url); } } @Override - public synchronized Class loadClass( String name ) - throws ClassNotFoundException - { - if ( childDelegation ) - { - Class c = findLoadedClass( name ); + public synchronized Class loadClass(String name) throws ClassNotFoundException { + if (childDelegation) { + Class c = findLoadedClass(name); - if ( c == null ) - { - try - { - c = findClass( name ); - } - catch ( ClassNotFoundException e ) - { - if ( parent == null ) - { + if (c == null) { + try { + c = findClass(name); + } catch (ClassNotFoundException e) { + if (parent == null) { throw e; - } - else - { - c = parent.loadClass( name ); + } else { + c = parent.loadClass(name); } } } return c; - } - else - { - return super.loadClass( name ); + } else { + return super.loadClass(name); } } @Override - public String toString() - { + public String toString() { return "IsolatedClassLoader{roleName='" + roleName + "'}"; } } diff --git a/surefire-booter/src/main/java/org/apache/maven/surefire/booter/KeyValueSource.java b/surefire-booter/src/main/java/org/apache/maven/surefire/booter/KeyValueSource.java index cf3c6293b5..7da898bd76 100644 --- a/surefire-booter/src/main/java/org/apache/maven/surefire/booter/KeyValueSource.java +++ b/surefire-booter/src/main/java/org/apache/maven/surefire/booter/KeyValueSource.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.booter; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,13 +16,13 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.booter; import java.util.Map; /** * A key-value source obeying the geneal constrains of java.util.Properties */ -public interface KeyValueSource -{ - void copyTo( Map target ); +public interface KeyValueSource { + void copyTo(Map target); } diff --git a/surefire-booter/src/main/java/org/apache/maven/surefire/booter/LazyTestsToRun.java b/surefire-booter/src/main/java/org/apache/maven/surefire/booter/LazyTestsToRun.java index 7a147bd54e..1dff93cf3a 100644 --- a/surefire-booter/src/main/java/org/apache/maven/surefire/booter/LazyTestsToRun.java +++ b/surefire-booter/src/main/java/org/apache/maven/surefire/booter/LazyTestsToRun.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.booter; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.booter; import java.util.Collections; import java.util.Iterator; @@ -41,9 +40,7 @@ * @author Andreas Gudian * @author Tibor Digana */ -final class LazyTestsToRun - extends TestsToRun -{ +final class LazyTestsToRun extends TestsToRun { private final MasterProcessChannelEncoder eventChannel; private final CommandReader commandReader; @@ -52,33 +49,28 @@ final class LazyTestsToRun * * @param eventChannel the output stream to use when requesting new new tests */ - LazyTestsToRun( MasterProcessChannelEncoder eventChannel, CommandReader commandReader ) - { - super( Collections.>emptySet() ); + LazyTestsToRun(MasterProcessChannelEncoder eventChannel, CommandReader commandReader) { + super(Collections.>emptySet()); this.eventChannel = eventChannel; this.commandReader = commandReader; } - private final class BlockingIterator - implements Iterator> - { - private final Iterator it = commandReader.getIterableClasses( eventChannel ).iterator(); + private final class BlockingIterator implements Iterator> { + private final Iterator it = + commandReader.getIterableClasses(eventChannel).iterator(); @Override - public boolean hasNext() - { + public boolean hasNext() { return it.hasNext(); } @Override - public Class next() - { - return findClass( it.next() ); + public Class next() { + return findClass(it.next()); } @Override - public void remove() - { + public void remove() { throw new UnsupportedOperationException(); } } @@ -87,8 +79,7 @@ public void remove() * @return test classes which have been retrieved by {@link LazyTestsToRun#iterator()}. */ @Override - public Iterator> iterated() - { + public Iterator> iterated() { return newWeakIterator(); } @@ -98,18 +89,16 @@ public Iterator> iterated() * @see TestsToRun#iterator() * */ @Override - public Iterator> iterator() - { + public Iterator> iterator() { return new BlockingIterator(); } /* (non-Javadoc) * {@inheritDoc} - * @see org.apache.maven.surefire.util.TestsToRun#toString() - */ + * @see org.apache.maven.surefire.util.TestsToRun#toString() + */ @Override - public String toString() - { + public String toString() { return "LazyTestsToRun"; } @@ -118,52 +107,42 @@ public String toString() * @see org.apache.maven.surefire.util.TestsToRun#allowEagerReading() */ @Override - public boolean allowEagerReading() - { + public boolean allowEagerReading() { return false; } - private static Class findClass( String clazz ) - { - return loadClass( Thread.currentThread().getContextClassLoader(), clazz ); + private static Class findClass(String clazz) { + return loadClass(Thread.currentThread().getContextClassLoader(), clazz); } /** * @return snapshot of tests upon constructs of {@link CommandReader#iterated() iterator}. * Therefore weakly consistent while {@link LazyTestsToRun#iterator()} is being iterated. */ - private Iterator> newWeakIterator() - { + private Iterator> newWeakIterator() { final Iterator it = commandReader.iterated(); - return new CloseableIterator>() - { + return new CloseableIterator>() { @Override - protected boolean isClosed() - { + protected boolean isClosed() { return LazyTestsToRun.this.isFinished(); } @Override - protected boolean doHasNext() - { + protected boolean doHasNext() { return it.hasNext(); } @Override - protected Class doNext() - { - return findClass( it.next() ); + protected Class doNext() { + return findClass(it.next()); } @Override - protected void doRemove() - { - } + protected void doRemove() {} @Override - public void remove() - { - throw new UnsupportedOperationException( "unsupported remove" ); + public void remove() { + throw new UnsupportedOperationException("unsupported remove"); } }; } diff --git a/surefire-booter/src/main/java/org/apache/maven/surefire/booter/ModularClasspath.java b/surefire-booter/src/main/java/org/apache/maven/surefire/booter/ModularClasspath.java index 89aa1319a3..b5883ceed7 100644 --- a/surefire-booter/src/main/java/org/apache/maven/surefire/booter/ModularClasspath.java +++ b/surefire-booter/src/main/java/org/apache/maven/surefire/booter/ModularClasspath.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.booter; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,8 +16,10 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.booter; import javax.annotation.Nonnull; + import java.io.File; import java.util.Collection; import java.util.List; @@ -34,53 +34,46 @@ * @author Tibor Digana (tibor17) * @since 2.21.0.Jigsaw */ -public final class ModularClasspath -{ +public final class ModularClasspath { private final String moduleNameFromDescriptor; private final List modulePath; private final Collection packages; private final File patchFile; private final boolean isMainDescriptor; - public ModularClasspath( @Nonnull String moduleNameFromDescriptor, - @Nonnull List modulePath, - @Nonnull Collection packages, - File patchFile, - boolean isMainDescriptor ) - { + public ModularClasspath( + @Nonnull String moduleNameFromDescriptor, + @Nonnull List modulePath, + @Nonnull Collection packages, + File patchFile, + boolean isMainDescriptor) { this.moduleNameFromDescriptor = moduleNameFromDescriptor; this.modulePath = modulePath; this.packages = packages; - this.patchFile = - isMainDescriptor ? requireNonNull( patchFile, "patchFile should not be null" ) : patchFile; + this.patchFile = isMainDescriptor ? requireNonNull(patchFile, "patchFile should not be null") : patchFile; this.isMainDescriptor = isMainDescriptor; } @Nonnull - public String getModuleNameFromDescriptor() - { + public String getModuleNameFromDescriptor() { return moduleNameFromDescriptor; } @Nonnull - public List getModulePath() - { - return unmodifiableList( modulePath ); + public List getModulePath() { + return unmodifiableList(modulePath); } @Nonnull - public Collection getPackages() - { - return unmodifiableCollection( packages ); + public Collection getPackages() { + return unmodifiableCollection(packages); } - public File getPatchFile() - { + public File getPatchFile() { return patchFile; } - public boolean isMainDescriptor() - { + public boolean isMainDescriptor() { return isMainDescriptor; } } diff --git a/surefire-booter/src/main/java/org/apache/maven/surefire/booter/ModularClasspathConfiguration.java b/surefire-booter/src/main/java/org/apache/maven/surefire/booter/ModularClasspathConfiguration.java index e19bd4f3a4..6a31124822 100644 --- a/surefire-booter/src/main/java/org/apache/maven/surefire/booter/ModularClasspathConfiguration.java +++ b/surefire-booter/src/main/java/org/apache/maven/surefire/booter/ModularClasspathConfiguration.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.booter; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.booter; import javax.annotation.Nonnull; @@ -29,8 +28,7 @@ * @author Tibor Digana (tibor17) * @since 2.21.0.Jigsaw */ -public class ModularClasspathConfiguration extends AbstractPathConfiguration -{ +public class ModularClasspathConfiguration extends AbstractPathConfiguration { private final ModularClasspath modularClasspath; private final Classpath testClasspathUrls; @@ -39,52 +37,45 @@ public class ModularClasspathConfiguration extends AbstractPathConfiguration */ private final Classpath inprocClasspath; - public ModularClasspathConfiguration( @Nonnull ModularClasspath modularClasspath, - @Nonnull Classpath testClasspathUrls, - @Nonnull Classpath surefireClasspathUrls, - @Nonnull Classpath inprocClasspath, - boolean enableAssertions, - boolean childDelegation ) - { - super( surefireClasspathUrls, enableAssertions, childDelegation ); + public ModularClasspathConfiguration( + @Nonnull ModularClasspath modularClasspath, + @Nonnull Classpath testClasspathUrls, + @Nonnull Classpath surefireClasspathUrls, + @Nonnull Classpath inprocClasspath, + boolean enableAssertions, + boolean childDelegation) { + super(surefireClasspathUrls, enableAssertions, childDelegation); this.modularClasspath = modularClasspath; this.testClasspathUrls = testClasspathUrls; this.inprocClasspath = inprocClasspath; } @Override - public Classpath getTestClasspath() - { + public Classpath getTestClasspath() { return testClasspathUrls; } @Override - public final boolean isModularPathConfig() - { + public final boolean isModularPathConfig() { return true; } @Override - public final boolean isClassPathConfig() - { + public final boolean isClassPathConfig() { return !isModularPathConfig(); } - public ModularClasspath getModularClasspath() - { + public ModularClasspath getModularClasspath() { return modularClasspath; } - public ClassLoader createMergedClassLoader() - throws SurefireExecutionException - { + public ClassLoader createMergedClassLoader() throws SurefireExecutionException { Collection modulePath = getModularClasspath().getModulePath(); - return createMergedClassLoader( join( getInprocTestClasspath(), new Classpath( modulePath ) ) ); + return createMergedClassLoader(join(getInprocTestClasspath(), new Classpath(modulePath))); } @Override - protected Classpath getInprocClasspath() - { + protected Classpath getInprocClasspath() { return inprocClasspath; } } diff --git a/surefire-booter/src/main/java/org/apache/maven/surefire/booter/PpidChecker.java b/surefire-booter/src/main/java/org/apache/maven/surefire/booter/PpidChecker.java index d908dab4a3..fcdad391cb 100644 --- a/surefire-booter/src/main/java/org/apache/maven/surefire/booter/PpidChecker.java +++ b/surefire-booter/src/main/java/org/apache/maven/surefire/booter/PpidChecker.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.booter; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,11 +16,10 @@ * specific language governing permissions and limitations * under the License. */ - -import org.apache.maven.surefire.api.booter.DumpErrorSingleton; -import org.apache.maven.surefire.api.util.SureFireFileManager; +package org.apache.maven.surefire.booter; import javax.annotation.Nonnull; + import java.io.File; import java.io.IOException; import java.io.InterruptedIOException; @@ -35,6 +32,9 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; +import org.apache.maven.surefire.api.booter.DumpErrorSingleton; +import org.apache.maven.surefire.api.util.SureFireFileManager; + import static java.lang.Integer.parseInt; import static java.lang.Long.parseLong; import static java.lang.String.join; @@ -44,17 +44,17 @@ import static java.util.concurrent.TimeUnit.HOURS; import static java.util.concurrent.TimeUnit.MINUTES; import static java.util.regex.Pattern.compile; +import static org.apache.maven.surefire.api.util.internal.StringUtils.NL; +import static org.apache.maven.surefire.booter.ProcessInfo.ERR_PROCESS_INFO; +import static org.apache.maven.surefire.booter.ProcessInfo.INVALID_PROCESS_INFO; +import static org.apache.maven.surefire.booter.ProcessInfo.unixProcessInfo; +import static org.apache.maven.surefire.booter.ProcessInfo.windowsProcessInfo; import static org.apache.maven.surefire.shared.io.IOUtils.closeQuietly; import static org.apache.maven.surefire.shared.lang3.StringUtils.isNotBlank; import static org.apache.maven.surefire.shared.lang3.SystemUtils.IS_OS_HP_UX; import static org.apache.maven.surefire.shared.lang3.SystemUtils.IS_OS_LINUX; import static org.apache.maven.surefire.shared.lang3.SystemUtils.IS_OS_UNIX; import static org.apache.maven.surefire.shared.lang3.SystemUtils.IS_OS_WINDOWS; -import static org.apache.maven.surefire.booter.ProcessInfo.unixProcessInfo; -import static org.apache.maven.surefire.booter.ProcessInfo.windowsProcessInfo; -import static org.apache.maven.surefire.booter.ProcessInfo.ERR_PROCESS_INFO; -import static org.apache.maven.surefire.booter.ProcessInfo.INVALID_PROCESS_INFO; -import static org.apache.maven.surefire.api.util.internal.StringUtils.NL; /** * Recognizes PID of Plugin process and determines lifetime. @@ -62,8 +62,7 @@ * @author Tibor Digana (tibor17) * @since 2.20.1 */ -final class PpidChecker -{ +final class PpidChecker { private static final long MINUTES_TO_MILLIS = 60L * 1000L; // 25 chars https://superuser.com/questions/937380/get-creation-time-of-file-in-milliseconds/937401#937401 private static final int WMIC_CREATION_DATE_VALUE_LENGTH = 25; @@ -84,24 +83,21 @@ final class PpidChecker * The etime is in the form of [[dd-]hh:]mm:ss on Unix like systems. * See the workaround https://issues.apache.org/jira/browse/SUREFIRE-1451. */ - static final Pattern UNIX_CMD_OUT_PATTERN = compile( "^(((\\d+)-)?(\\d{1,2}):)?(\\d{1,2}):(\\d{1,2})\\s+(\\d+)$" ); + static final Pattern UNIX_CMD_OUT_PATTERN = compile("^(((\\d+)-)?(\\d{1,2}):)?(\\d{1,2}):(\\d{1,2})\\s+(\\d+)$"); - static final Pattern BUSYBOX_CMD_OUT_PATTERN = compile( "^(\\d+)[hH](\\d{1,2})\\s+(\\d+)$" ); + static final Pattern BUSYBOX_CMD_OUT_PATTERN = compile("^(\\d+)[hH](\\d{1,2})\\s+(\\d+)$"); private final String ppid; private volatile ProcessInfo parentProcessInfo; private volatile boolean stopped; - PpidChecker( @Nonnull String ppid ) - { + PpidChecker(@Nonnull String ppid) { this.ppid = ppid; } - boolean canUse() - { - if ( isStopped() ) - { + boolean canUse() { + if (isStopped()) { return false; } final ProcessInfo ppi = parentProcessInfo; @@ -116,47 +112,39 @@ boolean canUse() * or this object has been {@link #destroyActiveCommands() destroyed} * @throws NullPointerException if extracted e-time is null */ - boolean isProcessAlive() - { - if ( !canUse() ) - { - throw new IllegalStateException( "irrelevant to call isProcessAlive()" ); + boolean isProcessAlive() { + if (!canUse()) { + throw new IllegalStateException("irrelevant to call isProcessAlive()"); } final ProcessInfo previousInfo = parentProcessInfo; - if ( IS_OS_WINDOWS ) - { + if (IS_OS_WINDOWS) { parentProcessInfo = windows(); checkProcessInfo(); // let's compare creation time, should be same unless killed or PID is reused by OS into another process return !parentProcessInfo.isInvalid() - && ( previousInfo == null || parentProcessInfo.isTimeEqualTo( previousInfo ) ); - } - else if ( IS_OS_UNIX ) - { + && (previousInfo == null || parentProcessInfo.isTimeEqualTo(previousInfo)); + } else if (IS_OS_UNIX) { parentProcessInfo = unix(); checkProcessInfo(); // let's compare elapsed time, should be greater or equal if parent process is the same and still alive return !parentProcessInfo.isInvalid() - && ( previousInfo == null || !parentProcessInfo.isTimeBefore( previousInfo ) ); + && (previousInfo == null || !parentProcessInfo.isTimeBefore(previousInfo)); } parentProcessInfo = ERR_PROCESS_INFO; - throw new IllegalStateException( "unknown platform or you did not call canUse() before isProcessAlive()" ); + throw new IllegalStateException("unknown platform or you did not call canUse() before isProcessAlive()"); } - private void checkProcessInfo() - { - if ( isStopped() ) - { - throw new IllegalStateException( "error [STOPPED] to read process " + ppid ); + private void checkProcessInfo() { + if (isStopped()) { + throw new IllegalStateException("error [STOPPED] to read process " + ppid); } - if ( !parentProcessInfo.canUse() ) - { - throw new IllegalStateException( "Cannot use PPID " + ppid + " process information. " - + "Going to use NOOP events." ); + if (!parentProcessInfo.canUse()) { + throw new IllegalStateException( + "Cannot use PPID " + ppid + " process information. " + "Going to use NOOP events."); } } @@ -167,192 +155,152 @@ private void checkProcessInfo() // etimes elapsed time since the process was started, in seconds. // http://hg.openjdk.java.net/jdk7/jdk7/jdk/file/9b8c96f96a0f/test/java/lang/ProcessBuilder/Basic.java#L167 - ProcessInfo unix() - { - String charset = System.getProperty( "native.encoding", System.getProperty( "file.encoding", "UTF-8" ) ); - ProcessInfoConsumer reader = new ProcessInfoConsumer( charset ) - { + ProcessInfo unix() { + String charset = System.getProperty("native.encoding", System.getProperty("file.encoding", "UTF-8")); + ProcessInfoConsumer reader = new ProcessInfoConsumer(charset) { @Override @Nonnull - ProcessInfo consumeLine( String line, ProcessInfo previousOutputLine ) - { - if ( previousOutputLine.isInvalid() ) - { - if ( hasHeader ) - { - Matcher matcher = UNIX_CMD_OUT_PATTERN.matcher( line ); - if ( matcher.matches() && ppid.equals( fromPID( matcher ) ) ) - { - long pidUptime = fromDays( matcher ) - + fromHours( matcher ) - + fromMinutes( matcher ) - + fromSeconds( matcher ); - return unixProcessInfo( ppid, pidUptime ); + ProcessInfo consumeLine(String line, ProcessInfo previousOutputLine) { + if (previousOutputLine.isInvalid()) { + if (hasHeader) { + Matcher matcher = UNIX_CMD_OUT_PATTERN.matcher(line); + if (matcher.matches() && ppid.equals(fromPID(matcher))) { + long pidUptime = fromDays(matcher) + + fromHours(matcher) + + fromMinutes(matcher) + + fromSeconds(matcher); + return unixProcessInfo(ppid, pidUptime); } - matcher = BUSYBOX_CMD_OUT_PATTERN.matcher( line ); - if ( matcher.matches() && ppid.equals( fromBusyboxPID( matcher ) ) ) - { - long pidUptime = fromBusyboxHours( matcher ) + fromBusyboxMinutes( matcher ); - return unixProcessInfo( ppid, pidUptime ); + matcher = BUSYBOX_CMD_OUT_PATTERN.matcher(line); + if (matcher.matches() && ppid.equals(fromBusyboxPID(matcher))) { + long pidUptime = fromBusyboxHours(matcher) + fromBusyboxMinutes(matcher); + return unixProcessInfo(ppid, pidUptime); } - } - else - { - hasHeader = line.contains( PS_ETIME_HEADER ) && line.contains( PS_PID_HEADER ); + } else { + hasHeader = line.contains(PS_ETIME_HEADER) && line.contains(PS_PID_HEADER); } } return previousOutputLine; } }; - String cmd = unixPathToPS() + " -o etime,pid " + ( IS_OS_LINUX ? "" : "-p " ) + ppid; - return reader.execute( "/bin/sh", "-c", cmd ); + String cmd = unixPathToPS() + " -o etime,pid " + (IS_OS_LINUX ? "" : "-p ") + ppid; + return reader.execute("/bin/sh", "-c", cmd); } - ProcessInfo windows() - { - ProcessInfoConsumer reader = new ProcessInfoConsumer( "US-ASCII" ) - { + ProcessInfo windows() { + ProcessInfoConsumer reader = new ProcessInfoConsumer("US-ASCII") { @Override @Nonnull - ProcessInfo consumeLine( String line, ProcessInfo previousProcessInfo ) throws Exception - { - if ( previousProcessInfo.isInvalid() && !line.isEmpty() ) - { - if ( hasHeader ) - { + ProcessInfo consumeLine(String line, ProcessInfo previousProcessInfo) throws Exception { + if (previousProcessInfo.isInvalid() && !line.isEmpty()) { + if (hasHeader) { // now the line is CreationDate, e.g. 20180406142327.741074+120 - if ( line.length() != WMIC_CREATION_DATE_VALUE_LENGTH ) - { - throw new IllegalStateException( "WMIC CreationDate should have 25 characters " - + line ); + if (line.length() != WMIC_CREATION_DATE_VALUE_LENGTH) { + throw new IllegalStateException("WMIC CreationDate should have 25 characters " + line); } - String startTimestamp = line.substring( 0, WMIC_CREATION_DATE_TIMESTAMP_LENGTH ); + String startTimestamp = line.substring(0, WMIC_CREATION_DATE_TIMESTAMP_LENGTH); int indexOfTimeZone = WMIC_CREATION_DATE_VALUE_LENGTH - 4; long startTimestampMillisUTC = - WMIC_CREATION_DATE_FORMAT.parse( startTimestamp ).getTime() - - parseInt( line.substring( indexOfTimeZone ) ) * MINUTES_TO_MILLIS; - return windowsProcessInfo( ppid, startTimestampMillisUTC ); - } - else - { - hasHeader = WMIC_CREATION_DATE.equals( line ); + WMIC_CREATION_DATE_FORMAT.parse(startTimestamp).getTime() + - parseInt(line.substring(indexOfTimeZone)) * MINUTES_TO_MILLIS; + return windowsProcessInfo(ppid, startTimestampMillisUTC); + } else { + hasHeader = WMIC_CREATION_DATE.equals(line); } } return previousProcessInfo; } }; String wmicPath = hasWmicStandardSystemPath() ? SYSTEM_PATH_TO_WMIC : ""; - return reader.execute( "CMD", "/A", "/X", "/C", - wmicPath + "wmic process where (ProcessId=" + ppid + ") get " + WMIC_CREATION_DATE - ); + return reader.execute( + "CMD", + "/A", + "/X", + "/C", + wmicPath + "wmic process where (ProcessId=" + ppid + ") get " + WMIC_CREATION_DATE); } - void destroyActiveCommands() - { + void destroyActiveCommands() { stopped = true; - for ( Process p = destroyableCommands.poll(); p != null; p = destroyableCommands.poll() ) - { + for (Process p = destroyableCommands.poll(); p != null; p = destroyableCommands.poll()) { p.destroy(); } } - boolean isStopped() - { + boolean isStopped() { return stopped; } - private static String unixPathToPS() - { + private static String unixPathToPS() { return canExecuteLocalUnixPs() ? "/usr/bin/ps" : "/bin/ps"; } - static boolean canExecuteUnixPs() - { + static boolean canExecuteUnixPs() { return canExecuteLocalUnixPs() || canExecuteStandardUnixPs(); } - private static boolean canExecuteLocalUnixPs() - { - try - { - return new File( "/usr/bin/ps" ).canExecute(); - } - catch ( SecurityException e ) - { + private static boolean canExecuteLocalUnixPs() { + try { + return new File("/usr/bin/ps").canExecute(); + } catch (SecurityException e) { return false; } } - private static boolean canExecuteStandardUnixPs() - { - try - { - return new File( "/bin/ps" ).canExecute(); - } - catch ( SecurityException e ) - { + private static boolean canExecuteStandardUnixPs() { + try { + return new File("/bin/ps").canExecute(); + } catch (SecurityException e) { return false; } } - private static boolean hasWmicStandardSystemPath() - { - String systemRoot = System.getenv( WINDOWS_SYSTEM_ROOT_ENV ); - return isNotBlank( systemRoot ) && new File( systemRoot, RELATIVE_PATH_TO_WMIC + "\\wmic.exe" ).isFile(); + private static boolean hasWmicStandardSystemPath() { + String systemRoot = System.getenv(WINDOWS_SYSTEM_ROOT_ENV); + return isNotBlank(systemRoot) && new File(systemRoot, RELATIVE_PATH_TO_WMIC + "\\wmic.exe").isFile(); } - static long fromDays( Matcher matcher ) - { - String s = matcher.group( 3 ); - return s == null ? 0L : DAYS.toSeconds( parseLong( s ) ); + static long fromDays(Matcher matcher) { + String s = matcher.group(3); + return s == null ? 0L : DAYS.toSeconds(parseLong(s)); } - static long fromHours( Matcher matcher ) - { - String s = matcher.group( 4 ); - return s == null ? 0L : HOURS.toSeconds( parseLong( s ) ); + static long fromHours(Matcher matcher) { + String s = matcher.group(4); + return s == null ? 0L : HOURS.toSeconds(parseLong(s)); } - static long fromMinutes( Matcher matcher ) - { - String s = matcher.group( 5 ); - return s == null ? 0L : MINUTES.toSeconds( parseLong( s ) ); + static long fromMinutes(Matcher matcher) { + String s = matcher.group(5); + return s == null ? 0L : MINUTES.toSeconds(parseLong(s)); } - static long fromSeconds( Matcher matcher ) - { - String s = matcher.group( 6 ); - return s == null ? 0L : parseLong( s ); + static long fromSeconds(Matcher matcher) { + String s = matcher.group(6); + return s == null ? 0L : parseLong(s); } - static String fromPID( Matcher matcher ) - { - return matcher.group( 7 ); + static String fromPID(Matcher matcher) { + return matcher.group(7); } - static long fromBusyboxHours( Matcher matcher ) - { - String s = matcher.group( 1 ); - return s == null ? 0L : HOURS.toSeconds( parseLong( s ) ); + static long fromBusyboxHours(Matcher matcher) { + String s = matcher.group(1); + return s == null ? 0L : HOURS.toSeconds(parseLong(s)); } - static long fromBusyboxMinutes( Matcher matcher ) - { - String s = matcher.group( 2 ); - return s == null ? 0L : MINUTES.toSeconds( parseLong( s ) ); + static long fromBusyboxMinutes(Matcher matcher) { + String s = matcher.group(2); + return s == null ? 0L : MINUTES.toSeconds(parseLong(s)); } - static String fromBusyboxPID( Matcher matcher ) - { - return matcher.group( 3 ); + static String fromBusyboxPID(Matcher matcher) { + return matcher.group(3); } - private static void checkValid( Scanner scanner ) - throws IOException - { + private static void checkValid(Scanner scanner) throws IOException { IOException exception = scanner.ioException(); - if ( exception != null ) - { + if (exception != null) { throw exception; } } @@ -364,15 +312,13 @@ private static void checkValid( Scanner scanner ) * * @return Windows WMIC format yyyymmddHHMMSS.xxx */ - private static SimpleDateFormat createWindowsCreationDateFormat() - { - SimpleDateFormat formatter = new SimpleDateFormat( "yyyyMMddHHmmss'.'SSS" ); - formatter.setTimeZone( TimeZone.getTimeZone( "UTC" ) ); + private static SimpleDateFormat createWindowsCreationDateFormat() { + SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss'.'SSS"); + formatter.setTimeZone(TimeZone.getTimeZone("UTC")); return formatter; } - public void stop() - { + public void stop() { stopped = true; } @@ -383,101 +329,84 @@ public void stop() * This implementation is taylor made without using any Thread. * It's easy to destroy Process from other Thread. */ - abstract class ProcessInfoConsumer - { + abstract class ProcessInfoConsumer { private final String charset; boolean hasHeader; - ProcessInfoConsumer( String charset ) - { + ProcessInfoConsumer(String charset) { this.charset = charset; } - abstract @Nonnull ProcessInfo consumeLine( String line, ProcessInfo previousProcessInfo ) throws Exception; + abstract @Nonnull ProcessInfo consumeLine(String line, ProcessInfo previousProcessInfo) throws Exception; - ProcessInfo execute( String... command ) - { - ProcessBuilder processBuilder = new ProcessBuilder( command ); + ProcessInfo execute(String... command) { + ProcessBuilder processBuilder = new ProcessBuilder(command); Process process = null; ProcessInfo processInfo = INVALID_PROCESS_INFO; - StringBuilder out = new StringBuilder( 64 ); - out.append( join( " ", command ) ) - .append( NL ); + StringBuilder out = new StringBuilder(64); + out.append(join(" ", command)).append(NL); Path stdErr = null; - try - { - stdErr = SureFireFileManager.createTempFile( "surefire", null ).toPath(); + try { + stdErr = SureFireFileManager.createTempFile("surefire", null).toPath(); - processBuilder.redirectError( stdErr.toFile() ); - if ( IS_OS_HP_UX ) // force to run shell commands in UNIX Standard mode on HP-UX + processBuilder.redirectError(stdErr.toFile()); + if (IS_OS_HP_UX) // force to run shell commands in UNIX Standard mode on HP-UX { - processBuilder.environment().put( "UNIX95", "1" ); + processBuilder.environment().put("UNIX95", "1"); } process = processBuilder.start(); - destroyableCommands.add( process ); - Scanner scanner = new Scanner( process.getInputStream(), charset ); - while ( scanner.hasNextLine() ) - { + destroyableCommands.add(process); + Scanner scanner = new Scanner(process.getInputStream(), charset); + while (scanner.hasNextLine()) { String line = scanner.nextLine(); - out.append( line ).append( NL ); - processInfo = consumeLine( line.trim(), processInfo ); + out.append(line).append(NL); + processInfo = consumeLine(line.trim(), processInfo); } - checkValid( scanner ); + checkValid(scanner); int exitCode = process.waitFor(); boolean isError = Thread.interrupted() || isStopped(); - if ( exitCode != 0 || isError ) - { - out.append( "<> <<" ).append( exitCode ).append( ">>" ) - .append( NL ) - .append( "<> <<" ).append( isStopped() ).append( ">>" ); - DumpErrorSingleton.getSingleton() - .dumpText( out.toString() ); + if (exitCode != 0 || isError) { + out.append("<> <<") + .append(exitCode) + .append(">>") + .append(NL) + .append("<> <<") + .append(isStopped()) + .append(">>"); + DumpErrorSingleton.getSingleton().dumpText(out.toString()); } - return isError ? ERR_PROCESS_INFO : ( exitCode == 0 ? processInfo : INVALID_PROCESS_INFO ); - } - catch ( Exception e ) - { - if ( !( e instanceof InterruptedException || e instanceof InterruptedIOException - || e.getCause() instanceof InterruptedException ) ) - { - DumpErrorSingleton.getSingleton() - .dumpText( out.toString() ); + return isError ? ERR_PROCESS_INFO : (exitCode == 0 ? processInfo : INVALID_PROCESS_INFO); + } catch (Exception e) { + if (!(e instanceof InterruptedException + || e instanceof InterruptedIOException + || e.getCause() instanceof InterruptedException)) { + DumpErrorSingleton.getSingleton().dumpText(out.toString()); - DumpErrorSingleton.getSingleton() - .dumpException( e ); + DumpErrorSingleton.getSingleton().dumpException(e); } //noinspection ResultOfMethodCallIgnored Thread.interrupted(); return ERR_PROCESS_INFO; - } - finally - { - if ( process != null ) - { - destroyableCommands.remove( process ); - closeQuietly( process.getInputStream() ); - closeQuietly( process.getErrorStream() ); - closeQuietly( process.getOutputStream() ); + } finally { + if (process != null) { + destroyableCommands.remove(process); + closeQuietly(process.getInputStream()); + closeQuietly(process.getErrorStream()); + closeQuietly(process.getOutputStream()); } - if ( stdErr != null ) - { - try - { - String error = new String( readAllBytes( stdErr ) ).trim(); - if ( !error.isEmpty() ) - { - DumpErrorSingleton.getSingleton() - .dumpText( error ); + if (stdErr != null) { + try { + String error = new String(readAllBytes(stdErr)).trim(); + if (!error.isEmpty()) { + DumpErrorSingleton.getSingleton().dumpText(error); } - delete( stdErr ); - } - catch ( IOException e ) - { + delete(stdErr); + } catch (IOException e) { // cannot do anything about it, the dump file writes would fail as well } } @@ -486,22 +415,17 @@ ProcessInfo execute( String... command ) } @Override - public String toString() - { - String args = "ppid=" + ppid - + ", stopped=" + stopped; + public String toString() { + String args = "ppid=" + ppid + ", stopped=" + stopped; ProcessInfo processInfo = parentProcessInfo; - if ( processInfo != null ) - { - args += ", invalid=" + processInfo.isInvalid() - + ", error=" + processInfo.isError(); + if (processInfo != null) { + args += ", invalid=" + processInfo.isInvalid() + ", error=" + processInfo.isError(); } - if ( IS_OS_UNIX ) - { - args += ", canExecuteLocalUnixPs=" + canExecuteLocalUnixPs() - + ", canExecuteStandardUnixPs=" + canExecuteStandardUnixPs(); + if (IS_OS_UNIX) { + args += ", canExecuteLocalUnixPs=" + canExecuteLocalUnixPs() + ", canExecuteStandardUnixPs=" + + canExecuteStandardUnixPs(); } return "PpidChecker{" + args + '}'; diff --git a/surefire-booter/src/main/java/org/apache/maven/surefire/booter/ProcessCheckerType.java b/surefire-booter/src/main/java/org/apache/maven/surefire/booter/ProcessCheckerType.java index 03a0e880d4..9b49055a4d 100644 --- a/surefire-booter/src/main/java/org/apache/maven/surefire/booter/ProcessCheckerType.java +++ b/surefire-booter/src/main/java/org/apache/maven/surefire/booter/ProcessCheckerType.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.booter; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,22 +16,21 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.booter; import static org.apache.maven.surefire.shared.utils.StringUtils.isBlank; /** * */ -public enum ProcessCheckerType -{ - PING( "ping" ), - NATIVE( "native" ), - ALL( "all" ); +public enum ProcessCheckerType { + PING("ping"), + NATIVE("native"), + ALL("all"); private final String type; - ProcessCheckerType( String type ) - { + ProcessCheckerType(String type) { this.type = type; } @@ -43,38 +40,29 @@ public enum ProcessCheckerType * @param type ping, native, all * @return {@link ProcessCheckerType} */ - public static ProcessCheckerType toEnum( String type ) - { - if ( isBlank( type ) ) - { + public static ProcessCheckerType toEnum(String type) { + if (isBlank(type)) { return null; } - for ( ProcessCheckerType e : values() ) - { - if ( e.type.equals( type ) ) - { + for (ProcessCheckerType e : values()) { + if (e.type.equals(type)) { return e; } } - throw new IllegalArgumentException( "unknown process checker" ); + throw new IllegalArgumentException("unknown process checker"); } - public String getType() - { + public String getType() { return type; } - public static boolean isValid( String type ) - { - try - { - toEnum( type ); + public static boolean isValid(String type) { + try { + toEnum(type); return true; - } - catch ( IllegalArgumentException e ) - { + } catch (IllegalArgumentException e) { return false; } } diff --git a/surefire-booter/src/main/java/org/apache/maven/surefire/booter/ProcessInfo.java b/surefire-booter/src/main/java/org/apache/maven/surefire/booter/ProcessInfo.java index f86e2ce23a..7714459650 100644 --- a/surefire-booter/src/main/java/org/apache/maven/surefire/booter/ProcessInfo.java +++ b/surefire-booter/src/main/java/org/apache/maven/surefire/booter/ProcessInfo.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.booter; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.booter; import javax.annotation.Nonnull; @@ -32,81 +31,68 @@ * @author Tibor Digana (tibor17) * @since 2.20.1 */ -final class ProcessInfo -{ - static final ProcessInfo INVALID_PROCESS_INFO = new ProcessInfo( null, 0 ); - static final ProcessInfo ERR_PROCESS_INFO = new ProcessInfo( null, 0 ); +final class ProcessInfo { + static final ProcessInfo INVALID_PROCESS_INFO = new ProcessInfo(null, 0); + static final ProcessInfo ERR_PROCESS_INFO = new ProcessInfo(null, 0); /** * On Unix we do not get PID due to the command is interested only to etime of PPID: *
    *
    /bin/ps -o etime= -p 123
    */ - static @Nonnull ProcessInfo unixProcessInfo( String pid, long etime ) - { - return new ProcessInfo( pid, etime ); + static @Nonnull ProcessInfo unixProcessInfo(String pid, long etime) { + return new ProcessInfo(pid, etime); } - static @Nonnull ProcessInfo windowsProcessInfo( String pid, long startTimestamp ) - { - return new ProcessInfo( pid, startTimestamp ); + static @Nonnull ProcessInfo windowsProcessInfo(String pid, long startTimestamp) { + return new ProcessInfo(pid, startTimestamp); } private final String pid; private final long time; - private ProcessInfo( String pid, long time ) - { + private ProcessInfo(String pid, long time) { this.pid = pid; this.time = time; } - boolean canUse() - { + boolean canUse() { return !isError(); } - boolean isInvalid() - { + boolean isInvalid() { return this == INVALID_PROCESS_INFO; } - boolean isError() - { + boolean isError() { return this == ERR_PROCESS_INFO; } - String getPID() - { + String getPID() { checkValid(); return pid; } - long getTime() - { + long getTime() { checkValid(); return time; } - boolean isTimeEqualTo( ProcessInfo that ) - { + boolean isTimeEqualTo(ProcessInfo that) { checkValid(); that.checkValid(); return time == that.time; } - boolean isTimeBefore( ProcessInfo that ) - { + boolean isTimeBefore(ProcessInfo that) { checkValid(); that.checkValid(); return time < that.time; } - private void checkValid() - { - if ( !canUse() ) - { - throw new IllegalStateException( "invalid process info" ); + private void checkValid() { + if (!canUse()) { + throw new IllegalStateException("invalid process info"); } } } diff --git a/surefire-booter/src/main/java/org/apache/maven/surefire/booter/PropertiesWrapper.java b/surefire-booter/src/main/java/org/apache/maven/surefire/booter/PropertiesWrapper.java index b5cccf478f..91cdb4f8ce 100644 --- a/surefire-booter/src/main/java/org/apache/maven/surefire/booter/PropertiesWrapper.java +++ b/surefire-booter/src/main/java/org/apache/maven/surefire/booter/PropertiesWrapper.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.booter; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,88 +16,74 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.booter; import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.Map; + import org.apache.maven.surefire.shared.utils.StringUtils; /** * @author Kristian Rosenvold */ -public class PropertiesWrapper - implements KeyValueSource -{ +public class PropertiesWrapper implements KeyValueSource { private final Map properties; - public PropertiesWrapper( Map properties ) - { - if ( properties == null ) - { - throw new IllegalStateException( "Properties cannot be null" ); + public PropertiesWrapper(Map properties) { + if (properties == null) { + throw new IllegalStateException("Properties cannot be null"); } this.properties = properties; } - public Map getProperties() - { + public Map getProperties() { return properties; } - public void setAsSystemProperties() - { - for ( Map.Entry entry : properties.entrySet() ) - { - System.setProperty( entry.getKey(), entry.getValue() ); + public void setAsSystemProperties() { + for (Map.Entry entry : properties.entrySet()) { + System.setProperty(entry.getKey(), entry.getValue()); } } - public String getProperty( String key ) - { - return properties.get( key ); + public String getProperty(String key) { + return properties.get(key); } - public boolean getBooleanProperty( String propertyName ) - { - return Boolean.parseBoolean( properties.get( propertyName ) ); + public boolean getBooleanProperty(String propertyName) { + return Boolean.parseBoolean(properties.get(propertyName)); } - public int getIntProperty( String propertyName ) - { - return Integer.parseInt( properties.get( propertyName ) ); + public int getIntProperty(String propertyName) { + return Integer.parseInt(properties.get(propertyName)); } - public Long getLongProperty( String propertyName ) - { - String number = getProperty( propertyName ); - return number == null ? null : Long.parseLong( number ); + public Long getLongProperty(String propertyName) { + String number = getProperty(propertyName); + return number == null ? null : Long.parseLong(number); } - public File getFileProperty( String key ) - { - final String property = getProperty( key ); - if ( property == null ) - { + public File getFileProperty(String key) { + final String property = getProperty(key); + if (property == null) { return null; } - TypeEncodedValue typeEncodedValue = new TypeEncodedValue( File.class.getName(), property ); + TypeEncodedValue typeEncodedValue = new TypeEncodedValue(File.class.getName(), property); return (File) typeEncodedValue.getDecodedValue(); } - public List getStringList( String propertyPrefix ) - { + public List getStringList(String propertyPrefix) { List result = new ArrayList<>(); - for ( int i = 0; ; i++ ) - { - String value = getProperty( propertyPrefix + i ); + for (int i = 0; ; i++) { + String value = getProperty(propertyPrefix + i); - if ( value == null ) - { + if (value == null) { return result; } - result.add( value ); + result.add(value); } } @@ -109,64 +93,49 @@ public List getStringList( String propertyPrefix ) * @param key The key for the propery * @return The object, of a supported type */ - public TypeEncodedValue getTypeEncodedValue( String key ) - { - String typeEncoded = getProperty( key ); - if ( typeEncoded != null ) - { - int typeSep = typeEncoded.indexOf( "|" ); - String type = typeEncoded.substring( 0, typeSep ); - String value = typeEncoded.substring( typeSep + 1 ); - return new TypeEncodedValue( type, value ); - } - else - { + public TypeEncodedValue getTypeEncodedValue(String key) { + String typeEncoded = getProperty(key); + if (typeEncoded != null) { + int typeSep = typeEncoded.indexOf("|"); + String type = typeEncoded.substring(0, typeSep); + String value = typeEncoded.substring(typeSep + 1); + return new TypeEncodedValue(type, value); + } else { return null; } } - Classpath getClasspath( String prefix ) - { - List elements = getStringList( prefix ); - return new Classpath( elements ); + Classpath getClasspath(String prefix) { + List elements = getStringList(prefix); + return new Classpath(elements); } - public void setClasspath( String prefix, Classpath classpath ) - { + public void setClasspath(String prefix, Classpath classpath) { List classpathElements = classpath.getClassPath(); - for ( int i = 0, size = classpathElements.size(); i < size; ++i ) - { - String element = (String) classpathElements.get( i ); - setProperty( prefix + i, element ); + for (int i = 0, size = classpathElements.size(); i < size; ++i) { + String element = (String) classpathElements.get(i); + setProperty(prefix + i, element); } } - - public void setProperty( String key, String value ) - { - if ( value != null ) - { - properties.put( key, value ); + public void setProperty(String key, String value) { + if (value != null) { + properties.put(key, value); } } - public void addList( List items, String propertyPrefix ) - { - if ( items != null && !items.isEmpty() ) - { + public void addList(List items, String propertyPrefix) { + if (items != null && !items.isEmpty()) { int i = 0; - for ( Object item : items ) - { - if ( item == null ) - { - throw new NullPointerException( propertyPrefix + i + " has null value" ); + for (Object item : items) { + if (item == null) { + throw new NullPointerException(propertyPrefix + i + " has null value"); } - String[] stringArray = StringUtils.split( item.toString(), "," ); + String[] stringArray = StringUtils.split(item.toString(), ","); - for ( String aStringArray : stringArray ) - { - properties.put( propertyPrefix + i, aStringArray ); + for (String aStringArray : stringArray) { + properties.put(propertyPrefix + i, aStringArray); i++; } } @@ -174,8 +143,7 @@ public void addList( List items, String propertyPrefix ) } @Override - public void copyTo( Map target ) - { - target.putAll( properties ); + public void copyTo(Map target) { + target.putAll(properties); } } diff --git a/surefire-booter/src/main/java/org/apache/maven/surefire/booter/ProviderConfiguration.java b/surefire-booter/src/main/java/org/apache/maven/surefire/booter/ProviderConfiguration.java index fd0effc45d..9c99626e70 100644 --- a/surefire-booter/src/main/java/org/apache/maven/surefire/booter/ProviderConfiguration.java +++ b/surefire-booter/src/main/java/org/apache/maven/surefire/booter/ProviderConfiguration.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.booter; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.booter; import java.io.File; import java.util.List; @@ -40,8 +39,7 @@ * @author Emmanuel Venisse * @author Kristian Rosenvold */ -public class ProviderConfiguration -{ +public class ProviderConfiguration { private final DirectoryScannerParameters dirScannerParams; private final ReporterConfiguration reporterConfiguration; @@ -66,15 +64,20 @@ public class ProviderConfiguration private final Integer systemExitTimeout; - @SuppressWarnings( "checkstyle:parameternumber" ) - public ProviderConfiguration( DirectoryScannerParameters directoryScannerParameters, - RunOrderParameters runOrderParameters, - ReporterConfiguration reporterConfiguration, TestArtifactInfo testArtifact, - TestRequest testSuiteDefinition, Map providerProperties, - TypeEncodedValue typeEncodedTestSet, boolean readTestsFromInStream, - List mainCliOptions, int skipAfterFailureCount, - Shutdown shutdown, Integer systemExitTimeout ) - { + @SuppressWarnings("checkstyle:parameternumber") + public ProviderConfiguration( + DirectoryScannerParameters directoryScannerParameters, + RunOrderParameters runOrderParameters, + ReporterConfiguration reporterConfiguration, + TestArtifactInfo testArtifact, + TestRequest testSuiteDefinition, + Map providerProperties, + TypeEncodedValue typeEncodedTestSet, + boolean readTestsFromInStream, + List mainCliOptions, + int skipAfterFailureCount, + Shutdown shutdown, + Integer systemExitTimeout) { this.runOrderParameters = runOrderParameters; this.providerProperties = providerProperties; this.reporterConfiguration = reporterConfiguration; @@ -89,85 +92,69 @@ public ProviderConfiguration( DirectoryScannerParameters directoryScannerParamet this.systemExitTimeout = systemExitTimeout; } - public ReporterConfiguration getReporterConfiguration() - { + public ReporterConfiguration getReporterConfiguration() { return reporterConfiguration; } - public File getBaseDir() - { + public File getBaseDir() { return dirScannerParams.getTestClassesDirectory(); } - public DirectoryScannerParameters getDirScannerParams() - { + public DirectoryScannerParameters getDirScannerParams() { return dirScannerParams; } @Deprecated - public List getIncludes() - { + public List getIncludes() { return dirScannerParams.getIncludes(); } @Deprecated - public List getExcludes() - { + public List getExcludes() { return dirScannerParams.getExcludes(); } - public TestArtifactInfo getTestArtifact() - { + public TestArtifactInfo getTestArtifact() { return testArtifact; } - public TestRequest getTestSuiteDefinition() - { + public TestRequest getTestSuiteDefinition() { return testSuiteDefinition; } - public Map getProviderProperties() - { + public Map getProviderProperties() { return providerProperties; } - public TypeEncodedValue getTestForFork() - { + public TypeEncodedValue getTestForFork() { return forkTestSet; } - public RunOrderParameters getRunOrderParameters() - { + public RunOrderParameters getRunOrderParameters() { return runOrderParameters; } - public boolean isReadTestsFromInStream() - { + public boolean isReadTestsFromInStream() { return readTestsFromInStream; } - public List getMainCliOptions() - { + public List getMainCliOptions() { return mainCliOptions; } - public int getSkipAfterFailureCount() - { + public int getSkipAfterFailureCount() { return skipAfterFailureCount; } - public Shutdown getShutdown() - { + public Shutdown getShutdown() { return shutdown; } - public Integer getSystemExitTimeout() - { + public Integer getSystemExitTimeout() { return systemExitTimeout; } - public long systemExitTimeout( long fallback ) - { + public long systemExitTimeout(long fallback) { return systemExitTimeout == null || systemExitTimeout < 0 ? fallback : systemExitTimeout; } } diff --git a/surefire-booter/src/main/java/org/apache/maven/surefire/booter/ProviderFactory.java b/surefire-booter/src/main/java/org/apache/maven/surefire/booter/ProviderFactory.java index 43461df686..df0741452f 100644 --- a/surefire-booter/src/main/java/org/apache/maven/surefire/booter/ProviderFactory.java +++ b/surefire-booter/src/main/java/org/apache/maven/surefire/booter/ProviderFactory.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.booter; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.booter; import java.io.PrintStream; import java.lang.reflect.InvocationTargetException; @@ -40,8 +39,7 @@ * * @author Kristian Rosenvold */ -public class ProviderFactory -{ +public class ProviderFactory { private final StartupConfiguration startupConfiguration; private final ProviderConfiguration providerConfiguration; @@ -52,137 +50,121 @@ public class ProviderFactory private final Object reporterManagerFactory; - private static final Class[] INVOKE_PARAMETERS = { Object.class }; + private static final Class[] INVOKE_PARAMETERS = {Object.class}; - private static final Class[] INVOKE_EMPTY_PARAMETER_TYPES = { }; + private static final Class[] INVOKE_EMPTY_PARAMETER_TYPES = {}; - private static final Object[] INVOKE_EMPTY_PARAMETERS = { }; + private static final Object[] INVOKE_EMPTY_PARAMETERS = {}; - public ProviderFactory( StartupConfiguration startupConfiguration, ProviderConfiguration providerConfiguration, - ClassLoader testsClassLoader, Object reporterManagerFactory ) - { + public ProviderFactory( + StartupConfiguration startupConfiguration, + ProviderConfiguration providerConfiguration, + ClassLoader testsClassLoader, + Object reporterManagerFactory) { this.providerConfiguration = providerConfiguration; this.startupConfiguration = startupConfiguration; - this.surefireReflector = new SurefireReflector( testsClassLoader ); + this.surefireReflector = new SurefireReflector(testsClassLoader); this.classLoader = testsClassLoader; this.reporterManagerFactory = reporterManagerFactory; } - public static RunResult invokeProvider( Object testSet, ClassLoader testsClassLoader, Object factory, - ProviderConfiguration providerConfiguration, boolean insideFork, - StartupConfiguration startupConfig, boolean restoreStreams ) - throws TestSetFailedException, InvocationTargetException - { + public static RunResult invokeProvider( + Object testSet, + ClassLoader testsClassLoader, + Object factory, + ProviderConfiguration providerConfiguration, + boolean insideFork, + StartupConfiguration startupConfig, + boolean restoreStreams) + throws TestSetFailedException, InvocationTargetException { final PrintStream orgSystemOut = System.out; final PrintStream orgSystemErr = System.err; // Note that System.out/System.err are also read in the "ReporterConfiguration" instantiation // in createProvider below. These are the same values as here. - try - { - return new ProviderFactory( startupConfig, providerConfiguration, testsClassLoader, factory ) - .createProvider( insideFork ) - .invoke( testSet ); - } - finally - { - if ( restoreStreams && ( !isSecurityManagerSupported() || System.getSecurityManager() == null ) ) - { - System.setOut( orgSystemOut ); - System.setErr( orgSystemErr ); + try { + return new ProviderFactory(startupConfig, providerConfiguration, testsClassLoader, factory) + .createProvider(insideFork) + .invoke(testSet); + } finally { + if (restoreStreams && (!isSecurityManagerSupported() || System.getSecurityManager() == null)) { + System.setOut(orgSystemOut); + System.setErr(orgSystemErr); } } } - public SurefireProvider createProvider( boolean isInsideFork ) - { + public SurefireProvider createProvider(boolean isInsideFork) { final Thread currentThread = Thread.currentThread(); final ClassLoader systemClassLoader = currentThread.getContextClassLoader(); - currentThread.setContextClassLoader( classLoader ); + currentThread.setContextClassLoader(classLoader); // Note: Duplicated in ForkedBooter#createProviderInCurrentClassloader - Object o = surefireReflector.createBooterConfiguration( classLoader, isInsideFork ); - surefireReflector.setReporterFactoryAware( o, reporterManagerFactory ); - surefireReflector.setTestSuiteDefinitionAware( o, providerConfiguration.getTestSuiteDefinition() ); - surefireReflector.setProviderPropertiesAware( o, providerConfiguration.getProviderProperties() ); - surefireReflector.setReporterConfigurationAware( o, providerConfiguration.getReporterConfiguration() ); - surefireReflector.setTestClassLoaderAware( o, classLoader ); - surefireReflector.setTestArtifactInfoAware( o, providerConfiguration.getTestArtifact() ); - surefireReflector.setRunOrderParameters( o, providerConfiguration.getRunOrderParameters() ); - surefireReflector.setIfDirScannerAware( o, providerConfiguration.getDirScannerParams() ); - surefireReflector.setMainCliOptions( o, providerConfiguration.getMainCliOptions() ); - surefireReflector.setSkipAfterFailureCount( o, providerConfiguration.getSkipAfterFailureCount() ); - if ( isInsideFork ) - { - surefireReflector.setSystemExitTimeout( o, providerConfiguration.getSystemExitTimeout() ); + Object o = surefireReflector.createBooterConfiguration(classLoader, isInsideFork); + surefireReflector.setReporterFactoryAware(o, reporterManagerFactory); + surefireReflector.setTestSuiteDefinitionAware(o, providerConfiguration.getTestSuiteDefinition()); + surefireReflector.setProviderPropertiesAware(o, providerConfiguration.getProviderProperties()); + surefireReflector.setReporterConfigurationAware(o, providerConfiguration.getReporterConfiguration()); + surefireReflector.setTestClassLoaderAware(o, classLoader); + surefireReflector.setTestArtifactInfoAware(o, providerConfiguration.getTestArtifact()); + surefireReflector.setRunOrderParameters(o, providerConfiguration.getRunOrderParameters()); + surefireReflector.setIfDirScannerAware(o, providerConfiguration.getDirScannerParams()); + surefireReflector.setMainCliOptions(o, providerConfiguration.getMainCliOptions()); + surefireReflector.setSkipAfterFailureCount(o, providerConfiguration.getSkipAfterFailureCount()); + if (isInsideFork) { + surefireReflector.setSystemExitTimeout(o, providerConfiguration.getSystemExitTimeout()); } - Object provider = surefireReflector.instantiateProvider( startupConfiguration.getActualClassName(), o ); - currentThread.setContextClassLoader( systemClassLoader ); + Object provider = surefireReflector.instantiateProvider(startupConfiguration.getActualClassName(), o); + currentThread.setContextClassLoader(systemClassLoader); - return new ProviderProxy( provider, classLoader ); + return new ProviderProxy(provider, classLoader); } - private final class ProviderProxy - implements SurefireProvider - { + private final class ProviderProxy implements SurefireProvider { private final Object providerInOtherClassLoader; private final ClassLoader testsClassLoader; - - private ProviderProxy( Object providerInOtherClassLoader, ClassLoader testsClassLoader ) - { + private ProviderProxy(Object providerInOtherClassLoader, ClassLoader testsClassLoader) { this.providerInOtherClassLoader = providerInOtherClassLoader; this.testsClassLoader = testsClassLoader; } @Override - public Iterable> getSuites() - { - ClassLoader current = swapClassLoader( testsClassLoader ); - try - { - return invokeGetter( providerInOtherClassLoader, "getSuites" ); - } - finally - { - Thread.currentThread().setContextClassLoader( current ); + public Iterable> getSuites() { + ClassLoader current = swapClassLoader(testsClassLoader); + try { + return invokeGetter(providerInOtherClassLoader, "getSuites"); + } finally { + Thread.currentThread().setContextClassLoader(current); } } @Override - public RunResult invoke( Object forkTestSet ) - throws ReporterException, InvocationTargetException - { - ClassLoader current = swapClassLoader( testsClassLoader ); - try - { - Method invoke = getMethod( providerInOtherClassLoader.getClass(), "invoke", INVOKE_PARAMETERS ); - Object result = invokeMethodWithArray2( providerInOtherClassLoader, invoke, forkTestSet ); - return (RunResult) surefireReflector.convertIfRunResult( result ); - } - finally - { - if ( System.getSecurityManager() == null ) - { - Thread.currentThread().setContextClassLoader( current ); + public RunResult invoke(Object forkTestSet) throws ReporterException, InvocationTargetException { + ClassLoader current = swapClassLoader(testsClassLoader); + try { + Method invoke = getMethod(providerInOtherClassLoader.getClass(), "invoke", INVOKE_PARAMETERS); + Object result = invokeMethodWithArray2(providerInOtherClassLoader, invoke, forkTestSet); + return (RunResult) surefireReflector.convertIfRunResult(result); + } finally { + if (System.getSecurityManager() == null) { + Thread.currentThread().setContextClassLoader(current); } } } - private ClassLoader swapClassLoader( ClassLoader newClassLoader ) - { + private ClassLoader swapClassLoader(ClassLoader newClassLoader) { ClassLoader current = Thread.currentThread().getContextClassLoader(); - Thread.currentThread().setContextClassLoader( newClassLoader ); + Thread.currentThread().setContextClassLoader(newClassLoader); return current; } @Override - public void cancel() - { + public void cancel() { Class providerType = providerInOtherClassLoader.getClass(); - Method invoke = getMethod( providerType, "cancel", INVOKE_EMPTY_PARAMETER_TYPES ); - invokeMethodWithArray( providerInOtherClassLoader, invoke, INVOKE_EMPTY_PARAMETERS ); + Method invoke = getMethod(providerType, "cancel", INVOKE_EMPTY_PARAMETER_TYPES); + invokeMethodWithArray(providerInOtherClassLoader, invoke, INVOKE_EMPTY_PARAMETERS); } } } diff --git a/surefire-booter/src/main/java/org/apache/maven/surefire/booter/StartupConfiguration.java b/surefire-booter/src/main/java/org/apache/maven/surefire/booter/StartupConfiguration.java index 7a9d1e4925..2881b0a335 100644 --- a/surefire-booter/src/main/java/org/apache/maven/surefire/booter/StartupConfiguration.java +++ b/surefire-booter/src/main/java/org/apache/maven/surefire/booter/StartupConfiguration.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.booter; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,8 +16,10 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.booter; import javax.annotation.Nonnull; + import java.util.Collections; import java.util.List; @@ -28,8 +28,7 @@ * * @author Kristian Rosenvold */ -public class StartupConfiguration -{ +public class StartupConfiguration { private static final String SUREFIRE_TEST_CLASSPATH = "surefire.test.class.path"; private final String providerClassName; @@ -38,12 +37,12 @@ public class StartupConfiguration private final ProcessCheckerType processChecker; private final List jpmsArguments; - public StartupConfiguration( @Nonnull String providerClassName, - @Nonnull AbstractPathConfiguration classpathConfiguration, - @Nonnull ClassLoaderConfiguration classLoaderConfiguration, - ProcessCheckerType processChecker, - @Nonnull List jpmsArguments ) - { + public StartupConfiguration( + @Nonnull String providerClassName, + @Nonnull AbstractPathConfiguration classpathConfiguration, + @Nonnull ClassLoaderConfiguration classLoaderConfiguration, + ProcessCheckerType processChecker, + @Nonnull List jpmsArguments) { this.classpathConfiguration = classpathConfiguration; this.classLoaderConfiguration = classLoaderConfiguration; this.providerClassName = providerClassName; @@ -51,38 +50,37 @@ public StartupConfiguration( @Nonnull String providerClassName, this.jpmsArguments = jpmsArguments; } - public boolean isProviderMainClass() - { - return providerClassName.endsWith( "#main" ); + public boolean isProviderMainClass() { + return providerClassName.endsWith("#main"); } - public static StartupConfiguration inForkedVm( String providerClassName, - ClasspathConfiguration classpathConfig, - ClassLoaderConfiguration classLoaderConfig, - ProcessCheckerType processChecker ) - { - return new StartupConfiguration( providerClassName, classpathConfig, classLoaderConfig, - processChecker, Collections.emptyList() ); + public static StartupConfiguration inForkedVm( + String providerClassName, + ClasspathConfiguration classpathConfig, + ClassLoaderConfiguration classLoaderConfig, + ProcessCheckerType processChecker) { + return new StartupConfiguration( + providerClassName, + classpathConfig, + classLoaderConfig, + processChecker, + Collections.emptyList()); } - public AbstractPathConfiguration getClasspathConfiguration() - { + public AbstractPathConfiguration getClasspathConfiguration() { return classpathConfiguration; } - public boolean isManifestOnlyJarRequestedAndUsable() - { + public boolean isManifestOnlyJarRequestedAndUsable() { return classLoaderConfiguration.isManifestOnlyJarRequestedAndUsable(); } - public String getProviderClassName() - { + public String getProviderClassName() { return providerClassName; } - public String getActualClassName() - { - return isProviderMainClass() ? stripEnd( providerClassName, "#main" ) : providerClassName; + public String getActualClassName() { + return isProviderMainClass() ? stripEnd(providerClassName, "#main") : providerClassName; } /** @@ -95,53 +93,41 @@ public String getActualClassName() * @param strip the String to remove * @return the stripped String */ - private static String stripEnd( String str, String strip ) - { - if ( str == null ) - { + private static String stripEnd(String str, String strip) { + if (str == null) { return null; } int end = str.length(); - if ( strip == null ) - { - while ( ( end != 0 ) && Character.isWhitespace( str.charAt( end - 1 ) ) ) - { + if (strip == null) { + while ((end != 0) && Character.isWhitespace(str.charAt(end - 1))) { end--; } - } - else - { - while ( end != 0 && strip.indexOf( str.charAt( end - 1 ) ) != -1 ) - { + } else { + while (end != 0 && strip.indexOf(str.charAt(end - 1)) != -1) { end--; } } - return str.substring( 0, end ); + return str.substring(0, end); } - public ClassLoaderConfiguration getClassLoaderConfiguration() - { + public ClassLoaderConfiguration getClassLoaderConfiguration() { return classLoaderConfiguration; } - public boolean isShadefire() - { - return providerClassName.startsWith( "org.apache.maven.shadefire.surefire" ); + public boolean isShadefire() { + return providerClassName.startsWith("org.apache.maven.shadefire.surefire"); } - public void writeSurefireTestClasspathProperty() - { - getClasspathConfiguration().getTestClasspath().writeToSystemProperty( SUREFIRE_TEST_CLASSPATH ); + public void writeSurefireTestClasspathProperty() { + getClasspathConfiguration().getTestClasspath().writeToSystemProperty(SUREFIRE_TEST_CLASSPATH); } - public ProcessCheckerType getProcessChecker() - { + public ProcessCheckerType getProcessChecker() { return processChecker; } - public List getJpmsArguments() - { + public List getJpmsArguments() { return jpmsArguments; } } diff --git a/surefire-booter/src/main/java/org/apache/maven/surefire/booter/SurefireBooterForkException.java b/surefire-booter/src/main/java/org/apache/maven/surefire/booter/SurefireBooterForkException.java index bae4ed0867..56c5e44081 100644 --- a/surefire-booter/src/main/java/org/apache/maven/surefire/booter/SurefireBooterForkException.java +++ b/surefire-booter/src/main/java/org/apache/maven/surefire/booter/SurefireBooterForkException.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.booter; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,7 +16,7 @@ * specific language governing permissions and limitations * under the License. */ - +package org.apache.maven.surefire.booter; import org.apache.maven.surefire.api.suite.RunResult; @@ -27,62 +25,51 @@ /** * Encapsulates exceptions thrown during Surefire forking. */ -public class SurefireBooterForkException - extends Exception -{ - public SurefireBooterForkException( String message, RunResult runResult ) - { - this( message, null, null, runResult ); +public class SurefireBooterForkException extends Exception { + public SurefireBooterForkException(String message, RunResult runResult) { + this(message, null, null, runResult); } - public SurefireBooterForkException( String message, String rethrownMessage, Throwable rethrownCause, - RunResult runResult ) - { - super( toString( message, rethrownMessage, rethrownCause, runResult ), rethrownCause ); + public SurefireBooterForkException( + String message, String rethrownMessage, Throwable rethrownCause, RunResult runResult) { + super(toString(message, rethrownMessage, rethrownCause, runResult), rethrownCause); } - public SurefireBooterForkException( String message, Throwable cause ) - { - super( message, cause ); + public SurefireBooterForkException(String message, Throwable cause) { + super(message, cause); } - public SurefireBooterForkException( String msg ) - { - super( msg ); + public SurefireBooterForkException(String msg) { + super(msg); } - private static String toString( String message, String rethrownMessage, Throwable rethrownCause, - RunResult runResult ) - { - return toNewLines( message, - rethrownMessage, - rethrownCause == null ? null : rethrownCause.getLocalizedMessage(), - runResult == null ? null : runResult.getFailure(), - runResult == null ? null : toString( runResult ) ); + private static String toString( + String message, String rethrownMessage, Throwable rethrownCause, RunResult runResult) { + return toNewLines( + message, + rethrownMessage, + rethrownCause == null ? null : rethrownCause.getLocalizedMessage(), + runResult == null ? null : runResult.getFailure(), + runResult == null ? null : toString(runResult)); } - private static String toString( RunResult runResult ) - { + private static String toString(RunResult runResult) { return "Fatal Tests run: " + runResult.getCompletedCount() - + ", Failures: " + runResult.getFailures() - + ", Errors: " + runResult.getErrors() - + ", Skipped: " + runResult.getSkipped() - + ", Flakes: " + runResult.getFlakes() - + ", Elapsed timeout: " + runResult.isTimeout(); + + ", Failures: " + runResult.getFailures() + + ", Errors: " + runResult.getErrors() + + ", Skipped: " + runResult.getSkipped() + + ", Flakes: " + runResult.getFlakes() + + ", Elapsed timeout: " + runResult.isTimeout(); } - private static String toNewLines( String... messages ) - { + private static String toNewLines(String... messages) { StringBuilder result = new StringBuilder(); - for ( String message : messages ) - { - if ( isNotBlank( message ) ) - { - if ( result.length() == 0 ) - { - result.append( '\n' ); + for (String message : messages) { + if (isNotBlank(message)) { + if (result.length() == 0) { + result.append('\n'); } - result.append( message ); + result.append(message); } } return result.toString(); diff --git a/surefire-booter/src/main/java/org/apache/maven/surefire/booter/SurefireExecutionException.java b/surefire-booter/src/main/java/org/apache/maven/surefire/booter/SurefireExecutionException.java index 9a0af3bc7e..690be3b569 100644 --- a/surefire-booter/src/main/java/org/apache/maven/surefire/booter/SurefireExecutionException.java +++ b/surefire-booter/src/main/java/org/apache/maven/surefire/booter/SurefireExecutionException.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.booter; /* @@ -19,17 +37,13 @@ * under the License. */ - /** * An error occurring during the invocation of Surefire via an alternate class loader. * * @author Brett Porter */ -public class SurefireExecutionException - extends Exception -{ - public SurefireExecutionException( String message, Throwable nested ) - { - super( message, nested ); +public class SurefireExecutionException extends Exception { + public SurefireExecutionException(String message, Throwable nested) { + super(message, nested); } } diff --git a/surefire-booter/src/main/java/org/apache/maven/surefire/booter/SurefireReflector.java b/surefire-booter/src/main/java/org/apache/maven/surefire/booter/SurefireReflector.java index 2df77b0c06..0f0f99b289 100644 --- a/surefire-booter/src/main/java/org/apache/maven/surefire/booter/SurefireReflector.java +++ b/surefire-booter/src/main/java/org/apache/maven/surefire/booter/SurefireReflector.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.booter; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,15 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.booter; + +import java.io.File; +import java.lang.reflect.Constructor; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.Map; import org.apache.maven.surefire.api.booter.BaseProviderFactory; import org.apache.maven.surefire.api.cli.CommandLineOption; @@ -33,14 +40,6 @@ import org.apache.maven.surefire.api.util.RunOrder; import org.apache.maven.surefire.api.util.SurefireReflectionException; -import java.io.File; -import java.lang.reflect.Constructor; -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import java.util.Map; - import static java.util.Collections.checkedList; import static org.apache.maven.surefire.api.util.ReflectionUtils.getConstructor; import static org.apache.maven.surefire.api.util.ReflectionUtils.getMethod; @@ -57,8 +56,7 @@ * * @author Kristian Rosenvold */ -public final class SurefireReflector -{ +public final class SurefireReflector { private final ClassLoader surefireClassLoader; private final Class reporterConfiguration; @@ -83,274 +81,224 @@ public final class SurefireReflector private final Class> commandLineOptionsClass; - @SuppressWarnings( "unchecked" ) - public SurefireReflector( ClassLoader surefireClassLoader ) - { + @SuppressWarnings("unchecked") + public SurefireReflector(ClassLoader surefireClassLoader) { this.surefireClassLoader = surefireClassLoader; - try - { - reporterConfiguration = surefireClassLoader.loadClass( ReporterConfiguration.class.getName() ); - testRequest = surefireClassLoader.loadClass( TestRequest.class.getName() ); - testArtifactInfo = surefireClassLoader.loadClass( TestArtifactInfo.class.getName() ); - directoryScannerParameters = surefireClassLoader.loadClass( DirectoryScannerParameters.class.getName() ); - runOrderParameters = surefireClassLoader.loadClass( RunOrderParameters.class.getName() ); - baseProviderFactory = surefireClassLoader.loadClass( BaseProviderFactory.class.getName() ); - reporterFactory = surefireClassLoader.loadClass( ReporterFactory.class.getName() ); - runResult = surefireClassLoader.loadClass( RunResult.class.getName() ); - booterParameters = surefireClassLoader.loadClass( ProviderParameters.class.getName() ); - testListResolver = surefireClassLoader.loadClass( TestListResolver.class.getName() ); - commandLineOptionsClass = - (Class>) surefireClassLoader.loadClass( CommandLineOption.class.getName() ); - } - catch ( ClassNotFoundException e ) - { - throw new SurefireReflectionException( e ); + try { + reporterConfiguration = surefireClassLoader.loadClass(ReporterConfiguration.class.getName()); + testRequest = surefireClassLoader.loadClass(TestRequest.class.getName()); + testArtifactInfo = surefireClassLoader.loadClass(TestArtifactInfo.class.getName()); + directoryScannerParameters = surefireClassLoader.loadClass(DirectoryScannerParameters.class.getName()); + runOrderParameters = surefireClassLoader.loadClass(RunOrderParameters.class.getName()); + baseProviderFactory = surefireClassLoader.loadClass(BaseProviderFactory.class.getName()); + reporterFactory = surefireClassLoader.loadClass(ReporterFactory.class.getName()); + runResult = surefireClassLoader.loadClass(RunResult.class.getName()); + booterParameters = surefireClassLoader.loadClass(ProviderParameters.class.getName()); + testListResolver = surefireClassLoader.loadClass(TestListResolver.class.getName()); + commandLineOptionsClass = (Class>) surefireClassLoader.loadClass(CommandLineOption.class.getName()); + } catch (ClassNotFoundException e) { + throw new SurefireReflectionException(e); } } - public Object convertIfRunResult( Object result ) - { - if ( result == null || !isRunResult( result ) ) - { + public Object convertIfRunResult(Object result) { + if (result == null || !isRunResult(result)) { return result; } - int getCompletedCount1 = invokeGetter( result, "getCompletedCount" ); - int getErrors = invokeGetter( result, "getErrors" ); - int getSkipped = invokeGetter( result, "getSkipped" ); - int getFailures = invokeGetter( result, "getFailures" ); - return new RunResult( getCompletedCount1, getErrors, getFailures, getSkipped ); + int getCompletedCount1 = invokeGetter(result, "getCompletedCount"); + int getErrors = invokeGetter(result, "getErrors"); + int getSkipped = invokeGetter(result, "getSkipped"); + int getFailures = invokeGetter(result, "getFailures"); + return new RunResult(getCompletedCount1, getErrors, getFailures, getSkipped); } - private Object createTestRequest( TestRequest suiteDefinition ) - { - if ( suiteDefinition == null ) - { + private Object createTestRequest(TestRequest suiteDefinition) { + if (suiteDefinition == null) { return null; - } - else - { - Object resolver = createTestListResolver( suiteDefinition.getTestListResolver() ); - Class[] arguments = { List.class, File.class, testListResolver, int.class }; - Constructor constructor = getConstructor( testRequest, arguments ); - return newInstance( constructor, - suiteDefinition.getSuiteXmlFiles(), - suiteDefinition.getTestSourceDirectory(), - resolver, - suiteDefinition.getRerunFailingTestsCount() ); + } else { + Object resolver = createTestListResolver(suiteDefinition.getTestListResolver()); + Class[] arguments = {List.class, File.class, testListResolver, int.class}; + Constructor constructor = getConstructor(testRequest, arguments); + return newInstance( + constructor, + suiteDefinition.getSuiteXmlFiles(), + suiteDefinition.getTestSourceDirectory(), + resolver, + suiteDefinition.getRerunFailingTestsCount()); } } - private Object createTestListResolver( TestListResolver resolver ) - { - if ( resolver == null ) - { + private Object createTestListResolver(TestListResolver resolver) { + if (resolver == null) { return null; - } - else - { - Constructor constructor = getConstructor( testListResolver, String.class ); - return newInstance( constructor, resolver.getPluginParameterTest() ); + } else { + Constructor constructor = getConstructor(testListResolver, String.class); + return newInstance(constructor, resolver.getPluginParameterTest()); } } - private Object createDirectoryScannerParameters( DirectoryScannerParameters directoryScannerParameters ) - { - if ( directoryScannerParameters == null ) - { + private Object createDirectoryScannerParameters(DirectoryScannerParameters directoryScannerParameters) { + if (directoryScannerParameters == null) { return null; } - //Can't use the constructor with the RunOrder parameter. Using it causes some integration tests to fail. - Class[] arguments = { File.class, List.class, List.class, List.class, String.class }; - Constructor constructor = getConstructor( this.directoryScannerParameters, arguments ); - return newInstance( constructor, - directoryScannerParameters.getTestClassesDirectory(), - directoryScannerParameters.getIncludes(), - directoryScannerParameters.getExcludes(), - directoryScannerParameters.getSpecificTests(), - RunOrder.asString( directoryScannerParameters.getRunOrder() ) ); + // Can't use the constructor with the RunOrder parameter. Using it causes some integration tests to fail. + Class[] arguments = {File.class, List.class, List.class, List.class, String.class}; + Constructor constructor = getConstructor(this.directoryScannerParameters, arguments); + return newInstance( + constructor, + directoryScannerParameters.getTestClassesDirectory(), + directoryScannerParameters.getIncludes(), + directoryScannerParameters.getExcludes(), + directoryScannerParameters.getSpecificTests(), + RunOrder.asString(directoryScannerParameters.getRunOrder())); } - private Object createRunOrderParameters( RunOrderParameters runOrderParameters ) - { - if ( runOrderParameters == null ) - { + private Object createRunOrderParameters(RunOrderParameters runOrderParameters) { + if (runOrderParameters == null) { return null; } - //Can't use the constructor with the RunOrder parameter. Using it causes some integration tests to fail. - Class[] arguments = { String.class, File.class, Long.class }; - Constructor constructor = getConstructor( this.runOrderParameters, arguments ); + // Can't use the constructor with the RunOrder parameter. Using it causes some integration tests to fail. + Class[] arguments = {String.class, File.class, Long.class}; + Constructor constructor = getConstructor(this.runOrderParameters, arguments); File runStatisticsFile = runOrderParameters.getRunStatisticsFile(); - return newInstance( constructor, RunOrder.asString( runOrderParameters.getRunOrder() ), runStatisticsFile, - runOrderParameters.getRunOrderRandomSeed() ); + return newInstance( + constructor, + RunOrder.asString(runOrderParameters.getRunOrder()), + runStatisticsFile, + runOrderParameters.getRunOrderRandomSeed()); } - private Object createTestArtifactInfo( TestArtifactInfo testArtifactInfo ) - { - if ( testArtifactInfo == null ) - { + private Object createTestArtifactInfo(TestArtifactInfo testArtifactInfo) { + if (testArtifactInfo == null) { return null; } - Class[] arguments = { String.class, String.class }; - Constructor constructor = getConstructor( this.testArtifactInfo, arguments ); - return newInstance( constructor, testArtifactInfo.getVersion(), testArtifactInfo.getClassifier() ); + Class[] arguments = {String.class, String.class}; + Constructor constructor = getConstructor(this.testArtifactInfo, arguments); + return newInstance(constructor, testArtifactInfo.getVersion(), testArtifactInfo.getClassifier()); } - private Object createReporterConfiguration( ReporterConfiguration reporterConfig ) - { - Constructor constructor = getConstructor( reporterConfiguration, File.class, boolean.class ); - return newInstance( constructor, reporterConfig.getReportsDirectory(), reporterConfig.isTrimStackTrace() ); + private Object createReporterConfiguration(ReporterConfiguration reporterConfig) { + Constructor constructor = getConstructor(reporterConfiguration, File.class, boolean.class); + return newInstance(constructor, reporterConfig.getReportsDirectory(), reporterConfig.isTrimStackTrace()); } - public Object createBooterConfiguration( ClassLoader surefireClassLoader, boolean insideFork ) - { - return instantiateOneArg( surefireClassLoader, BaseProviderFactory.class.getName(), boolean.class, insideFork ); + public Object createBooterConfiguration(ClassLoader surefireClassLoader, boolean insideFork) { + return instantiateOneArg(surefireClassLoader, BaseProviderFactory.class.getName(), boolean.class, insideFork); } - public Object instantiateProvider( String providerClassName, Object booterParameters ) - { - return instantiateOneArg( surefireClassLoader, providerClassName, this.booterParameters, booterParameters ); + public Object instantiateProvider(String providerClassName, Object booterParameters) { + return instantiateOneArg(surefireClassLoader, providerClassName, this.booterParameters, booterParameters); } - public void setIfDirScannerAware( Object o, DirectoryScannerParameters dirScannerParams ) - { - if ( baseProviderFactory.isAssignableFrom( o.getClass() ) ) - { - setDirectoryScannerParameters( o, dirScannerParams ); + public void setIfDirScannerAware(Object o, DirectoryScannerParameters dirScannerParams) { + if (baseProviderFactory.isAssignableFrom(o.getClass())) { + setDirectoryScannerParameters(o, dirScannerParams); } } - public void setMainCliOptions( Object o, List options ) - { - if ( baseProviderFactory.isAssignableFrom( o.getClass() ) ) - { - List> newOptions = checkedList( new ArrayList>( options.size() ), commandLineOptionsClass ); - Collection ordinals = toOrdinals( options ); - for ( Enum e : commandLineOptionsClass.getEnumConstants() ) - { - if ( ordinals.contains( e.ordinal() ) ) - { - newOptions.add( e ); + public void setMainCliOptions(Object o, List options) { + if (baseProviderFactory.isAssignableFrom(o.getClass())) { + List> newOptions = checkedList(new ArrayList>(options.size()), commandLineOptionsClass); + Collection ordinals = toOrdinals(options); + for (Enum e : commandLineOptionsClass.getEnumConstants()) { + if (ordinals.contains(e.ordinal())) { + newOptions.add(e); } } - invokeSetter( o, "setMainCliOptions", List.class, newOptions ); + invokeSetter(o, "setMainCliOptions", List.class, newOptions); } } - public void setSkipAfterFailureCount( Object o, int skipAfterFailureCount ) - { - invokeSetter( o, "setSkipAfterFailureCount", int.class, skipAfterFailureCount ); + public void setSkipAfterFailureCount(Object o, int skipAfterFailureCount) { + invokeSetter(o, "setSkipAfterFailureCount", int.class, skipAfterFailureCount); } - public void setSystemExitTimeout( Object o, Integer systemExitTimeout ) - { - invokeSetter( o, "setSystemExitTimeout", Integer.class, systemExitTimeout ); + public void setSystemExitTimeout(Object o, Integer systemExitTimeout) { + invokeSetter(o, "setSystemExitTimeout", Integer.class, systemExitTimeout); } - void setDirectoryScannerParameters( Object o, DirectoryScannerParameters dirScannerParams ) - { - Object param = createDirectoryScannerParameters( dirScannerParams ); - invokeSetter( o, "setDirectoryScannerParameters", directoryScannerParameters, param ); + void setDirectoryScannerParameters(Object o, DirectoryScannerParameters dirScannerParams) { + Object param = createDirectoryScannerParameters(dirScannerParams); + invokeSetter(o, "setDirectoryScannerParameters", directoryScannerParameters, param); } - public void setRunOrderParameters( Object o, RunOrderParameters runOrderParameters ) - { - Object param = createRunOrderParameters( runOrderParameters ); - invokeSetter( o, "setRunOrderParameters", this.runOrderParameters, param ); + public void setRunOrderParameters(Object o, RunOrderParameters runOrderParameters) { + Object param = createRunOrderParameters(runOrderParameters); + invokeSetter(o, "setRunOrderParameters", this.runOrderParameters, param); } - public void setTestSuiteDefinitionAware( Object o, TestRequest testSuiteDefinition2 ) - { - if ( baseProviderFactory.isAssignableFrom( o.getClass() ) ) - { - setTestSuiteDefinition( o, testSuiteDefinition2 ); + public void setTestSuiteDefinitionAware(Object o, TestRequest testSuiteDefinition2) { + if (baseProviderFactory.isAssignableFrom(o.getClass())) { + setTestSuiteDefinition(o, testSuiteDefinition2); } } - void setTestSuiteDefinition( Object o, TestRequest testSuiteDefinition1 ) - { - Object param = createTestRequest( testSuiteDefinition1 ); - invokeSetter( o, "setTestRequest", testRequest, param ); + void setTestSuiteDefinition(Object o, TestRequest testSuiteDefinition1) { + Object param = createTestRequest(testSuiteDefinition1); + invokeSetter(o, "setTestRequest", testRequest, param); } - public void setProviderPropertiesAware( Object o, Map properties ) - { - if ( baseProviderFactory.isAssignableFrom( o.getClass() ) ) - { - setProviderProperties( o, properties ); + public void setProviderPropertiesAware(Object o, Map properties) { + if (baseProviderFactory.isAssignableFrom(o.getClass())) { + setProviderProperties(o, properties); } } - void setProviderProperties( Object o, Map providerProperties ) - { - invokeSetter( o, "setProviderProperties", Map.class, providerProperties ); + void setProviderProperties(Object o, Map providerProperties) { + invokeSetter(o, "setProviderProperties", Map.class, providerProperties); } - public void setReporterConfigurationAware( Object o, ReporterConfiguration reporterConfiguration1 ) - { - if ( baseProviderFactory.isAssignableFrom( o.getClass() ) ) - { - setReporterConfiguration( o, reporterConfiguration1 ); + public void setReporterConfigurationAware(Object o, ReporterConfiguration reporterConfiguration1) { + if (baseProviderFactory.isAssignableFrom(o.getClass())) { + setReporterConfiguration(o, reporterConfiguration1); } } - private void setReporterConfiguration( Object o, ReporterConfiguration reporterConfiguration ) - { - Object param = createReporterConfiguration( reporterConfiguration ); - invokeSetter( o, "setReporterConfiguration", this.reporterConfiguration, param ); + private void setReporterConfiguration(Object o, ReporterConfiguration reporterConfiguration) { + Object param = createReporterConfiguration(reporterConfiguration); + invokeSetter(o, "setReporterConfiguration", this.reporterConfiguration, param); } - public void setTestClassLoaderAware( Object o, ClassLoader testClassLoader ) - { - if ( baseProviderFactory.isAssignableFrom( o.getClass() ) ) - { - setTestClassLoader( o, testClassLoader ); + public void setTestClassLoaderAware(Object o, ClassLoader testClassLoader) { + if (baseProviderFactory.isAssignableFrom(o.getClass())) { + setTestClassLoader(o, testClassLoader); } } - void setTestClassLoader( Object o, ClassLoader testClassLoader ) - { - Method setter = getMethod( o, "setClassLoaders", ClassLoader.class ); - invokeMethodWithArray( o, setter, testClassLoader ); + void setTestClassLoader(Object o, ClassLoader testClassLoader) { + Method setter = getMethod(o, "setClassLoaders", ClassLoader.class); + invokeMethodWithArray(o, setter, testClassLoader); } - public void setTestArtifactInfoAware( Object o, TestArtifactInfo testArtifactInfo1 ) - { - if ( baseProviderFactory.isAssignableFrom( o.getClass() ) ) - { - setTestArtifactInfo( o, testArtifactInfo1 ); + public void setTestArtifactInfoAware(Object o, TestArtifactInfo testArtifactInfo1) { + if (baseProviderFactory.isAssignableFrom(o.getClass())) { + setTestArtifactInfo(o, testArtifactInfo1); } } - void setTestArtifactInfo( Object o, TestArtifactInfo testArtifactInfo ) - { - Object param = createTestArtifactInfo( testArtifactInfo ); - invokeSetter( o, "setTestArtifactInfo", this.testArtifactInfo, param ); + void setTestArtifactInfo(Object o, TestArtifactInfo testArtifactInfo) { + Object param = createTestArtifactInfo(testArtifactInfo); + invokeSetter(o, "setTestArtifactInfo", this.testArtifactInfo, param); } - public void setReporterFactoryAware( Object o, Object reporterFactory ) - { - if ( baseProviderFactory.isAssignableFrom( o.getClass() ) ) - { - setReporterFactory( o, reporterFactory ); + public void setReporterFactoryAware(Object o, Object reporterFactory) { + if (baseProviderFactory.isAssignableFrom(o.getClass())) { + setReporterFactory(o, reporterFactory); } } - void setReporterFactory( Object o, Object reporterFactory ) - { - invokeSetter( o, "setReporterFactory", this.reporterFactory, reporterFactory ); + void setReporterFactory(Object o, Object reporterFactory) { + invokeSetter(o, "setReporterFactory", this.reporterFactory, reporterFactory); } - private boolean isRunResult( Object o ) - { - return runResult.isAssignableFrom( o.getClass() ); + private boolean isRunResult(Object o) { + return runResult.isAssignableFrom(o.getClass()); } - private static Collection toOrdinals( Collection> enums ) - { - Collection ordinals = new ArrayList<>( enums.size() ); - for ( Enum e : enums ) - { - ordinals.add( e.ordinal() ); + private static Collection toOrdinals(Collection> enums) { + Collection ordinals = new ArrayList<>(enums.size()); + for (Enum e : enums) { + ordinals.add(e.ordinal()); } return ordinals; } diff --git a/surefire-booter/src/main/java/org/apache/maven/surefire/booter/SystemPropertyManager.java b/surefire-booter/src/main/java/org/apache/maven/surefire/booter/SystemPropertyManager.java index 68accca657..84b93b826d 100644 --- a/surefire-booter/src/main/java/org/apache/maven/surefire/booter/SystemPropertyManager.java +++ b/surefire-booter/src/main/java/org/apache/maven/surefire/booter/SystemPropertyManager.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.booter; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.booter; import java.io.File; import java.io.FileInputStream; @@ -33,8 +32,7 @@ /** * @author Kristian Rosenvold */ -public class SystemPropertyManager -{ +public class SystemPropertyManager { /** * Loads the properties, closes the stream @@ -43,56 +41,42 @@ public class SystemPropertyManager * @return The properties * @throws java.io.IOException If something bad happens */ - public static PropertiesWrapper loadProperties( InputStream inStream ) - throws IOException - { - try ( final InputStream stream = inStream ) - { + public static PropertiesWrapper loadProperties(InputStream inStream) throws IOException { + try (InputStream stream = inStream) { Properties p = new Properties(); - p.load( stream ); - Map map = new ConcurrentHashMap<>( p.size() ); - for ( String key : p.stringPropertyNames() ) - { - map.put( key, p.getProperty( key ) ); + p.load(stream); + Map map = new ConcurrentHashMap<>(p.size()); + for (String key : p.stringPropertyNames()) { + map.put(key, p.getProperty(key)); } - return new PropertiesWrapper( map ); + return new PropertiesWrapper(map); } } - private static PropertiesWrapper loadProperties( File file ) - throws IOException - { - return loadProperties( new FileInputStream( file ) ); + private static PropertiesWrapper loadProperties(File file) throws IOException { + return loadProperties(new FileInputStream(file)); } - public static void setSystemProperties( File file ) - throws IOException - { - PropertiesWrapper p = loadProperties( file ); + public static void setSystemProperties(File file) throws IOException { + PropertiesWrapper p = loadProperties(file); p.setAsSystemProperties(); } - public static File writePropertiesFile( Properties properties, File tempDirectory, String name, - boolean keepForkFiles ) - throws IOException - { - File file = TempFileManager.instance( tempDirectory ).createTempFile( name, "tmp" ); - if ( !keepForkFiles ) - { + public static File writePropertiesFile( + Properties properties, File tempDirectory, String name, boolean keepForkFiles) throws IOException { + File file = TempFileManager.instance(tempDirectory).createTempFile(name, "tmp"); + if (!keepForkFiles) { file.deleteOnExit(); } - writePropertiesFile( file, name, properties ); + writePropertiesFile(file, name, properties); return file; } - public static void writePropertiesFile( File file, String name, Properties properties ) - throws IOException - { - try ( FileOutputStream out = new FileOutputStream( file ) ) - { - properties.store( out, name ); + public static void writePropertiesFile(File file, String name, Properties properties) throws IOException { + try (FileOutputStream out = new FileOutputStream(file)) { + properties.store(out, name); } } } diff --git a/surefire-booter/src/main/java/org/apache/maven/surefire/booter/SystemUtils.java b/surefire-booter/src/main/java/org/apache/maven/surefire/booter/SystemUtils.java index 674cb22edc..3f7b4aa5b0 100644 --- a/surefire-booter/src/main/java/org/apache/maven/surefire/booter/SystemUtils.java +++ b/surefire-booter/src/main/java/org/apache/maven/surefire/booter/SystemUtils.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.booter; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,8 +16,7 @@ * specific language governing permissions and limitations * under the License. */ - -import org.apache.maven.surefire.api.util.ReflectionUtils; +package org.apache.maven.surefire.booter; import java.io.BufferedReader; import java.io.File; @@ -33,16 +30,18 @@ import java.util.Properties; import java.util.StringTokenizer; +import org.apache.maven.surefire.api.util.ReflectionUtils; + import static java.lang.Thread.currentThread; import static java.util.Objects.requireNonNull; +import static org.apache.maven.surefire.api.util.ReflectionUtils.invokeMethodChain; import static org.apache.maven.surefire.api.util.ReflectionUtils.invokeMethodWithArray; -import static org.apache.maven.surefire.shared.lang3.JavaVersion.JAVA_RECENT; +import static org.apache.maven.surefire.api.util.ReflectionUtils.tryLoadClass; import static org.apache.maven.surefire.shared.lang3.JavaVersion.JAVA_9; +import static org.apache.maven.surefire.shared.lang3.JavaVersion.JAVA_RECENT; import static org.apache.maven.surefire.shared.lang3.StringUtils.isNumeric; -import static org.apache.maven.surefire.api.util.ReflectionUtils.invokeMethodChain; -import static org.apache.maven.surefire.api.util.ReflectionUtils.tryLoadClass; -import static org.apache.maven.surefire.shared.lang3.SystemUtils.IS_OS_LINUX; import static org.apache.maven.surefire.shared.lang3.SystemUtils.IS_OS_FREE_BSD; +import static org.apache.maven.surefire.shared.lang3.SystemUtils.IS_OS_LINUX; import static org.apache.maven.surefire.shared.lang3.SystemUtils.IS_OS_NET_BSD; import static org.apache.maven.surefire.shared.lang3.SystemUtils.IS_OS_OPEN_BSD; @@ -52,27 +51,24 @@ * @author Tibor Digana (tibor17) * @since 2.20.1 */ -public final class SystemUtils -{ - private static final BigDecimal JIGSAW_JAVA_VERSION = new BigDecimal( 9 ).stripTrailingZeros(); +public final class SystemUtils { + private static final BigDecimal JIGSAW_JAVA_VERSION = new BigDecimal(9).stripTrailingZeros(); private static final int PROC_STATUS_PID_FIRST_CHARS = 20; - private SystemUtils() - { - throw new IllegalStateException( "no instantiable constructor" ); + private SystemUtils() { + throw new IllegalStateException("no instantiable constructor"); } /** * @param jvmExecPath e.g. /jdk/bin/java, /jdk/jre/bin/java * @return {@code true} if {@code jvmExecPath} is path to java binary executor */ - public static boolean endsWithJavaPath( String jvmExecPath ) - { - File javaExec = new File( jvmExecPath ).getAbsoluteFile(); + public static boolean endsWithJavaPath(String jvmExecPath) { + File javaExec = new File(jvmExecPath).getAbsoluteFile(); File bin = javaExec.getParentFile(); String exec = javaExec.getName(); - return exec.startsWith( "java" ) && bin != null && bin.getName().equals( "bin" ); + return exec.startsWith("java") && bin != null && bin.getName().equals("bin"); } /** @@ -84,16 +80,13 @@ public static boolean endsWithJavaPath( String jvmExecPath ) * @param jvmExecutable /jdk/bin/java* or /jdk/jre/bin/java* * @return path to jdk directory; or null if wrong path or directory layout of JDK installation. */ - public static File toJdkHomeFromJvmExec( String jvmExecutable ) - { - File bin = new File( jvmExecutable ).getAbsoluteFile().getParentFile(); - if ( "bin".equals( bin.getName() ) ) - { + public static File toJdkHomeFromJvmExec(String jvmExecutable) { + File bin = new File(jvmExecutable).getAbsoluteFile().getParentFile(); + if ("bin".equals(bin.getName())) { File parent = bin.getParentFile(); - if ( "jre".equals( parent.getName() ) ) - { + if ("jre".equals(parent.getName())) { File jdk = parent.getParentFile(); - return new File( jdk, "bin" ).isDirectory() ? jdk : null; + return new File(jdk, "bin").isDirectory() ? jdk : null; } return parent; } @@ -107,9 +100,8 @@ public static File toJdkHomeFromJvmExec( String jvmExecutable ) * * @return path to JDK */ - public static File toJdkHomeFromJre() - { - return toJdkHomeFromJre( System.getProperty( "java.home" ) ); + public static File toJdkHomeFromJre() { + return toJdkHomeFromJre(System.getProperty("java.home")); } /** @@ -121,114 +113,83 @@ public static File toJdkHomeFromJre() * @param jreHome path to /jdk or /jdk/jre * @return path to JDK */ - static File toJdkHomeFromJre( String jreHome ) - { - File pathToJreOrJdk = new File( jreHome ).getAbsoluteFile(); - return "jre".equals( pathToJreOrJdk.getName() ) ? pathToJreOrJdk.getParentFile() : pathToJreOrJdk; + static File toJdkHomeFromJre(String jreHome) { + File pathToJreOrJdk = new File(jreHome).getAbsoluteFile(); + return "jre".equals(pathToJreOrJdk.getName()) ? pathToJreOrJdk.getParentFile() : pathToJreOrJdk; } - public static BigDecimal toJdkVersionFromReleaseFile( File jdkHome ) - { - File release = new File( requireNonNull( jdkHome ).getAbsoluteFile(), "release" ); - if ( !release.isFile() ) - { + public static BigDecimal toJdkVersionFromReleaseFile(File jdkHome) { + File release = new File(requireNonNull(jdkHome).getAbsoluteFile(), "release"); + if (!release.isFile()) { return null; } Properties properties = new Properties(); - try ( InputStream is = new FileInputStream( release ) ) - { - properties.load( is ); - String javaVersion = properties.getProperty( "JAVA_VERSION" ).replace( "\"", "" ); - StringTokenizer versions = new StringTokenizer( javaVersion, "._" ); + try (InputStream is = new FileInputStream(release)) { + properties.load(is); + String javaVersion = properties.getProperty("JAVA_VERSION").replace("\"", ""); + StringTokenizer versions = new StringTokenizer(javaVersion, "._"); - if ( versions.countTokens() == 1 ) - { + if (versions.countTokens() == 1) { javaVersion = versions.nextToken(); - } - else if ( versions.countTokens() >= 2 ) - { + } else if (versions.countTokens() >= 2) { String majorVersion = versions.nextToken(); String minorVersion = versions.nextToken(); - javaVersion = isNumeric( minorVersion ) ? majorVersion + "." + minorVersion : majorVersion; - } - else - { + javaVersion = isNumeric(minorVersion) ? majorVersion + "." + minorVersion : majorVersion; + } else { return null; } - return new BigDecimal( javaVersion ); - } - catch ( IOException e ) - { + return new BigDecimal(javaVersion); + } catch (IOException e) { return null; } } - public static boolean isJava9AtLeast( String jvmExecutablePath ) - { - File externalJavaHome = toJdkHomeFromJvmExec( jvmExecutablePath ); + public static boolean isJava9AtLeast(String jvmExecutablePath) { + File externalJavaHome = toJdkHomeFromJvmExec(jvmExecutablePath); File thisJavaHome = toJdkHomeFromJre(); - if ( thisJavaHome.equals( externalJavaHome ) ) - { + if (thisJavaHome.equals(externalJavaHome)) { return isBuiltInJava9AtLeast(); - } - else - { + } else { BigDecimal releaseFileVersion = - externalJavaHome == null ? null : toJdkVersionFromReleaseFile( externalJavaHome ); - return isJava9AtLeast( releaseFileVersion ); + externalJavaHome == null ? null : toJdkVersionFromReleaseFile(externalJavaHome); + return isJava9AtLeast(releaseFileVersion); } } - public static boolean isBuiltInJava9AtLeast() - { - return JAVA_RECENT.atLeast( JAVA_9 ); + public static boolean isBuiltInJava9AtLeast() { + return JAVA_RECENT.atLeast(JAVA_9); } - public static boolean isJava9AtLeast( BigDecimal version ) - { - return version != null && version.compareTo( JIGSAW_JAVA_VERSION ) >= 0; + public static boolean isJava9AtLeast(BigDecimal version) { + return version != null && version.compareTo(JIGSAW_JAVA_VERSION) >= 0; } - public static ClassLoader platformClassLoader() - { - if ( isBuiltInJava9AtLeast() ) - { - return reflectClassLoader( ClassLoader.class, "getPlatformClassLoader" ); + public static ClassLoader platformClassLoader() { + if (isBuiltInJava9AtLeast()) { + return reflectClassLoader(ClassLoader.class, "getPlatformClassLoader"); } return null; } - public static Long pid() - { - if ( isBuiltInJava9AtLeast() ) - { + public static Long pid() { + if (isBuiltInJava9AtLeast()) { Long pid = pidOnJava9(); - if ( pid != null ) - { + if (pid != null) { return pid; } } - if ( IS_OS_LINUX ) - { - try - { + if (IS_OS_LINUX) { + try { return pidStatusOnLinux(); - } - catch ( Exception e ) - { + } catch (Exception e) { // examine PID via JMX } - } - else if ( IS_OS_FREE_BSD || IS_OS_NET_BSD || IS_OS_OPEN_BSD ) - { - try - { + } else if (IS_OS_FREE_BSD || IS_OS_NET_BSD || IS_OS_OPEN_BSD) { + try { return pidStatusOnBSD(); - } - catch ( Exception e ) - { + } catch (Exception e) { // examine PID via JMX } } @@ -236,18 +197,13 @@ else if ( IS_OS_FREE_BSD || IS_OS_NET_BSD || IS_OS_OPEN_BSD ) return pidOnJMX(); } - static Long pidOnJMX() - { + static Long pidOnJMX() { String processName = ManagementFactory.getRuntimeMXBean().getName(); - if ( processName.contains( "@" ) ) - { - String pid = processName.substring( 0, processName.indexOf( '@' ) ).trim(); - try - { - return Long.parseLong( pid ); - } - catch ( NumberFormatException e ) - { + if (processName.contains("@")) { + String pid = processName.substring(0, processName.indexOf('@')).trim(); + try { + return Long.parseLong(pid); + } catch (NumberFormatException e) { return null; } } @@ -271,9 +227,8 @@ static Long pidOnJMX() * @return self PID * @throws Exception i/o and number format exc */ - static Long pidStatusOnLinux() throws Exception - { - return pidStatusOnLinux( "" ); + static Long pidStatusOnLinux() throws Exception { + return pidStatusOnLinux(""); } /** @@ -283,15 +238,13 @@ static Long pidStatusOnLinux() throws Exception * @return same as in {@link #pidStatusOnLinux()} * @throws Exception same as in {@link #pidStatusOnLinux()} */ - static Long pidStatusOnLinux( String root ) throws Exception - { - try ( FileReader input = new FileReader( root + "/proc/self/stat" ) ) - { + static Long pidStatusOnLinux(String root) throws Exception { + try (FileReader input = new FileReader(root + "/proc/self/stat")) { // Reading and encoding 20 characters is bit faster than whole line. // size of (long) = 19, + 1 space char[] buffer = new char[PROC_STATUS_PID_FIRST_CHARS]; - String startLine = new String( buffer, 0, input.read( buffer ) ); - return Long.parseLong( startLine.substring( 0, startLine.indexOf( ' ' ) ) ); + String startLine = new String(buffer, 0, input.read(buffer)); + return Long.parseLong(startLine.substring(0, startLine.indexOf(' '))); } } @@ -313,9 +266,8 @@ static Long pidStatusOnLinux( String root ) throws Exception * @return current PID * @throws Exception if could not read /proc/curproc/status */ - static Long pidStatusOnBSD() throws Exception - { - return pidStatusOnBSD( "" ); + static Long pidStatusOnBSD() throws Exception { + return pidStatusOnBSD(""); } /** @@ -325,35 +277,28 @@ static Long pidStatusOnBSD() throws Exception * @return same as in {@link #pidStatusOnBSD()} * @throws Exception same as in {@link #pidStatusOnBSD()} */ - static Long pidStatusOnBSD( String root ) throws Exception - { - try ( BufferedReader input = new BufferedReader( new FileReader( root + "/proc/curproc/status" ) ) ) - { + static Long pidStatusOnBSD(String root) throws Exception { + try (BufferedReader input = new BufferedReader(new FileReader(root + "/proc/curproc/status"))) { String line = input.readLine(); - int i1 = 1 + line.indexOf( ' ' ); - int i2 = line.indexOf( ' ', i1 ); - return Long.parseLong( line.substring( i1, i2 ) ); + int i1 = 1 + line.indexOf(' '); + int i2 = line.indexOf(' ', i1); + return Long.parseLong(line.substring(i1, i2)); } } - static Long pidOnJava9() - { + static Long pidOnJava9() { ClassLoader classLoader = currentThread().getContextClassLoader(); - Class processHandle = tryLoadClass( classLoader, "java.lang.ProcessHandle" ); - Class[] classesChain = { processHandle, processHandle }; - String[] methodChain = { "current", "pid" }; - return invokeMethodChain( classesChain, methodChain, null ); + Class processHandle = tryLoadClass(classLoader, "java.lang.ProcessHandle"); + Class[] classesChain = {processHandle, processHandle}; + String[] methodChain = {"current", "pid"}; + return invokeMethodChain(classesChain, methodChain, null); } - static ClassLoader reflectClassLoader( Class target, String getterMethodName ) - { - try - { - Method getter = ReflectionUtils.getMethod( target, getterMethodName ); - return invokeMethodWithArray( null, getter ); - } - catch ( RuntimeException e ) - { + static ClassLoader reflectClassLoader(Class target, String getterMethodName) { + try { + Method getter = ReflectionUtils.getMethod(target, getterMethodName); + return invokeMethodWithArray(null, getter); + } catch (RuntimeException e) { return null; } } diff --git a/surefire-booter/src/main/java/org/apache/maven/surefire/booter/TypeEncodedValue.java b/surefire-booter/src/main/java/org/apache/maven/surefire/booter/TypeEncodedValue.java index 554db3b180..d88eb7cd34 100644 --- a/surefire-booter/src/main/java/org/apache/maven/surefire/booter/TypeEncodedValue.java +++ b/surefire-booter/src/main/java/org/apache/maven/surefire/booter/TypeEncodedValue.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.booter; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.booter; import java.io.ByteArrayInputStream; import java.io.File; @@ -31,110 +30,80 @@ /** * @author Kristian Rosenvold */ -public final class TypeEncodedValue -{ +public final class TypeEncodedValue { private final String type; private final String value; - public TypeEncodedValue( String type, String value ) - { + public TypeEncodedValue(String type, String value) { this.type = type; this.value = value; } - private boolean isTypeClass() - { - return Class.class.getName().equals( type ); + private boolean isTypeClass() { + return Class.class.getName().equals(type); } - public Object getDecodedValue() - { - return getDecodedValue( Thread.currentThread().getContextClassLoader() ); + public Object getDecodedValue() { + return getDecodedValue(Thread.currentThread().getContextClassLoader()); } - public Object getDecodedValue( ClassLoader classLoader ) - { - if ( type.trim().isEmpty() ) - { + public Object getDecodedValue(ClassLoader classLoader) { + if (type.trim().isEmpty()) { return null; - } - else if ( type.equals( String.class.getName() ) ) - { + } else if (type.equals(String.class.getName())) { return value; - } - else if ( isTypeClass() ) - { - return loadClass( classLoader, value ); - } - else if ( type.equals( File.class.getName() ) ) - { - return new File( value ); - } - else if ( type.equals( Boolean.class.getName() ) ) - { - return Boolean.valueOf( value ); - } - else if ( type.equals( Integer.class.getName() ) ) - { - return Integer.valueOf( value ); - } - else if ( type.equals( Properties.class.getName() ) ) - { + } else if (isTypeClass()) { + return loadClass(classLoader, value); + } else if (type.equals(File.class.getName())) { + return new File(value); + } else if (type.equals(Boolean.class.getName())) { + return Boolean.valueOf(value); + } else if (type.equals(Integer.class.getName())) { + return Integer.valueOf(value); + } else if (type.equals(Properties.class.getName())) { Properties result = new Properties(); - try - { - result.load( new ByteArrayInputStream( value.getBytes( ISO_8859_1 ) ) ); + try { + result.load(new ByteArrayInputStream(value.getBytes(ISO_8859_1))); return result; + } catch (IOException e) { + throw new IllegalStateException("bug in property conversion", e); } - catch ( IOException e ) - { - throw new IllegalStateException( "bug in property conversion", e ); - } - } - else - { - throw new IllegalArgumentException( "Unknown parameter type: " + type ); + } else { + throw new IllegalArgumentException("Unknown parameter type: " + type); } } @Override - public boolean equals( Object o ) - { - if ( this == o ) - { + public boolean equals(Object o) { + if (this == o) { return true; } - if ( o == null || getClass() != o.getClass() ) - { + if (o == null || getClass() != o.getClass()) { return false; } TypeEncodedValue that = (TypeEncodedValue) o; - return equalsType( that ) && equalsValue( that ); + return equalsType(that) && equalsValue(that); } @Override - public int hashCode() - { + public int hashCode() { int result = type != null ? type.hashCode() : 0; - result = 31 * result + ( value != null ? value.hashCode() : 0 ); + result = 31 * result + (value != null ? value.hashCode() : 0); return result; } @Override - public String toString() - { + public String toString() { return "TypeEncodedValue{" + "type='" + type + '\'' + ", value='" + value + '\'' + '}'; } - private boolean equalsType( TypeEncodedValue that ) - { - return Objects.equals( type, that.type ); + private boolean equalsType(TypeEncodedValue that) { + return Objects.equals(type, that.type); } - private boolean equalsValue( TypeEncodedValue that ) - { - return Objects.equals( value, that.value ); + private boolean equalsValue(TypeEncodedValue that) { + return Objects.equals(value, that.value); } } diff --git a/surefire-booter/src/main/java/org/apache/maven/surefire/booter/spi/AbstractMasterProcessChannelProcessorFactory.java b/surefire-booter/src/main/java/org/apache/maven/surefire/booter/spi/AbstractMasterProcessChannelProcessorFactory.java index 63407f28b7..5a9a1e8245 100644 --- a/surefire-booter/src/main/java/org/apache/maven/surefire/booter/spi/AbstractMasterProcessChannelProcessorFactory.java +++ b/surefire-booter/src/main/java/org/apache/maven/surefire/booter/spi/AbstractMasterProcessChannelProcessorFactory.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.booter.spi; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,9 +16,7 @@ * specific language governing permissions and limitations * under the License. */ - -import org.apache.maven.surefire.api.util.internal.WritableBufferedByteChannel; -import org.apache.maven.surefire.spi.MasterProcessChannelProcessorFactory; +package org.apache.maven.surefire.booter.spi; import java.io.IOException; import java.nio.ByteBuffer; @@ -29,6 +25,9 @@ import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.atomic.AtomicLong; +import org.apache.maven.surefire.api.util.internal.WritableBufferedByteChannel; +import org.apache.maven.surefire.spi.MasterProcessChannelProcessorFactory; + import static java.security.AccessController.doPrivileged; import static java.util.concurrent.Executors.newScheduledThreadPool; import static java.util.concurrent.TimeUnit.MILLISECONDS; @@ -37,69 +36,54 @@ /** * Default implementation of {@link MasterProcessChannelProcessorFactory}. */ -public abstract class AbstractMasterProcessChannelProcessorFactory - implements MasterProcessChannelProcessorFactory -{ +public abstract class AbstractMasterProcessChannelProcessorFactory implements MasterProcessChannelProcessorFactory { private static final String STREAM_FLUSHER = "surefire-forkedjvm-stream-flusher"; private final ScheduledExecutorService flusher; - public AbstractMasterProcessChannelProcessorFactory() - { - flusher = newScheduledThreadPool( 1, newDaemonThreadFactory( STREAM_FLUSHER ) ); + public AbstractMasterProcessChannelProcessorFactory() { + flusher = newScheduledThreadPool(1, newDaemonThreadFactory(STREAM_FLUSHER)); } - protected void schedulePeriodicFlusher( int delayInMillis, final WritableBufferedByteChannel channel ) - { + protected void schedulePeriodicFlusher(int delayInMillis, final WritableBufferedByteChannel channel) { final AtomicLong bufferOverflows = new AtomicLong(); - flusher.scheduleWithFixedDelay( new Runnable() - { - @Override - public void run() - { - long currentBufferOverflows = channel.countBufferOverflows(); - // optimization: flush the Channel only if the buffer has not overflew after last period of time - if ( bufferOverflows.get() == currentBufferOverflows ) - { - try - { - channel.write( ByteBuffer.allocate( 0 ) ); + flusher.scheduleWithFixedDelay( + new Runnable() { + @Override + public void run() { + long currentBufferOverflows = channel.countBufferOverflows(); + // optimization: flush the Channel only if the buffer has not overflew after last period of time + if (bufferOverflows.get() == currentBufferOverflows) { + try { + channel.write(ByteBuffer.allocate(0)); + } catch (Exception e) { + // cannot do anything about this I/O issue + } + } else { + bufferOverflows.set(currentBufferOverflows); + } } - catch ( Exception e ) - { - // cannot do anything about this I/O issue - } - } - else - { - bufferOverflows.set( currentBufferOverflows ); - } - } - }, 0L, delayInMillis, MILLISECONDS ); + }, + 0L, + delayInMillis, + MILLISECONDS); } @Override - public void close() throws IOException - { - try - { - doPrivileged( new PrivilegedAction() - { - @Override - public Object run() - { - flusher.shutdown(); - // Do NOT call awaitTermination() due to this would unnecessarily prolong teardown - // time of the JVM. It is not a critical situation when the JXM exits this daemon - // thread because the interrupted flusher does not break any business function. - // All business data is already safely flushed by test events, then by sending BYE - // event at the exit time and finally by flushEventChannelOnExit() in ForkedBooter. - return null; - } - } - ); - } - catch ( AccessControlException e ) - { + public void close() throws IOException { + try { + doPrivileged(new PrivilegedAction() { + @Override + public Object run() { + flusher.shutdown(); + // Do NOT call awaitTermination() due to this would unnecessarily prolong teardown + // time of the JVM. It is not a critical situation when the JXM exits this daemon + // thread because the interrupted flusher does not break any business function. + // All business data is already safely flushed by test events, then by sending BYE + // event at the exit time and finally by flushEventChannelOnExit() in ForkedBooter. + return null; + } + }); + } catch (AccessControlException e) { // ignore } } diff --git a/surefire-booter/src/main/java/org/apache/maven/surefire/booter/spi/CommandChannelDecoder.java b/surefire-booter/src/main/java/org/apache/maven/surefire/booter/spi/CommandChannelDecoder.java index 85bda73a83..3c1a609f27 100644 --- a/surefire-booter/src/main/java/org/apache/maven/surefire/booter/spi/CommandChannelDecoder.java +++ b/surefire-booter/src/main/java/org/apache/maven/surefire/booter/spi/CommandChannelDecoder.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.booter.spi; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,12 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.booter.spi; + +import javax.annotation.Nonnull; + +import java.io.IOException; +import java.nio.channels.ReadableByteChannel; import org.apache.maven.surefire.api.booter.Command; import org.apache.maven.surefire.api.booter.MasterProcessChannelDecoder; @@ -26,10 +30,6 @@ import org.apache.maven.surefire.api.stream.MalformedChannelException; import org.apache.maven.surefire.booter.stream.CommandDecoder; -import javax.annotation.Nonnull; -import java.io.IOException; -import java.nio.channels.ReadableByteChannel; - /** * magic number : opcode [: opcode specific data]* *
    @@ -37,50 +37,38 @@ * @author Tibor Digana (tibor17) * @since 3.0.0-M5 */ -public class CommandChannelDecoder implements MasterProcessChannelDecoder -{ +public class CommandChannelDecoder implements MasterProcessChannelDecoder { private final CommandDecoder decoder; private Memento memento; - public CommandChannelDecoder( @Nonnull ReadableByteChannel channel, - @Nonnull ForkNodeArguments arguments ) - { - decoder = new CommandDecoder( channel, arguments ); + public CommandChannelDecoder(@Nonnull ReadableByteChannel channel, @Nonnull ForkNodeArguments arguments) { + decoder = new CommandDecoder(channel, arguments); } @Override @Nonnull - @SuppressWarnings( "checkstyle:innerassignment" ) - public Command decode() throws IOException - { - if ( memento == null ) - { + @SuppressWarnings("checkstyle:innerassignment") + public Command decode() throws IOException { + if (memento == null) { // do not create memento in constructor because the constructor is called in another thread // memento is the thread confinement object memento = decoder.new Memento(); } - do - { - try - { - Command command = decoder.decode( memento ); - if ( command != null ) - { + do { + try { + Command command = decoder.decode(memento); + if (command != null) { return command; } - } - catch ( MalformedChannelException e ) - { + } catch (MalformedChannelException e) { // a bad stream, already logged the stream down to a dump file or console, and continue till OEF } - } - while ( true ); + } while (true); } @Override - public void close() throws IOException - { + public void close() throws IOException { decoder.close(); } } diff --git a/surefire-booter/src/main/java/org/apache/maven/surefire/booter/spi/EventChannelEncoder.java b/surefire-booter/src/main/java/org/apache/maven/surefire/booter/spi/EventChannelEncoder.java index f06b281773..13df7fa1a0 100644 --- a/surefire-booter/src/main/java/org/apache/maven/surefire/booter/spi/EventChannelEncoder.java +++ b/surefire-booter/src/main/java/org/apache/maven/surefire/booter/spi/EventChannelEncoder.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.booter.spi; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,19 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.booter.spi; + +import javax.annotation.Nonnull; + +import java.io.IOException; +import java.nio.Buffer; +import java.nio.ByteBuffer; +import java.nio.channels.ClosedChannelException; +import java.nio.charset.CharsetEncoder; +import java.util.Iterator; +import java.util.Map; +import java.util.Map.Entry; +import java.util.concurrent.atomic.AtomicBoolean; import org.apache.maven.plugin.surefire.log.api.ConsoleLoggerUtils; import org.apache.maven.surefire.api.booter.DumpErrorSingleton; @@ -32,17 +43,6 @@ import org.apache.maven.surefire.api.util.internal.WritableBufferedByteChannel; import org.apache.maven.surefire.booter.stream.EventEncoder; -import javax.annotation.Nonnull; -import java.io.IOException; -import java.nio.Buffer; -import java.nio.ByteBuffer; -import java.nio.channels.ClosedChannelException; -import java.nio.charset.CharsetEncoder; -import java.util.Iterator; -import java.util.Map; -import java.util.Map.Entry; -import java.util.concurrent.atomic.AtomicBoolean; - import static org.apache.maven.surefire.api.booter.ForkedProcessEventType.BOOTERCODE_BYE; import static org.apache.maven.surefire.api.booter.ForkedProcessEventType.BOOTERCODE_CONSOLE_DEBUG; import static org.apache.maven.surefire.api.booter.ForkedProcessEventType.BOOTERCODE_CONSOLE_ERROR; @@ -72,9 +72,8 @@ * @author Tibor Digana (tibor17) * @since 3.0.0-M4 */ -@SuppressWarnings( "checkstyle:linelength" ) -public class EventChannelEncoder extends EventEncoder implements MasterProcessChannelEncoder -{ +@SuppressWarnings("checkstyle:linelength") +public class EventChannelEncoder extends EventEncoder implements MasterProcessChannelEncoder { private final AtomicBoolean trouble = new AtomicBoolean(); private volatile boolean onExit; @@ -83,268 +82,241 @@ public class EventChannelEncoder extends EventEncoder implements MasterProcessCh * * @param out the channel available for writing the events */ - public EventChannelEncoder( @Nonnull WritableBufferedByteChannel out ) - { - super( out ); + public EventChannelEncoder(@Nonnull WritableBufferedByteChannel out) { + super(out); } @Override - public boolean checkError() - { + public boolean checkError() { return trouble.get(); } @Override - public void onJvmExit() - { + public void onJvmExit() { onExit = true; - write( ByteBuffer.wrap( new byte[] {'\n'} ), true ); + write(ByteBuffer.wrap(new byte[] {'\n'}), true); } - void encodeSystemProperties( Map sysProps, RunMode runMode, Long testRunId ) - { + void encodeSystemProperties(Map sysProps, RunMode runMode, Long testRunId) { CharsetEncoder encoder = newCharsetEncoder(); ByteBuffer result = null; - for ( Iterator> it = sysProps.entrySet().iterator(); it.hasNext(); ) - { + for (Iterator> it = sysProps.entrySet().iterator(); it.hasNext(); ) { Entry entry = it.next(); String key = entry.getKey(); String value = entry.getValue(); int bufferLength = - estimateBufferLength( BOOTERCODE_SYSPROPS.getOpcode().length(), runMode, encoder, 0, 1, key, value ); - result = result != null && result.capacity() >= bufferLength ? result : ByteBuffer.allocate( bufferLength ); - ( (Buffer) result ).clear(); + estimateBufferLength(BOOTERCODE_SYSPROPS.getOpcode().length(), runMode, encoder, 0, 1, key, value); + result = result != null && result.capacity() >= bufferLength ? result : ByteBuffer.allocate(bufferLength); + ((Buffer) result).clear(); // :maven-surefire-event:sys-prop:::UTF-8::::: - encode( encoder, result, BOOTERCODE_SYSPROPS, runMode, testRunId, key, value ); + encode(encoder, result, BOOTERCODE_SYSPROPS, runMode, testRunId, key, value); boolean sync = !it.hasNext(); - write( result, sync ); + write(result, sync); } } @Override - public void testSetStarting( TestSetReportEntry reportEntry, boolean trimStackTraces ) - { - encode( BOOTERCODE_TESTSET_STARTING, reportEntry, trimStackTraces, true ); + public void testSetStarting(TestSetReportEntry reportEntry, boolean trimStackTraces) { + encode(BOOTERCODE_TESTSET_STARTING, reportEntry, trimStackTraces, true); } @Override - public void testSetCompleted( TestSetReportEntry reportEntry, boolean trimStackTraces ) - { - encodeSystemProperties( reportEntry.getSystemProperties(), reportEntry.getRunMode(), reportEntry.getTestRunId() ); - encode( BOOTERCODE_TESTSET_COMPLETED, reportEntry, trimStackTraces, true ); + public void testSetCompleted(TestSetReportEntry reportEntry, boolean trimStackTraces) { + encodeSystemProperties(reportEntry.getSystemProperties(), reportEntry.getRunMode(), reportEntry.getTestRunId()); + encode(BOOTERCODE_TESTSET_COMPLETED, reportEntry, trimStackTraces, true); } @Override - public void testStarting( ReportEntry reportEntry, boolean trimStackTraces ) - { - encode( BOOTERCODE_TEST_STARTING, reportEntry, trimStackTraces, true ); + public void testStarting(ReportEntry reportEntry, boolean trimStackTraces) { + encode(BOOTERCODE_TEST_STARTING, reportEntry, trimStackTraces, true); } @Override - public void testSucceeded( ReportEntry reportEntry, boolean trimStackTraces ) - { - encode( BOOTERCODE_TEST_SUCCEEDED, reportEntry, trimStackTraces, true ); + public void testSucceeded(ReportEntry reportEntry, boolean trimStackTraces) { + encode(BOOTERCODE_TEST_SUCCEEDED, reportEntry, trimStackTraces, true); } @Override - public void testFailed( ReportEntry reportEntry, boolean trimStackTraces ) - { - encode( BOOTERCODE_TEST_FAILED, reportEntry, trimStackTraces, true ); + public void testFailed(ReportEntry reportEntry, boolean trimStackTraces) { + encode(BOOTERCODE_TEST_FAILED, reportEntry, trimStackTraces, true); } @Override - public void testSkipped( ReportEntry reportEntry, boolean trimStackTraces ) - { - encode( BOOTERCODE_TEST_SKIPPED, reportEntry, trimStackTraces, true ); + public void testSkipped(ReportEntry reportEntry, boolean trimStackTraces) { + encode(BOOTERCODE_TEST_SKIPPED, reportEntry, trimStackTraces, true); } @Override - public void testError( ReportEntry reportEntry, boolean trimStackTraces ) - { - encode( BOOTERCODE_TEST_ERROR, reportEntry, trimStackTraces, true ); + public void testError(ReportEntry reportEntry, boolean trimStackTraces) { + encode(BOOTERCODE_TEST_ERROR, reportEntry, trimStackTraces, true); } @Override - public void testAssumptionFailure( ReportEntry reportEntry, boolean trimStackTraces ) - { - encode( BOOTERCODE_TEST_ASSUMPTIONFAILURE, reportEntry, trimStackTraces, true ); + public void testAssumptionFailure(ReportEntry reportEntry, boolean trimStackTraces) { + encode(BOOTERCODE_TEST_ASSUMPTIONFAILURE, reportEntry, trimStackTraces, true); } @Override - public void testOutput( TestOutputReportEntry reportEntry ) - { + public void testOutput(TestOutputReportEntry reportEntry) { boolean stdout = reportEntry.isStdOut(); boolean newLine = reportEntry.isNewLine(); String msg = reportEntry.getLog(); - ForkedProcessEventType event = - stdout ? ( newLine ? BOOTERCODE_STDOUT_NEW_LINE : BOOTERCODE_STDOUT ) - : ( newLine ? BOOTERCODE_STDERR_NEW_LINE : BOOTERCODE_STDERR ); - setOutErr( event, reportEntry.getRunMode(), reportEntry.getTestRunId(), msg ); + ForkedProcessEventType event = stdout + ? (newLine ? BOOTERCODE_STDOUT_NEW_LINE : BOOTERCODE_STDOUT) + : (newLine ? BOOTERCODE_STDERR_NEW_LINE : BOOTERCODE_STDERR); + setOutErr(event, reportEntry.getRunMode(), reportEntry.getTestRunId(), msg); } - private void setOutErr( ForkedProcessEventType eventType, RunMode runMode, Long testRunId, String message ) - { - ByteBuffer result = encodeMessage( eventType, runMode, testRunId, message ); - write( result, false ); + private void setOutErr(ForkedProcessEventType eventType, RunMode runMode, Long testRunId, String message) { + ByteBuffer result = encodeMessage(eventType, runMode, testRunId, message); + write(result, false); } @Override - public void consoleInfoLog( String message ) - { - ByteBuffer result = encodeMessage( BOOTERCODE_CONSOLE_INFO, message ); - write( result, true ); + public void consoleInfoLog(String message) { + ByteBuffer result = encodeMessage(BOOTERCODE_CONSOLE_INFO, message); + write(result, true); } @Override - public void consoleErrorLog( String message ) - { - consoleErrorLog( message, null ); + public void consoleErrorLog(String message) { + consoleErrorLog(message, null); } @Override - public void consoleErrorLog( Throwable t ) - { - consoleErrorLog( t.getLocalizedMessage(), t ); + public void consoleErrorLog(Throwable t) { + consoleErrorLog(t.getLocalizedMessage(), t); } @Override - public void consoleErrorLog( String message, Throwable t ) - { + public void consoleErrorLog(String message, Throwable t) { CharsetEncoder encoder = newCharsetEncoder(); - String stackTrace = t == null ? null : ConsoleLoggerUtils.toString( t ); - int bufferMaxLength = estimateBufferLength( BOOTERCODE_CONSOLE_ERROR.getOpcode().length(), null, encoder, 0, 0, - message, null, stackTrace ); - ByteBuffer result = ByteBuffer.allocate( bufferMaxLength ); - encodeHeader( result, BOOTERCODE_CONSOLE_ERROR ); - encodeCharset( result ); - encode( encoder, result, message, null, stackTrace ); - write( result, true ); + String stackTrace = t == null ? null : ConsoleLoggerUtils.toString(t); + int bufferMaxLength = estimateBufferLength( + BOOTERCODE_CONSOLE_ERROR.getOpcode().length(), null, encoder, 0, 0, message, null, stackTrace); + ByteBuffer result = ByteBuffer.allocate(bufferMaxLength); + encodeHeader(result, BOOTERCODE_CONSOLE_ERROR); + encodeCharset(result); + encode(encoder, result, message, null, stackTrace); + write(result, true); } @Override - public void consoleErrorLog( StackTraceWriter stackTraceWriter, boolean trimStackTraces ) - { - error( stackTraceWriter, trimStackTraces, BOOTERCODE_CONSOLE_ERROR, true ); + public void consoleErrorLog(StackTraceWriter stackTraceWriter, boolean trimStackTraces) { + error(stackTraceWriter, trimStackTraces, BOOTERCODE_CONSOLE_ERROR, true); } @Override - public void consoleDebugLog( String message ) - { - ByteBuffer result = encodeMessage( BOOTERCODE_CONSOLE_DEBUG, message ); - write( result, true ); + public void consoleDebugLog(String message) { + ByteBuffer result = encodeMessage(BOOTERCODE_CONSOLE_DEBUG, message); + write(result, true); } @Override - public void consoleWarningLog( String message ) - { - ByteBuffer result = encodeMessage( BOOTERCODE_CONSOLE_WARNING, message ); - write( result, true ); + public void consoleWarningLog(String message) { + ByteBuffer result = encodeMessage(BOOTERCODE_CONSOLE_WARNING, message); + write(result, true); } @Override - public void bye() - { - encodeOpcode( BOOTERCODE_BYE, true ); + public void bye() { + encodeOpcode(BOOTERCODE_BYE, true); } @Override - public void stopOnNextTest() - { - encodeOpcode( BOOTERCODE_STOP_ON_NEXT_TEST, true ); + public void stopOnNextTest() { + encodeOpcode(BOOTERCODE_STOP_ON_NEXT_TEST, true); } @Override - public void acquireNextTest() - { - encodeOpcode( BOOTERCODE_NEXT_TEST, true ); + public void acquireNextTest() { + encodeOpcode(BOOTERCODE_NEXT_TEST, true); } @Override - public void sendExitError( StackTraceWriter stackTraceWriter, boolean trimStackTraces ) - { - error( stackTraceWriter, trimStackTraces, BOOTERCODE_JVM_EXIT_ERROR, true ); + public void sendExitError(StackTraceWriter stackTraceWriter, boolean trimStackTraces) { + error(stackTraceWriter, trimStackTraces, BOOTERCODE_JVM_EXIT_ERROR, true); } - private void error( StackTraceWriter stackTraceWriter, boolean trimStackTraces, ForkedProcessEventType eventType, - @SuppressWarnings( "SameParameterValue" ) boolean sync ) - { + private void error( + StackTraceWriter stackTraceWriter, + boolean trimStackTraces, + ForkedProcessEventType eventType, + @SuppressWarnings("SameParameterValue") boolean sync) { CharsetEncoder encoder = newCharsetEncoder(); - StackTrace stackTraceWrapper = new StackTrace( stackTraceWriter, trimStackTraces ); - int bufferMaxLength = estimateBufferLength( eventType.getOpcode().length(), null, encoder, 0, 0, - stackTraceWrapper.message, stackTraceWrapper.smartTrimmedStackTrace, stackTraceWrapper.stackTrace ); - ByteBuffer result = ByteBuffer.allocate( bufferMaxLength ); - - encodeHeader( result, eventType ); - encodeCharset( result ); - encode( encoder, result, stackTraceWrapper ); - write( result, sync ); + StackTrace stackTraceWrapper = new StackTrace(stackTraceWriter, trimStackTraces); + int bufferMaxLength = estimateBufferLength( + eventType.getOpcode().length(), + null, + encoder, + 0, + 0, + stackTraceWrapper.message, + stackTraceWrapper.smartTrimmedStackTrace, + stackTraceWrapper.stackTrace); + ByteBuffer result = ByteBuffer.allocate(bufferMaxLength); + + encodeHeader(result, eventType); + encodeCharset(result); + encode(encoder, result, stackTraceWrapper); + write(result, sync); } // example // :maven-surefire-event:testset-starting:rerun-test-after-failure:1:5:UTF-8::SourceName::SourceText::Name::NameText::Group::Message::ElapsedTime::LocalizedMessage::SmartTrimmedStackTrace::toStackTrace( stw, trimStackTraces ):: - private void encode( ForkedProcessEventType operation, ReportEntry reportEntry, - boolean trimStackTraces, @SuppressWarnings( "SameParameterValue" ) boolean sync ) - { - ByteBuffer result = encode( operation, reportEntry, trimStackTraces ); - write( result, sync ); + private void encode( + ForkedProcessEventType operation, + ReportEntry reportEntry, + boolean trimStackTraces, + @SuppressWarnings("SameParameterValue") boolean sync) { + ByteBuffer result = encode(operation, reportEntry, trimStackTraces); + write(result, sync); } - private void encodeOpcode( ForkedProcessEventType eventType, boolean sync ) - { - int bufferMaxLength = estimateBufferLength( eventType.getOpcode().length(), null, null, 0, 0 ); - ByteBuffer result = ByteBuffer.allocate( bufferMaxLength ); - encodeHeader( result, eventType ); - write( result, sync ); + private void encodeOpcode(ForkedProcessEventType eventType, boolean sync) { + int bufferMaxLength = estimateBufferLength(eventType.getOpcode().length(), null, null, 0, 0); + ByteBuffer result = ByteBuffer.allocate(bufferMaxLength); + encodeHeader(result, eventType); + write(result, sync); } @Override - protected void write( ByteBuffer frame, boolean sync ) - { + protected void write(ByteBuffer frame, boolean sync) { final boolean wasInterrupted = Thread.interrupted(); - try - { - super.write( frame, sync ); - } - catch ( ClosedChannelException e ) - { - if ( !onExit ) - { - String event = new String( frame.array(), frame.arrayOffset() + ( (Buffer) frame ).position(), frame.remaining(), - getCharset() ); + try { + super.write(frame, sync); + } catch (ClosedChannelException e) { + if (!onExit) { + String event = new String( + frame.array(), + frame.arrayOffset() + ((Buffer) frame).position(), + frame.remaining(), + getCharset()); DumpErrorSingleton.getSingleton() - .dumpException( e, "Channel closed while writing the event '" + event + "'." ); + .dumpException(e, "Channel closed while writing the event '" + event + "'."); } - } - catch ( IOException e ) - { - if ( trouble.compareAndSet( false, true ) ) - { - DumpErrorSingleton.getSingleton() - .dumpException( e ); + } catch (IOException e) { + if (trouble.compareAndSet(false, true)) { + DumpErrorSingleton.getSingleton().dumpException(e); } - } - finally - { - if ( wasInterrupted ) - { + } finally { + if (wasInterrupted) { Thread.currentThread().interrupt(); } } } - private void encode( CharsetEncoder encoder, ByteBuffer result, StackTrace stw ) - { - encode( encoder, result, stw.message, stw.smartTrimmedStackTrace, stw.stackTrace ); + private void encode(CharsetEncoder encoder, ByteBuffer result, StackTrace stw) { + encode(encoder, result, stw.message, stw.smartTrimmedStackTrace, stw.stackTrace); } - private void encode( CharsetEncoder encoder, ByteBuffer result, - String message, String smartStackTrace, String stackTrace ) - { - encodeString( encoder, result, message ); - encodeString( encoder, result, smartStackTrace ); - encodeString( encoder, result, stackTrace ); + private void encode( + CharsetEncoder encoder, ByteBuffer result, String message, String smartStackTrace, String stackTrace) { + encodeString(encoder, result, message); + encodeString(encoder, result, smartStackTrace); + encodeString(encoder, result, stackTrace); } /** @@ -360,76 +332,79 @@ private void encode( CharsetEncoder encoder, ByteBuffer result, *
  • {@link ForkedProcessEventType#BOOTERCODE_TEST_ASSUMPTIONFAILURE}.
  • * */ - ByteBuffer encode( ForkedProcessEventType operation, ReportEntry reportEntry, boolean trimStackTraces ) - { - StackTrace stackTraceWrapper = new StackTrace( reportEntry.getStackTraceWriter(), trimStackTraces ); + ByteBuffer encode(ForkedProcessEventType operation, ReportEntry reportEntry, boolean trimStackTraces) { + StackTrace stackTraceWrapper = new StackTrace(reportEntry.getStackTraceWriter(), trimStackTraces); CharsetEncoder encoder = newCharsetEncoder(); - int bufferMaxLength = estimateBufferLength( operation.getOpcode().length(), reportEntry.getRunMode(), encoder, - 1, 1, reportEntry.getSourceName(), reportEntry.getSourceText(), reportEntry.getName(), - reportEntry.getNameText(), reportEntry.getGroup(), reportEntry.getMessage(), stackTraceWrapper.message, - stackTraceWrapper.smartTrimmedStackTrace, stackTraceWrapper.stackTrace ); - - ByteBuffer result = ByteBuffer.allocate( bufferMaxLength ); - - encodeHeader( result, operation, reportEntry.getRunMode(), reportEntry.getTestRunId() ); - encodeCharset( result ); - - encodeString( encoder, result, reportEntry.getSourceName() ); - encodeString( encoder, result, reportEntry.getSourceText() ); - encodeString( encoder, result, reportEntry.getName() ); - encodeString( encoder, result, reportEntry.getNameText() ); - encodeString( encoder, result, reportEntry.getGroup() ); - encodeString( encoder, result, reportEntry.getMessage() ); - encodeInteger( result, reportEntry.getElapsed() ); - - encode( encoder, result, stackTraceWrapper ); + int bufferMaxLength = estimateBufferLength( + operation.getOpcode().length(), + reportEntry.getRunMode(), + encoder, + 1, + 1, + reportEntry.getSourceName(), + reportEntry.getSourceText(), + reportEntry.getName(), + reportEntry.getNameText(), + reportEntry.getGroup(), + reportEntry.getMessage(), + stackTraceWrapper.message, + stackTraceWrapper.smartTrimmedStackTrace, + stackTraceWrapper.stackTrace); + + ByteBuffer result = ByteBuffer.allocate(bufferMaxLength); + + encodeHeader(result, operation, reportEntry.getRunMode(), reportEntry.getTestRunId()); + encodeCharset(result); + + encodeString(encoder, result, reportEntry.getSourceName()); + encodeString(encoder, result, reportEntry.getSourceText()); + encodeString(encoder, result, reportEntry.getName()); + encodeString(encoder, result, reportEntry.getNameText()); + encodeString(encoder, result, reportEntry.getGroup()); + encodeString(encoder, result, reportEntry.getMessage()); + encodeInteger(result, reportEntry.getElapsed()); + + encode(encoder, result, stackTraceWrapper); return result; } - ByteBuffer encodeMessage( ForkedProcessEventType eventType, RunMode runMode, Long testRunId, String message ) - { + ByteBuffer encodeMessage(ForkedProcessEventType eventType, RunMode runMode, Long testRunId, String message) { CharsetEncoder encoder = newCharsetEncoder(); - int bufferMaxLength = estimateBufferLength( eventType.getOpcode().length(), runMode, encoder, 0, - 1, message ); - ByteBuffer result = ByteBuffer.allocate( bufferMaxLength ); - encode( encoder, result, eventType, runMode, testRunId, message ); + int bufferMaxLength = estimateBufferLength(eventType.getOpcode().length(), runMode, encoder, 0, 1, message); + ByteBuffer result = ByteBuffer.allocate(bufferMaxLength); + encode(encoder, result, eventType, runMode, testRunId, message); return result; } - ByteBuffer encodeMessage( ForkedProcessEventType eventType, String message ) - { + ByteBuffer encodeMessage(ForkedProcessEventType eventType, String message) { CharsetEncoder encoder = newCharsetEncoder(); - int bufferMaxLength = estimateBufferLength( eventType.getOpcode().length(), null, encoder, 0, 0, message ); - ByteBuffer result = ByteBuffer.allocate( bufferMaxLength ); - encode( encoder, result, eventType, message ); + int bufferMaxLength = estimateBufferLength(eventType.getOpcode().length(), null, encoder, 0, 0, message); + ByteBuffer result = ByteBuffer.allocate(bufferMaxLength); + encode(encoder, result, eventType, message); return result; } - private static String toStackTrace( StackTraceWriter stw, boolean trimStackTraces ) - { - if ( stw == null ) - { + private static String toStackTrace(StackTraceWriter stw, boolean trimStackTraces) { + if (stw == null) { return null; } return trimStackTraces ? stw.writeTrimmedTraceToString() : stw.writeTraceToString(); } - private static final class StackTrace - { + private static final class StackTrace { final String message; final String smartTrimmedStackTrace; final String stackTrace; - StackTrace( StackTraceWriter stackTraceWriter, boolean trimStackTraces ) - { + StackTrace(StackTraceWriter stackTraceWriter, boolean trimStackTraces) { SafeThrowable throwable = stackTraceWriter == null ? null : stackTraceWriter.getThrowable(); message = throwable == null ? null : throwable.getLocalizedMessage(); smartTrimmedStackTrace = stackTraceWriter == null ? null : stackTraceWriter.smartTrimmedStackTrace(); - stackTrace = stackTraceWriter == null ? null : toStackTrace( stackTraceWriter, trimStackTraces ); + stackTrace = stackTraceWriter == null ? null : toStackTrace(stackTraceWriter, trimStackTraces); } } } diff --git a/surefire-booter/src/main/java/org/apache/maven/surefire/booter/spi/LegacyMasterProcessChannelProcessorFactory.java b/surefire-booter/src/main/java/org/apache/maven/surefire/booter/spi/LegacyMasterProcessChannelProcessorFactory.java index 3d96f06631..e18a43a6cd 100644 --- a/surefire-booter/src/main/java/org/apache/maven/surefire/booter/spi/LegacyMasterProcessChannelProcessorFactory.java +++ b/surefire-booter/src/main/java/org/apache/maven/surefire/booter/spi/LegacyMasterProcessChannelProcessorFactory.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.booter.spi; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,16 +16,18 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.booter.spi; + +import javax.annotation.Nonnull; + +import java.io.IOException; +import java.net.MalformedURLException; import org.apache.maven.surefire.api.booter.MasterProcessChannelDecoder; import org.apache.maven.surefire.api.booter.MasterProcessChannelEncoder; import org.apache.maven.surefire.api.fork.ForkNodeArguments; import org.apache.maven.surefire.api.util.internal.WritableBufferedByteChannel; -import javax.annotation.Nonnull; -import java.io.IOException; -import java.net.MalformedURLException; - import static org.apache.maven.surefire.api.util.internal.Channels.newBufferedChannel; /** @@ -37,37 +37,30 @@ * @author Tibor Digana (tibor17) * @since 3.0.0-M5 */ -public class LegacyMasterProcessChannelProcessorFactory - extends AbstractMasterProcessChannelProcessorFactory -{ +public class LegacyMasterProcessChannelProcessorFactory extends AbstractMasterProcessChannelProcessorFactory { private static final int FLUSH_PERIOD_MILLIS = 100; @Override - public boolean canUse( String channelConfig ) - { - return channelConfig.startsWith( "pipe://" ); + public boolean canUse(String channelConfig) { + return channelConfig.startsWith("pipe://"); } @Override - public void connect( String channelConfig ) throws IOException - { - if ( !canUse( channelConfig ) ) - { - throw new MalformedURLException( "Unknown channel string " + channelConfig ); + public void connect(String channelConfig) throws IOException { + if (!canUse(channelConfig)) { + throw new MalformedURLException("Unknown channel string " + channelConfig); } } @Override - public MasterProcessChannelDecoder createDecoder( @Nonnull ForkNodeArguments forkingArguments ) - { - return new CommandChannelDecoder( newBufferedChannel( System.in ), forkingArguments ); + public MasterProcessChannelDecoder createDecoder(@Nonnull ForkNodeArguments forkingArguments) { + return new CommandChannelDecoder(newBufferedChannel(System.in), forkingArguments); } @Override - public MasterProcessChannelEncoder createEncoder( @Nonnull ForkNodeArguments forkingArguments ) - { - WritableBufferedByteChannel channel = newBufferedChannel( System.out ); - schedulePeriodicFlusher( FLUSH_PERIOD_MILLIS, channel ); - return new EventChannelEncoder( channel ); + public MasterProcessChannelEncoder createEncoder(@Nonnull ForkNodeArguments forkingArguments) { + WritableBufferedByteChannel channel = newBufferedChannel(System.out); + schedulePeriodicFlusher(FLUSH_PERIOD_MILLIS, channel); + return new EventChannelEncoder(channel); } } diff --git a/surefire-booter/src/main/java/org/apache/maven/surefire/booter/spi/SurefireMasterProcessChannelProcessorFactory.java b/surefire-booter/src/main/java/org/apache/maven/surefire/booter/spi/SurefireMasterProcessChannelProcessorFactory.java index 6af7bb846a..e93bf08239 100644 --- a/surefire-booter/src/main/java/org/apache/maven/surefire/booter/spi/SurefireMasterProcessChannelProcessorFactory.java +++ b/surefire-booter/src/main/java/org/apache/maven/surefire/booter/spi/SurefireMasterProcessChannelProcessorFactory.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.booter.spi; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,13 +16,10 @@ * specific language governing permissions and limitations * under the License. */ - -import org.apache.maven.surefire.api.booter.MasterProcessChannelDecoder; -import org.apache.maven.surefire.api.booter.MasterProcessChannelEncoder; -import org.apache.maven.surefire.api.fork.ForkNodeArguments; -import org.apache.maven.surefire.api.util.internal.WritableBufferedByteChannel; +package org.apache.maven.surefire.booter.spi; import javax.annotation.Nonnull; + import java.io.IOException; import java.net.InetSocketAddress; import java.net.MalformedURLException; @@ -37,6 +32,11 @@ import java.util.StringTokenizer; import java.util.concurrent.ExecutionException; +import org.apache.maven.surefire.api.booter.MasterProcessChannelDecoder; +import org.apache.maven.surefire.api.booter.MasterProcessChannelEncoder; +import org.apache.maven.surefire.api.fork.ForkNodeArguments; +import org.apache.maven.surefire.api.util.internal.WritableBufferedByteChannel; + import static java.net.StandardSocketOptions.SO_KEEPALIVE; import static java.net.StandardSocketOptions.SO_REUSEADDR; import static java.net.StandardSocketOptions.TCP_NODELAY; @@ -55,105 +55,81 @@ * @author Tibor Digana (tibor17) * @since 3.0.0-M5 */ -public class SurefireMasterProcessChannelProcessorFactory - extends AbstractMasterProcessChannelProcessorFactory -{ +public class SurefireMasterProcessChannelProcessorFactory extends AbstractMasterProcessChannelProcessorFactory { private static final int FLUSH_PERIOD_MILLIS = 100; private volatile AsynchronousSocketChannel clientSocketChannel; @Override - public boolean canUse( String channelConfig ) - { - return channelConfig.startsWith( "tcp://" ); + public boolean canUse(String channelConfig) { + return channelConfig.startsWith("tcp://"); } @Override - public void connect( String channelConfig ) throws IOException - { - if ( !canUse( channelConfig ) ) - { - throw new MalformedURLException( "Unknown channel string " + channelConfig ); + public void connect(String channelConfig) throws IOException { + if (!canUse(channelConfig)) { + throw new MalformedURLException("Unknown channel string " + channelConfig); } - try - { - URI uri = new URI( channelConfig ); - InetSocketAddress hostAddress = new InetSocketAddress( uri.getHost(), uri.getPort() ); - clientSocketChannel = open( withFixedThreadPool( 2, newDaemonThreadFactory() ) ); - setTrueOptions( SO_REUSEADDR, TCP_NODELAY, SO_KEEPALIVE ); - clientSocketChannel.connect( hostAddress ).get(); - String sessionId = extractSessionId( uri ); - if ( sessionId != null ) - { - ByteBuffer buff = ByteBuffer.wrap( sessionId.getBytes( US_ASCII ) ); - while ( buff.hasRemaining() ) - { - clientSocketChannel.write( buff ).get(); + try { + URI uri = new URI(channelConfig); + InetSocketAddress hostAddress = new InetSocketAddress(uri.getHost(), uri.getPort()); + clientSocketChannel = open(withFixedThreadPool(2, newDaemonThreadFactory())); + setTrueOptions(SO_REUSEADDR, TCP_NODELAY, SO_KEEPALIVE); + clientSocketChannel.connect(hostAddress).get(); + String sessionId = extractSessionId(uri); + if (sessionId != null) { + ByteBuffer buff = ByteBuffer.wrap(sessionId.getBytes(US_ASCII)); + while (buff.hasRemaining()) { + clientSocketChannel.write(buff).get(); } } - } - catch ( URISyntaxException | InterruptedException e ) - { - throw new IOException( e.getLocalizedMessage(), e ); - } - catch ( ExecutionException e ) - { - throw new IOException( e.getLocalizedMessage(), e.getCause() ); + } catch (URISyntaxException | InterruptedException e) { + throw new IOException(e.getLocalizedMessage(), e); + } catch (ExecutionException e) { + throw new IOException(e.getLocalizedMessage(), e.getCause()); } } @Override - public MasterProcessChannelDecoder createDecoder( @Nonnull ForkNodeArguments forkingArguments ) - { - ReadableByteChannel bufferedChannel = newBufferedChannel( newInputStream( clientSocketChannel ) ); - return new CommandChannelDecoder( bufferedChannel, forkingArguments ); + public MasterProcessChannelDecoder createDecoder(@Nonnull ForkNodeArguments forkingArguments) { + ReadableByteChannel bufferedChannel = newBufferedChannel(newInputStream(clientSocketChannel)); + return new CommandChannelDecoder(bufferedChannel, forkingArguments); } @Override - public MasterProcessChannelEncoder createEncoder( @Nonnull ForkNodeArguments forkingArguments ) - { - WritableBufferedByteChannel channel = newBufferedChannel( newOutputStream( clientSocketChannel ) ); - schedulePeriodicFlusher( FLUSH_PERIOD_MILLIS, channel ); - return new EventChannelEncoder( channel ); + public MasterProcessChannelEncoder createEncoder(@Nonnull ForkNodeArguments forkingArguments) { + WritableBufferedByteChannel channel = newBufferedChannel(newOutputStream(clientSocketChannel)); + schedulePeriodicFlusher(FLUSH_PERIOD_MILLIS, channel); + return new EventChannelEncoder(channel); } @Override - public void close() throws IOException - { + public void close() throws IOException { super.close(); - if ( clientSocketChannel != null && clientSocketChannel.isOpen() ) - { + if (clientSocketChannel != null && clientSocketChannel.isOpen()) { clientSocketChannel.close(); } } @SafeVarargs - private final void setTrueOptions( SocketOption... options ) - throws IOException - { - for ( SocketOption option : options ) - { - if ( clientSocketChannel.supportedOptions().contains( option ) ) - { - clientSocketChannel.setOption( option, true ); + private final void setTrueOptions(SocketOption... options) throws IOException { + for (SocketOption option : options) { + if (clientSocketChannel.supportedOptions().contains(option)) { + clientSocketChannel.setOption(option, true); } } } - private static String extractSessionId( URI uri ) - { + private static String extractSessionId(URI uri) { String query = uri.getQuery(); - if ( query == null ) - { + if (query == null) { return null; } - for ( StringTokenizer tokenizer = new StringTokenizer( query, "&" ); tokenizer.hasMoreTokens(); ) - { + for (StringTokenizer tokenizer = new StringTokenizer(query, "&"); tokenizer.hasMoreTokens(); ) { String token = tokenizer.nextToken(); - int delimiter = token.indexOf( '=' ); - if ( delimiter != -1 && "sessionId".equals( token.substring( 0, delimiter ) ) ) - { - return token.substring( delimiter + 1 ); + int delimiter = token.indexOf('='); + if (delimiter != -1 && "sessionId".equals(token.substring(0, delimiter))) { + return token.substring(delimiter + 1); } } return null; diff --git a/surefire-booter/src/main/java/org/apache/maven/surefire/booter/stream/CommandDecoder.java b/surefire-booter/src/main/java/org/apache/maven/surefire/booter/stream/CommandDecoder.java index 4a7e257f71..3a48ca92dd 100644 --- a/surefire-booter/src/main/java/org/apache/maven/surefire/booter/stream/CommandDecoder.java +++ b/surefire-booter/src/main/java/org/apache/maven/surefire/booter/stream/CommandDecoder.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.booter.stream; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,16 +16,10 @@ * specific language governing permissions and limitations * under the License. */ - -import org.apache.maven.surefire.api.booter.Command; -import org.apache.maven.surefire.api.booter.MasterProcessCommand; -import org.apache.maven.surefire.api.booter.Shutdown; -import org.apache.maven.surefire.api.fork.ForkNodeArguments; -import org.apache.maven.surefire.api.stream.AbstractStreamDecoder; -import org.apache.maven.surefire.api.stream.MalformedChannelException; -import org.apache.maven.surefire.api.stream.SegmentType; +package org.apache.maven.surefire.booter.stream; import javax.annotation.Nonnull; + import java.io.BufferedOutputStream; import java.io.File; import java.io.FileNotFoundException; @@ -37,6 +29,14 @@ import java.nio.channels.ReadableByteChannel; import java.util.concurrent.FutureTask; +import org.apache.maven.surefire.api.booter.Command; +import org.apache.maven.surefire.api.booter.MasterProcessCommand; +import org.apache.maven.surefire.api.booter.Shutdown; +import org.apache.maven.surefire.api.fork.ForkNodeArguments; +import org.apache.maven.surefire.api.stream.AbstractStreamDecoder; +import org.apache.maven.surefire.api.stream.MalformedChannelException; +import org.apache.maven.surefire.api.stream.SegmentType; + import static org.apache.maven.surefire.api.booter.Command.BYE_ACK; import static org.apache.maven.surefire.api.booter.Command.NOOP; import static org.apache.maven.surefire.api.booter.Command.SKIP_SINCE_NEXT_TEST; @@ -53,94 +53,71 @@ /** * */ -public class CommandDecoder extends AbstractStreamDecoder -{ +public class CommandDecoder extends AbstractStreamDecoder { private static final int DEBUG_SINK_BUFFER_SIZE = 64 * 1024; private static final int NO_POSITION = -1; - private static final SegmentType[] COMMAND_WITHOUT_DATA = new SegmentType[] { - END_OF_FRAME - }; + private static final SegmentType[] COMMAND_WITHOUT_DATA = new SegmentType[] {END_OF_FRAME}; - private static final SegmentType[] COMMAND_WITH_ONE_STRING = new SegmentType[] { - STRING_ENCODING, - DATA_STRING, - END_OF_FRAME - }; + private static final SegmentType[] COMMAND_WITH_ONE_STRING = + new SegmentType[] {STRING_ENCODING, DATA_STRING, END_OF_FRAME}; private final ForkNodeArguments arguments; private final OutputStream debugSink; - public CommandDecoder( @Nonnull ReadableByteChannel channel, - @Nonnull ForkNodeArguments arguments ) - { - super( channel, arguments, COMMAND_TYPES ); + public CommandDecoder(@Nonnull ReadableByteChannel channel, @Nonnull ForkNodeArguments arguments) { + super(channel, arguments, COMMAND_TYPES); this.arguments = arguments; debugSink = newDebugSink(); } @Override - public Command decode( @Nonnull Memento memento ) throws IOException, MalformedChannelException - { - try - { - MasterProcessCommand commandType = readMessageType( memento ); - if ( commandType == null ) - { - throw new MalformedFrameException( memento.getLine().getPositionByteBuffer(), - memento.getByteBuffer().position() ); + public Command decode(@Nonnull Memento memento) throws IOException, MalformedChannelException { + try { + MasterProcessCommand commandType = readMessageType(memento); + if (commandType == null) { + throw new MalformedFrameException( + memento.getLine().getPositionByteBuffer(), + memento.getByteBuffer().position()); } - for ( SegmentType segmentType : nextSegmentType( commandType ) ) - { - switch ( segmentType ) - { + for (SegmentType segmentType : nextSegmentType(commandType)) { + switch (segmentType) { case STRING_ENCODING: - memento.setCharset( readCharset( memento ) ); + memento.setCharset(readCharset(memento)); break; case DATA_STRING: - memento.getData().add( readString( memento ) ); + memento.getData().add(readString(memento)); break; case DATA_INTEGER: - memento.getData().add( readInteger( memento ) ); + memento.getData().add(readInteger(memento)); break; case END_OF_FRAME: - memento.getLine().setPositionByteBuffer( memento.getByteBuffer().position() ); + memento.getLine() + .setPositionByteBuffer(memento.getByteBuffer().position()); memento.getLine().clear(); - return toMessage( commandType, memento ); + return toMessage(commandType, memento); default: - memento.getLine().setPositionByteBuffer( NO_POSITION ); - arguments.dumpStreamText( "Unknown enum (" - + SegmentType.class.getSimpleName() - + ") " - + segmentType ); + memento.getLine().setPositionByteBuffer(NO_POSITION); + arguments.dumpStreamText( + "Unknown enum (" + SegmentType.class.getSimpleName() + ") " + segmentType); } } - } - catch ( MalformedFrameException e ) - { - if ( e.hasValidPositions() ) - { + } catch (MalformedFrameException e) { + if (e.hasValidPositions()) { int length = e.readTo() - e.readFrom(); - memento.getLine().write( memento.getByteBuffer(), e.readFrom(), length ); + memento.getLine().write(memento.getByteBuffer(), e.readFrom(), length); } return null; - } - catch ( RuntimeException e ) - { - getArguments().dumpStreamException( e ); + } catch (RuntimeException e) { + getArguments().dumpStreamException(e); return null; - } - catch ( IOException e ) - { - if ( !( e.getCause() instanceof InterruptedException ) ) - { - printRemainingStream( memento ); + } catch (IOException e) { + if (!(e.getCause() instanceof InterruptedException)) { + printRemainingStream(memento); } throw e; - } - finally - { + } finally { memento.reset(); } @@ -149,17 +126,14 @@ public Command decode( @Nonnull Memento memento ) throws IOException, MalformedC @Nonnull @Override - protected final byte[] getEncodedMagicNumber() - { + protected final byte[] getEncodedMagicNumber() { return MAGIC_NUMBER_FOR_COMMANDS_BYTES; } @Nonnull @Override - protected SegmentType[] nextSegmentType( @Nonnull MasterProcessCommand commandType ) - { - switch ( commandType ) - { + protected SegmentType[] nextSegmentType(@Nonnull MasterProcessCommand commandType) { + switch (commandType) { case NOOP: case BYE_ACK: case SKIP_SINCE_NEXT_TEST: @@ -169,89 +143,75 @@ protected SegmentType[] nextSegmentType( @Nonnull MasterProcessCommand commandTy case SHUTDOWN: return COMMAND_WITH_ONE_STRING; default: - throw new IllegalArgumentException( "Unknown enum " + commandType ); + throw new IllegalArgumentException("Unknown enum " + commandType); } } @Nonnull @Override - protected Command toMessage( @Nonnull MasterProcessCommand commandType, @Nonnull Memento memento ) - throws MalformedFrameException - { - switch ( commandType ) - { + protected Command toMessage(@Nonnull MasterProcessCommand commandType, @Nonnull Memento memento) + throws MalformedFrameException { + switch (commandType) { case NOOP: - checkArguments( memento, 0 ); + checkArguments(memento, 0); return NOOP; case BYE_ACK: - checkArguments( memento, 0 ); + checkArguments(memento, 0); return BYE_ACK; case SKIP_SINCE_NEXT_TEST: - checkArguments( memento, 0 ); + checkArguments(memento, 0); return SKIP_SINCE_NEXT_TEST; case TEST_SET_FINISHED: - checkArguments( memento, 0 ); + checkArguments(memento, 0); return TEST_SET_FINISHED; case RUN_CLASS: - checkArguments( memento, 1 ); - return toRunClass( (String) memento.getData().get( 0 ) ); + checkArguments(memento, 1); + return toRunClass((String) memento.getData().get(0)); case SHUTDOWN: - checkArguments( memento, 1 ); - return toShutdown( Shutdown.parameterOf( (String) memento.getData().get( 0 ) ) ); + checkArguments(memento, 1); + return toShutdown( + Shutdown.parameterOf((String) memento.getData().get(0))); default: - throw new IllegalArgumentException( "Missing a branch for the event type " + commandType ); + throw new IllegalArgumentException("Missing a branch for the event type " + commandType); } } @Override - protected void debugStream( byte[] array, int position, int remaining ) - { - if ( debugSink == null ) - { + protected void debugStream(byte[] array, int position, int remaining) { + if (debugSink == null) { return; } - try - { - debugSink.write( array, position, remaining ); - } - catch ( IOException e ) - { + try { + debugSink.write(array, position, remaining); + } catch (IOException e) { // logger file was deleted // System.out is already used by the stream in this decoder } } - private OutputStream newDebugSink() - { + private OutputStream newDebugSink() { final File sink = arguments.getCommandStreamBinaryFile(); - if ( sink == null ) - { + if (sink == null) { return null; } - try - { - OutputStream fos = new FileOutputStream( sink, true ); - final OutputStream os = new BufferedOutputStream( fos, DEBUG_SINK_BUFFER_SIZE ); - addShutDownHook( new Thread( new FutureTask<>( () -> - { + try { + OutputStream fos = new FileOutputStream(sink, true); + final OutputStream os = new BufferedOutputStream(fos, DEBUG_SINK_BUFFER_SIZE); + addShutDownHook(new Thread(new FutureTask<>(() -> { os.close(); return null; - } ) ) ); + }))); return os; - } - catch ( FileNotFoundException e ) - { + } catch (FileNotFoundException e) { return null; } } @Override - public void close() throws IOException - { - if ( debugSink != null ) - { + public void close() throws IOException { + if (debugSink != null) { debugSink.close(); } } diff --git a/surefire-booter/src/main/java/org/apache/maven/surefire/booter/stream/EventEncoder.java b/surefire-booter/src/main/java/org/apache/maven/surefire/booter/stream/EventEncoder.java index f982017126..ebc50f5148 100644 --- a/surefire-booter/src/main/java/org/apache/maven/surefire/booter/stream/EventEncoder.java +++ b/surefire-booter/src/main/java/org/apache/maven/surefire/booter/stream/EventEncoder.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.booter.stream; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,15 +16,17 @@ * specific language governing permissions and limitations * under the License. */ - -import org.apache.maven.surefire.api.booter.ForkedProcessEventType; -import org.apache.maven.surefire.api.stream.AbstractStreamEncoder; -import org.apache.maven.surefire.api.util.internal.WritableBufferedByteChannel; +package org.apache.maven.surefire.booter.stream; import javax.annotation.Nonnull; + import java.nio.charset.Charset; import java.nio.charset.CharsetEncoder; +import org.apache.maven.surefire.api.booter.ForkedProcessEventType; +import org.apache.maven.surefire.api.stream.AbstractStreamEncoder; +import org.apache.maven.surefire.api.util.internal.WritableBufferedByteChannel; + import static org.apache.maven.surefire.api.booter.Constants.DEFAULT_STREAM_ENCODING; import static org.apache.maven.surefire.api.booter.Constants.DEFAULT_STREAM_ENCODING_BYTES; import static org.apache.maven.surefire.api.booter.Constants.MAGIC_NUMBER_FOR_EVENTS_BYTES; @@ -34,45 +34,38 @@ /** * */ -public class EventEncoder extends AbstractStreamEncoder -{ - public EventEncoder( WritableBufferedByteChannel out ) - { - super( out ); +public class EventEncoder extends AbstractStreamEncoder { + public EventEncoder(WritableBufferedByteChannel out) { + super(out); } @Nonnull @Override - protected final byte[] getEncodedMagicNumber() - { + protected final byte[] getEncodedMagicNumber() { return MAGIC_NUMBER_FOR_EVENTS_BYTES; } @Nonnull @Override - protected final byte[] enumToByteArray( @Nonnull ForkedProcessEventType e ) - { + protected final byte[] enumToByteArray(@Nonnull ForkedProcessEventType e) { return e.getOpcodeBinary(); } @Nonnull @Override - protected final byte[] getEncodedCharsetName() - { + protected final byte[] getEncodedCharsetName() { return DEFAULT_STREAM_ENCODING_BYTES; } @Nonnull @Override - protected final Charset getCharset() - { + protected final Charset getCharset() { return DEFAULT_STREAM_ENCODING; } @Nonnull @Override - protected final CharsetEncoder newCharsetEncoder() - { + protected final CharsetEncoder newCharsetEncoder() { return getCharset().newEncoder(); } } diff --git a/surefire-booter/src/test/java/org/apache/maven/surefire/booter/BooterDeserializerTest.java b/surefire-booter/src/test/java/org/apache/maven/surefire/booter/BooterDeserializerTest.java index 32cf1545f3..1148bec371 100644 --- a/surefire-booter/src/test/java/org/apache/maven/surefire/booter/BooterDeserializerTest.java +++ b/surefire-booter/src/test/java/org/apache/maven/surefire/booter/BooterDeserializerTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.booter; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,13 +16,14 @@ * specific language governing permissions and limitations * under the License. */ - -import org.junit.Test; +package org.apache.maven.surefire.booter; import java.io.IOException; import java.io.InputStream; import java.io.StringBufferInputStream; +import org.junit.Test; + import static org.apache.maven.surefire.booter.BooterConstants.PROCESS_CHECKER; import static org.apache.maven.surefire.booter.BooterConstants.PROVIDER_CONFIGURATION; import static org.apache.maven.surefire.booter.BooterConstants.USESYSTEMCLASSLOADER; @@ -34,24 +33,24 @@ /** * */ -public class BooterDeserializerTest -{ +public class BooterDeserializerTest { @Test - public void testStartupConfiguration() throws IOException - { - InputStream is = new StringBufferInputStream( PROCESS_CHECKER + "=all\n" + public void testStartupConfiguration() throws IOException { + InputStream is = new StringBufferInputStream(PROCESS_CHECKER + "=all\n" + USESYSTEMCLASSLOADER + "=true\n" - + PROVIDER_CONFIGURATION + "=abc.MyProvider" ); + + PROVIDER_CONFIGURATION + "=abc.MyProvider"); - BooterDeserializer deserializer = new BooterDeserializer( is ); + BooterDeserializer deserializer = new BooterDeserializer(is); - assertThat( deserializer.getStartupConfiguration().getProcessChecker() ) - .isEqualTo( ALL ); + assertThat(deserializer.getStartupConfiguration().getProcessChecker()).isEqualTo(ALL); - assertThat( deserializer.getStartupConfiguration().getClassLoaderConfiguration().isUseSystemClassLoader() ) + assertThat(deserializer + .getStartupConfiguration() + .getClassLoaderConfiguration() + .isUseSystemClassLoader()) .isTrue(); - assertThat( deserializer.getStartupConfiguration().getProviderClassName() ) - .isEqualTo( "abc.MyProvider" ); + assertThat(deserializer.getStartupConfiguration().getProviderClassName()) + .isEqualTo("abc.MyProvider"); } } diff --git a/surefire-booter/src/test/java/org/apache/maven/surefire/booter/ClasspathTest.java b/surefire-booter/src/test/java/org/apache/maven/surefire/booter/ClasspathTest.java index 023e8360b9..722129ad24 100644 --- a/surefire-booter/src/test/java/org/apache/maven/surefire/booter/ClasspathTest.java +++ b/surefire-booter/src/test/java/org/apache/maven/surefire/booter/ClasspathTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.booter; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.booter; import java.io.File; import java.net.URI; @@ -33,200 +32,164 @@ /** * @author Kristian Rosenvold */ -public class ClasspathTest - extends TestCase -{ +public class ClasspathTest extends TestCase { private static final String DUMMY_PROPERTY_NAME = "dummyProperty"; private static final String DUMMY_URL_1 = "foo.jar"; private static final String DUMMY_URL_2 = "bar.jar"; - public void testShouldWriteEmptyPropertyForEmptyClasspath() - { + public void testShouldWriteEmptyPropertyForEmptyClasspath() { Classpath classpath = Classpath.emptyClasspath(); - classpath.writeToSystemProperty( DUMMY_PROPERTY_NAME ); - assertEquals( "", System.getProperty( DUMMY_PROPERTY_NAME ) ); + classpath.writeToSystemProperty(DUMMY_PROPERTY_NAME); + assertEquals("", System.getProperty(DUMMY_PROPERTY_NAME)); } - public void testShouldWriteSeparatedElementsAsSystemProperty() - { - Classpath classpath = Classpath.emptyClasspath() - .addClassPathElementUrl( DUMMY_URL_1 ) - .addClassPathElementUrl( DUMMY_URL_2 ); - classpath.writeToSystemProperty( DUMMY_PROPERTY_NAME ); - assertEquals( DUMMY_URL_1 + File.pathSeparatorChar + DUMMY_URL_2 + File.pathSeparatorChar, - System.getProperty( DUMMY_PROPERTY_NAME ) ); + public void testShouldWriteSeparatedElementsAsSystemProperty() { + Classpath classpath = + Classpath.emptyClasspath().addClassPathElementUrl(DUMMY_URL_1).addClassPathElementUrl(DUMMY_URL_2); + classpath.writeToSystemProperty(DUMMY_PROPERTY_NAME); + assertEquals( + DUMMY_URL_1 + File.pathSeparatorChar + DUMMY_URL_2 + File.pathSeparatorChar, + System.getProperty(DUMMY_PROPERTY_NAME)); } - public void testShouldAddNoDuplicateElements() - { - Classpath classpath = emptyClasspath() - .addClassPathElementUrl( DUMMY_URL_1 ) - .addClassPathElementUrl( DUMMY_URL_1 ); - assertClasspathConsistsOfElements( classpath, new String[]{ DUMMY_URL_1 } ); + public void testShouldAddNoDuplicateElements() { + Classpath classpath = + emptyClasspath().addClassPathElementUrl(DUMMY_URL_1).addClassPathElementUrl(DUMMY_URL_1); + assertClasspathConsistsOfElements(classpath, new String[] {DUMMY_URL_1}); } - public void testShouldJoinTwoNullClasspaths() - { - Classpath joinedClasspath = Classpath.join( null, null ); - assertEmptyClasspath( joinedClasspath ); + public void testShouldJoinTwoNullClasspaths() { + Classpath joinedClasspath = Classpath.join(null, null); + assertEmptyClasspath(joinedClasspath); } - public void testShouldHaveAllElementsAfterJoiningTwoDifferentClasspaths() - { + public void testShouldHaveAllElementsAfterJoiningTwoDifferentClasspaths() { Classpath firstClasspath = Classpath.emptyClasspath(); - Classpath secondClasspath = firstClasspath.addClassPathElementUrl( DUMMY_URL_1 ) - .addClassPathElementUrl( DUMMY_URL_2 ); - Classpath joinedClasspath = Classpath.join( firstClasspath, secondClasspath ); - assertClasspathConsistsOfElements( joinedClasspath, new String[]{ DUMMY_URL_1, DUMMY_URL_2 } ); + Classpath secondClasspath = + firstClasspath.addClassPathElementUrl(DUMMY_URL_1).addClassPathElementUrl(DUMMY_URL_2); + Classpath joinedClasspath = Classpath.join(firstClasspath, secondClasspath); + assertClasspathConsistsOfElements(joinedClasspath, new String[] {DUMMY_URL_1, DUMMY_URL_2}); } - public void testShouldNotHaveDuplicatesAfterJoiningTowClasspathsWithEqualElements() - { - Classpath firstClasspath = Classpath.emptyClasspath().addClassPathElementUrl( DUMMY_URL_1 ); - Classpath secondClasspath = Classpath.emptyClasspath().addClassPathElementUrl( DUMMY_URL_1 ); - Classpath joinedClasspath = Classpath.join( firstClasspath, secondClasspath ); - assertClasspathConsistsOfElements( joinedClasspath, new String[]{ DUMMY_URL_1 } ); + public void testShouldNotHaveDuplicatesAfterJoiningTowClasspathsWithEqualElements() { + Classpath firstClasspath = Classpath.emptyClasspath().addClassPathElementUrl(DUMMY_URL_1); + Classpath secondClasspath = Classpath.emptyClasspath().addClassPathElementUrl(DUMMY_URL_1); + Classpath joinedClasspath = Classpath.join(firstClasspath, secondClasspath); + assertClasspathConsistsOfElements(joinedClasspath, new String[] {DUMMY_URL_1}); } - public void testShouldNotBeAbleToRemoveElement() - { - try - { + public void testShouldNotBeAbleToRemoveElement() { + try { Classpath classpath = createClasspathWithTwoElements(); - classpath.getClassPath().remove( 0 ); - } - catch ( java.lang.UnsupportedOperationException ignore ) - { + classpath.getClassPath().remove(0); + } catch (java.lang.UnsupportedOperationException ignore) { } } - private void assertClasspathConsistsOfElements( Classpath classpath, String[] elements ) - { + private void assertClasspathConsistsOfElements(Classpath classpath, String[] elements) { List classpathElements = classpath.getClassPath(); - for ( String element : elements ) - { - assertTrue( "The element '" + element + " is missing.", classpathElements.contains( element ) ); + for (String element : elements) { + assertTrue("The element '" + element + " is missing.", classpathElements.contains(element)); } - assertEquals( "Wrong number of classpath elements.", elements.length, classpathElements.size() ); + assertEquals("Wrong number of classpath elements.", elements.length, classpathElements.size()); } - private void assertEmptyClasspath( Classpath classpath ) - { + private void assertEmptyClasspath(Classpath classpath) { List classpathElements = classpath.getClassPath(); - assertEquals( "Wrong number of classpath elements.", 0, classpathElements.size() ); + assertEquals("Wrong number of classpath elements.", 0, classpathElements.size()); } - private Classpath createClasspathWithTwoElements() - { + private Classpath createClasspathWithTwoElements() { Classpath classpath = Classpath.emptyClasspath(); - return classpath.addClassPathElementUrl( DUMMY_URL_1 ).addClassPathElementUrl( DUMMY_URL_2 ); + return classpath.addClassPathElementUrl(DUMMY_URL_1).addClassPathElementUrl(DUMMY_URL_2); } - public void testShouldThrowIllegalArgumentExceptionWhenNullIsAddedAsClassPathElementUrl() - { + public void testShouldThrowIllegalArgumentExceptionWhenNullIsAddedAsClassPathElementUrl() { Classpath classpath = Classpath.emptyClasspath(); - try - { - classpath.addClassPathElementUrl( null ); - fail( "IllegalArgumentException not thrown." ); - } - catch ( IllegalArgumentException expected ) - { + try { + classpath.addClassPathElementUrl(null); + fail("IllegalArgumentException not thrown."); + } catch (IllegalArgumentException expected) { } } - public void testShouldNotAddNullAsClassPathElementUrl() - { + public void testShouldNotAddNullAsClassPathElementUrl() { Classpath classpath = Classpath.emptyClasspath(); - try - { - classpath.addClassPathElementUrl( null ); + try { + classpath.addClassPathElementUrl(null); + } catch (IllegalArgumentException ignored) { } - catch ( IllegalArgumentException ignored ) - { - } - assertEmptyClasspath( classpath ); + assertEmptyClasspath(classpath); } - public void testCloneShouldBeEqual() - { - Classpath classpath = Classpath.emptyClasspath() - .addClassPathElementUrl( DUMMY_URL_1 ) - .addClassPathElementUrl( DUMMY_URL_2 ); + public void testCloneShouldBeEqual() { + Classpath classpath = + Classpath.emptyClasspath().addClassPathElementUrl(DUMMY_URL_1).addClassPathElementUrl(DUMMY_URL_2); - assertEquals( classpath, classpath ); - assertFalse( classpath.equals( null ) ); + assertEquals(classpath, classpath); + assertFalse(classpath.equals(null)); - assertEquals( 2, classpath.getClassPath().size() ); - assertEquals( classpath, classpath.clone() ); - assertEquals( classpath.hashCode(), classpath.clone().hashCode() ); + assertEquals(2, classpath.getClassPath().size()); + assertEquals(classpath, classpath.clone()); + assertEquals(classpath.hashCode(), classpath.clone().hashCode()); } - public void testIterator() - { - Classpath classpath = Classpath.emptyClasspath() - .addClassPathElementUrl( DUMMY_URL_1 ) - .addClassPathElementUrl( DUMMY_URL_2 ); + public void testIterator() { + Classpath classpath = + Classpath.emptyClasspath().addClassPathElementUrl(DUMMY_URL_1).addClassPathElementUrl(DUMMY_URL_2); Iterator it = classpath.iterator(); String url1 = it.hasNext() ? it.next() : null; String url2 = it.hasNext() ? it.next() : null; - assertEquals( DUMMY_URL_1, url1 ); - assertEquals( DUMMY_URL_2, url2 ); + assertEquals(DUMMY_URL_1, url1); + assertEquals(DUMMY_URL_2, url2); } - public void testLog() - { - Classpath classpath = Classpath.emptyClasspath() - .addClassPathElementUrl( DUMMY_URL_1 ) - .addClassPathElementUrl( DUMMY_URL_2 ); - String log = classpath.getLogMessage( "classpath:" ); - assertEquals( "classpath: " + DUMMY_URL_1 + " " + DUMMY_URL_2, log ); + public void testLog() { + Classpath classpath = + Classpath.emptyClasspath().addClassPathElementUrl(DUMMY_URL_1).addClassPathElementUrl(DUMMY_URL_2); + String log = classpath.getLogMessage("classpath:"); + assertEquals("classpath: " + DUMMY_URL_1 + " " + DUMMY_URL_2, log); } - public void testCompactLog() - { + public void testCompactLog() { Classpath classpath = Classpath.emptyClasspath() - .addClassPathElementUrl( "root" + File.separatorChar + DUMMY_URL_1 ) - .addClassPathElementUrl( "root" + File.separatorChar + DUMMY_URL_2 ); - String log = classpath.getCompactLogMessage( "classpath:" ); - assertEquals( "classpath: " + DUMMY_URL_1 + " " + DUMMY_URL_2, log ); + .addClassPathElementUrl("root" + File.separatorChar + DUMMY_URL_1) + .addClassPathElementUrl("root" + File.separatorChar + DUMMY_URL_2); + String log = classpath.getCompactLogMessage("classpath:"); + assertEquals("classpath: " + DUMMY_URL_1 + " " + DUMMY_URL_2, log); } - public void testLoadInNewClassLoader() throws Exception - { + public void testLoadInNewClassLoader() throws Exception { Class target = ConsoleLogger.class; - String thisPath = "/" + target.getName().replace( '.', '/' ) + ".class"; - URL url = target.getResource( thisPath ); - assertTrue( url.toString().endsWith( thisPath ) ); - String s = url.toString().replace( thisPath, "" ).replace( "!", "" ).replace( "jar:file:", "file:" ); - URI oneClasspath = new URI( s ); - assertTrue( "File: '" + oneClasspath + "' should exist", new File( oneClasspath ).exists() ); + String thisPath = "/" + target.getName().replace('.', '/') + ".class"; + URL url = target.getResource(thisPath); + assertTrue(url.toString().endsWith(thisPath)); + String s = url.toString().replace(thisPath, "").replace("!", "").replace("jar:file:", "file:"); + URI oneClasspath = new URI(s); + assertTrue("File: '" + oneClasspath + "' should exist", new File(oneClasspath).exists()); Classpath classpath = Classpath.emptyClasspath(); - ClassLoader classLoader = classpath.addClassPathElementUrl( new File( oneClasspath ).getCanonicalPath() ) - .createClassLoader( false, true, "" ); - Class cls = classLoader.loadClass( target.getName() ); - assertNotNull( cls ); - assertEquals( cls.getName(), target.getName() ); - assertNotSame( cls, target ); + ClassLoader classLoader = classpath + .addClassPathElementUrl(new File(oneClasspath).getCanonicalPath()) + .createClassLoader(false, true, ""); + Class cls = classLoader.loadClass(target.getName()); + assertNotNull(cls); + assertEquals(cls.getName(), target.getName()); + assertNotSame(cls, target); } - public void testDontLoadInNewClassLoader() throws SurefireExecutionException - { + public void testDontLoadInNewClassLoader() throws SurefireExecutionException { Class target = ConsoleLogger.class; - ClassLoader classLoader = emptyClasspath().createClassLoader( false, true, "" ); + ClassLoader classLoader = emptyClasspath().createClassLoader(false, true, ""); - try - { - classLoader.loadClass( target.getName() ); - fail( "Class should not be loaded" ); - } - catch ( ClassNotFoundException e ) - { - assertEquals( target.getName(), e.getMessage() ); + try { + classLoader.loadClass(target.getName()); + fail("Class should not be loaded"); + } catch (ClassNotFoundException e) { + assertEquals(target.getName(), e.getMessage()); } } } diff --git a/surefire-booter/src/test/java/org/apache/maven/surefire/booter/CommandReaderTest.java b/surefire-booter/src/test/java/org/apache/maven/surefire/booter/CommandReaderTest.java index 7fecd465a9..74a16729ee 100644 --- a/surefire-booter/src/test/java/org/apache/maven/surefire/booter/CommandReaderTest.java +++ b/surefire-booter/src/test/java/org/apache/maven/surefire/booter/CommandReaderTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.booter; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,20 +16,7 @@ * specific language governing permissions and limitations * under the License. */ - -import org.apache.maven.plugin.surefire.log.api.ConsoleLogger; -import org.apache.maven.plugin.surefire.log.api.NullConsoleLogger; -import org.apache.maven.surefire.api.booter.MasterProcessChannelDecoder; -import org.apache.maven.surefire.api.booter.Shutdown; -import org.apache.maven.surefire.api.fork.ForkNodeArguments; -import org.apache.maven.surefire.booter.spi.CommandChannelDecoder; -import org.apache.maven.surefire.booter.spi.EventChannelEncoder; -import org.apache.maven.surefire.api.testset.TestSetFailedException; -import org.apache.maven.surefire.api.util.internal.WritableBufferedByteChannel; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +package org.apache.maven.surefire.booter; import java.io.ByteArrayOutputStream; import java.io.IOException; @@ -46,6 +31,20 @@ import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; +import org.apache.maven.plugin.surefire.log.api.ConsoleLogger; +import org.apache.maven.plugin.surefire.log.api.NullConsoleLogger; +import org.apache.maven.surefire.api.booter.MasterProcessChannelDecoder; +import org.apache.maven.surefire.api.booter.Shutdown; +import org.apache.maven.surefire.api.fork.ForkNodeArguments; +import org.apache.maven.surefire.api.testset.TestSetFailedException; +import org.apache.maven.surefire.api.util.internal.WritableBufferedByteChannel; +import org.apache.maven.surefire.booter.spi.CommandChannelDecoder; +import org.apache.maven.surefire.booter.spi.EventChannelEncoder; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; + import static java.nio.charset.StandardCharsets.US_ASCII; import static org.apache.maven.surefire.api.util.internal.Channels.newBufferedChannel; import static org.apache.maven.surefire.api.util.internal.Channels.newChannel; @@ -62,230 +61,193 @@ * @author Tibor Digana (tibor17) * @since 2.19 */ -@RunWith( NewClassLoaderRunner.class ) -@SuppressWarnings( "checkstyle:magicnumber" ) -public class CommandReaderTest -{ +@RunWith(NewClassLoaderRunner.class) +@SuppressWarnings("checkstyle:magicnumber") +public class CommandReaderTest { private static final long DELAY = 200L; private static final long TEST_TIMEOUT = 15_000L; private final BlockingQueue blockingStream = new LinkedBlockingQueue<>(); private CommandReader reader; - static class A - { - } + static class A {} - static class B - { - } + static class B {} - static class C - { - } + static class C {} - static class D - { - } + static class D {} @Before - public void init() - { + public void init() { //noinspection ResultOfMethodCallIgnored Thread.interrupted(); InputStream realInputStream = new SystemInputStream(); - addTestToPipeline( getClass().getName() ); + addTestToPipeline(getClass().getName()); ConsoleLogger logger = new NullConsoleLogger(); - ForkNodeArguments args = new ForkedNodeArg( 1, false ); - MasterProcessChannelDecoder decoder = - new CommandChannelDecoder( newChannel( realInputStream ), args ); - reader = new CommandReader( decoder, Shutdown.DEFAULT, logger ); + ForkNodeArguments args = new ForkedNodeArg(1, false); + MasterProcessChannelDecoder decoder = new CommandChannelDecoder(newChannel(realInputStream), args); + reader = new CommandReader(decoder, Shutdown.DEFAULT, logger); } @After - public void deinit() - { + public void deinit() { reader.stop(); } @Test - public void readJustOneClass() - { - Iterator it = reader.getIterableClasses( new EventChannelEncoder( nul() ) ).iterator(); - assertTrue( it.hasNext() ); - assertThat( it.next(), is( getClass().getName() ) ); + public void readJustOneClass() { + Iterator it = + reader.getIterableClasses(new EventChannelEncoder(nul())).iterator(); + assertTrue(it.hasNext()); + assertThat(it.next(), is(getClass().getName())); reader.stop(); - assertFalse( it.hasNext() ); - try - { + assertFalse(it.hasNext()); + try { it.next(); fail(); - } - catch ( NoSuchElementException e ) - { + } catch (NoSuchElementException e) { // expected } } @Test - public void manyClasses() - { - Iterator it1 = reader.getIterableClasses( new EventChannelEncoder( nul() ) ).iterator(); - assertThat( it1.next(), is( getClass().getName() ) ); - addTestToPipeline( A.class.getName() ); - assertThat( it1.next(), is( A.class.getName() ) ); - addTestToPipeline( B.class.getName() ); - assertThat( it1.next(), is( B.class.getName() ) ); - addTestToPipeline( C.class.getName() ); - assertThat( it1.next(), is( C.class.getName() ) ); + public void manyClasses() { + Iterator it1 = + reader.getIterableClasses(new EventChannelEncoder(nul())).iterator(); + assertThat(it1.next(), is(getClass().getName())); + addTestToPipeline(A.class.getName()); + assertThat(it1.next(), is(A.class.getName())); + addTestToPipeline(B.class.getName()); + assertThat(it1.next(), is(B.class.getName())); + addTestToPipeline(C.class.getName()); + assertThat(it1.next(), is(C.class.getName())); addEndOfPipeline(); - addTestToPipeline( D.class.getName() ); - assertFalse( it1.hasNext() ); + addTestToPipeline(D.class.getName()); + assertFalse(it1.hasNext()); } @Test - public void twoIterators() throws Exception - { - Iterator it1 = reader.getIterableClasses( new EventChannelEncoder( nul() ) ).iterator(); + public void twoIterators() throws Exception { + Iterator it1 = + reader.getIterableClasses(new EventChannelEncoder(nul())).iterator(); - assertThat( it1.next(), is( getClass().getName() ) ); - addTestToPipeline( A.class.getName() ); - assertThat( it1.next(), is( A.class.getName() ) ); - addTestToPipeline( B.class.getName() ); + assertThat(it1.next(), is(getClass().getName())); + addTestToPipeline(A.class.getName()); + assertThat(it1.next(), is(A.class.getName())); + addTestToPipeline(B.class.getName()); - TimeUnit.MILLISECONDS.sleep( DELAY ); // give the test chance to fail + TimeUnit.MILLISECONDS.sleep(DELAY); // give the test chance to fail Iterator it2 = reader.iterated(); - assertThat( it1.next(), is( B.class.getName() ) ); - addTestToPipeline( C.class.getName() ); + assertThat(it1.next(), is(B.class.getName())); + addTestToPipeline(C.class.getName()); - assertThat( it2.hasNext(), is( true ) ); - assertThat( it2.next(), is( getClass().getName() ) ); - assertThat( it2.hasNext(), is( true ) ); - assertThat( it2.next(), is( A.class.getName() ) ); - assertThat( it2.hasNext() ).isFalse(); + assertThat(it2.hasNext(), is(true)); + assertThat(it2.next(), is(getClass().getName())); + assertThat(it2.hasNext(), is(true)); + assertThat(it2.next(), is(A.class.getName())); + assertThat(it2.hasNext()).isFalse(); - assertThat( it1.next(), is( C.class.getName() ) ); + assertThat(it1.next(), is(C.class.getName())); addEndOfPipeline(); - assertThat( it1.hasNext() ).isFalse(); + assertThat(it1.hasNext()).isFalse(); } - @Test( expected = NoSuchElementException.class ) - public void stopBeforeReadInThread() throws Throwable - { - Runnable runnable = new Runnable() - { + @Test(expected = NoSuchElementException.class) + public void stopBeforeReadInThread() throws Throwable { + Runnable runnable = new Runnable() { @Override - public void run() - { - Iterator it = reader.getIterableClasses( new EventChannelEncoder( nul() ) ).iterator(); - assertThat( it.next(), is( CommandReaderTest.class.getName() ) ); + public void run() { + Iterator it = reader.getIterableClasses(new EventChannelEncoder(nul())) + .iterator(); + assertThat(it.next(), is(CommandReaderTest.class.getName())); } }; - FutureTask futureTask = new FutureTask<>( runnable, null ); - Thread t = new Thread( futureTask ); + FutureTask futureTask = new FutureTask<>(runnable, null); + Thread t = new Thread(futureTask); reader.stop(); t.start(); - try - { + try { futureTask.get(); - } - catch ( ExecutionException e ) - { + } catch (ExecutionException e) { throw e.getCause(); } } @Test - public void readTwoClassesInThread() throws Throwable - { - final CountDownLatch counter = new CountDownLatch( 1 ); - Runnable runnable = new Runnable() - { + public void readTwoClassesInThread() throws Throwable { + final CountDownLatch counter = new CountDownLatch(1); + Runnable runnable = new Runnable() { @Override - public void run() - { - Iterator it = - reader.getIterableClasses( new EventChannelEncoder( nul() ) ).iterator(); - assertThat( it.next(), is( CommandReaderTest.class.getName() ) ); + public void run() { + Iterator it = reader.getIterableClasses(new EventChannelEncoder(nul())) + .iterator(); + assertThat(it.next(), is(CommandReaderTest.class.getName())); counter.countDown(); - assertThat( it.next(), is( Foo.class.getName() ) ); + assertThat(it.next(), is(Foo.class.getName())); } }; - FutureTask futureTask = new FutureTask<>( runnable, null ); - Thread t = new Thread( futureTask ); + FutureTask futureTask = new FutureTask<>(runnable, null); + Thread t = new Thread(futureTask); t.start(); counter.await(); - addTestToPipeline( Foo.class.getName() ); - try - { + addTestToPipeline(Foo.class.getName()); + try { futureTask.get(); - } - catch ( ExecutionException e ) - { + } catch (ExecutionException e) { throw e.getCause(); } } - @Test( timeout = TEST_TIMEOUT ) - public void shouldAwaitReaderUp() throws TestSetFailedException - { - assertTrue( reader.awaitStarted() ); + @Test(timeout = TEST_TIMEOUT) + public void shouldAwaitReaderUp() throws TestSetFailedException { + assertTrue(reader.awaitStarted()); reader.stop(); - assertFalse( reader.awaitStarted() ); + assertFalse(reader.awaitStarted()); } - private class SystemInputStream extends InputStream - { + private class SystemInputStream extends InputStream { @Override - public int read() throws IOException - { - try - { + public int read() throws IOException { + try { return CommandReaderTest.this.blockingStream.take(); - } - catch ( InterruptedException e ) - { - throw new IOException( e ); + } catch (InterruptedException e) { + throw new IOException(e); } } } - private void addTestToPipeline( String cls ) - { + private void addTestToPipeline(String cls) { int clsLength = cls.length(); - String cmd = new StringBuilder( 512 ) - .append( ":maven-surefire-command:" ) - .append( (char) 13 ) - .append( ":run-testclass:" ) - .append( (char) 5 ) - .append( ":UTF-8:" ) - .append( (char) ( clsLength >> 24 ) ) - .append( (char) ( ( clsLength >> 16 ) & 0xff ) ) - .append( (char) ( ( clsLength >> 8 ) & 0xff ) ) - .append( (char) ( clsLength & 0xff ) ) - .append( ":" ) - .append( cls ) - .append( ":" ) - .toString(); - - for ( byte cmdByte : cmd.getBytes( US_ASCII ) ) - { - blockingStream.add( cmdByte ); + String cmd = new StringBuilder(512) + .append(":maven-surefire-command:") + .append((char) 13) + .append(":run-testclass:") + .append((char) 5) + .append(":UTF-8:") + .append((char) (clsLength >> 24)) + .append((char) ((clsLength >> 16) & 0xff)) + .append((char) ((clsLength >> 8) & 0xff)) + .append((char) (clsLength & 0xff)) + .append(":") + .append(cls) + .append(":") + .toString(); + + for (byte cmdByte : cmd.getBytes(US_ASCII)) { + blockingStream.add(cmdByte); } } - private void addEndOfPipeline() - { - for ( byte cmdByte : ( ":maven-surefire-command:" + (char) 16 + ":testset-finished:" ).getBytes( US_ASCII ) ) - { - blockingStream.add( cmdByte ); + private void addEndOfPipeline() { + for (byte cmdByte : (":maven-surefire-command:" + (char) 16 + ":testset-finished:").getBytes(US_ASCII)) { + blockingStream.add(cmdByte); } } - private static WritableBufferedByteChannel nul() - { - return newBufferedChannel( new PrintStream( new ByteArrayOutputStream() ) ); + private static WritableBufferedByteChannel nul() { + return newBufferedChannel(new PrintStream(new ByteArrayOutputStream())); } } diff --git a/surefire-booter/src/test/java/org/apache/maven/surefire/booter/Foo.java b/surefire-booter/src/test/java/org/apache/maven/surefire/booter/Foo.java index e5483271d5..ac9da004b0 100644 --- a/surefire-booter/src/test/java/org/apache/maven/surefire/booter/Foo.java +++ b/surefire-booter/src/test/java/org/apache/maven/surefire/booter/Foo.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.booter; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.booter; import java.util.Map; @@ -32,8 +31,7 @@ /** * @author Kristian Rosenvold */ -public class Foo extends BaseProviderFactory -{ +public class Foo extends BaseProviderFactory { private Map providerProperties; private ReporterConfiguration reporterConfiguration; @@ -46,72 +44,62 @@ public class Foo extends BaseProviderFactory private boolean called; - Foo() - { - super( false ); + Foo() { + super(false); } @Override - public void setDirectoryScannerParameters( DirectoryScannerParameters directoryScanner ) - { - super.setDirectoryScannerParameters( directoryScanner ); + public void setDirectoryScannerParameters(DirectoryScannerParameters directoryScanner) { + super.setDirectoryScannerParameters(directoryScanner); this.called = true; } /** * @return true if it has been called */ - public Boolean isCalled() - { + public Boolean isCalled() { return called; } @Override - public void setProviderProperties( Map providerProperties ) - { - super.setProviderProperties( providerProperties ); + public void setProviderProperties(Map providerProperties) { + super.setProviderProperties(providerProperties); called = true; } @Override - public void setReporterConfiguration( ReporterConfiguration reporterConfiguration ) - { + public void setReporterConfiguration(ReporterConfiguration reporterConfiguration) { this.reporterConfiguration = reporterConfiguration; this.called = true; } @Override - public void setClassLoaders( ClassLoader testClassLoader ) - { + public void setClassLoaders(ClassLoader testClassLoader) { this.testClassLoader = testClassLoader; this.called = true; } @Override - public void setTestRequest( TestRequest testRequest ) - { - super.setTestRequest( testRequest ); + public void setTestRequest(TestRequest testRequest) { + super.setTestRequest(testRequest); this.called = true; } @Override - public void setTestArtifactInfo( TestArtifactInfo testArtifactInfo ) - { + public void setTestArtifactInfo(TestArtifactInfo testArtifactInfo) { this.testArtifactInfo = testArtifactInfo; this.called = true; } @Override - public void setRunOrderParameters( RunOrderParameters runOrderParameters ) - { - super.setRunOrderParameters( runOrderParameters ); + public void setRunOrderParameters(RunOrderParameters runOrderParameters) { + super.setRunOrderParameters(runOrderParameters); this.called = true; } @Override - public void setReporterFactory( ReporterFactory reporterFactory ) - { - super.setReporterFactory( reporterFactory ); + public void setReporterFactory(ReporterFactory reporterFactory) { + super.setReporterFactory(reporterFactory); called = true; } } diff --git a/surefire-booter/src/test/java/org/apache/maven/surefire/booter/ForkedBooterMockTest.java b/surefire-booter/src/test/java/org/apache/maven/surefire/booter/ForkedBooterMockTest.java index 62df899301..0c5dff7434 100644 --- a/surefire-booter/src/test/java/org/apache/maven/surefire/booter/ForkedBooterMockTest.java +++ b/surefire-booter/src/test/java/org/apache/maven/surefire/booter/ForkedBooterMockTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.booter; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,22 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.booter; + +import javax.annotation.Nonnull; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.net.InetSocketAddress; +import java.net.MalformedURLException; +import java.net.URI; +import java.nio.Buffer; +import java.nio.ByteBuffer; +import java.nio.channels.ServerSocketChannel; +import java.nio.channels.SocketChannel; +import java.util.UUID; +import java.util.concurrent.Callable; +import java.util.concurrent.FutureTask; import org.apache.maven.plugin.surefire.log.api.ConsoleLogger; import org.apache.maven.surefire.api.booter.MasterProcessChannelDecoder; @@ -45,20 +59,6 @@ import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; -import javax.annotation.Nonnull; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.net.InetSocketAddress; -import java.net.MalformedURLException; -import java.net.URI; -import java.nio.Buffer; -import java.nio.ByteBuffer; -import java.nio.channels.ServerSocketChannel; -import java.nio.channels.SocketChannel; -import java.util.UUID; -import java.util.concurrent.Callable; -import java.util.concurrent.FutureTask; - import static java.nio.charset.StandardCharsets.US_ASCII; import static java.util.concurrent.TimeUnit.SECONDS; import static org.apache.maven.surefire.api.util.internal.Channels.newBufferedChannel; @@ -86,16 +86,10 @@ /** * PowerMock tests for {@link ForkedBooter}. */ -@RunWith( PowerMockRunner.class ) -@PrepareForTest( { - PpidChecker.class, - ForkedBooter.class, - EventChannelEncoder.class, - ShutdownHookUtils.class -} ) -@PowerMockIgnore( { "org.jacoco.agent.rt.*", "com.vladium.emma.rt.*" } ) -public class ForkedBooterMockTest -{ +@RunWith(PowerMockRunner.class) +@PrepareForTest({PpidChecker.class, ForkedBooter.class, EventChannelEncoder.class, ShutdownHookUtils.class}) +@PowerMockIgnore({"org.jacoco.agent.rt.*", "com.vladium.emma.rt.*"}) +public class ForkedBooterMockTest { @Rule public final ErrorCollector errorCollector = new ErrorCollector(); @@ -118,356 +112,286 @@ public class ForkedBooterMockTest private ArgumentCaptor capturedBooter; @Test - public void shouldCheckNewPingMechanism() throws Exception - { - boolean canUse = invokeMethod( ForkedBooter.class, "canUseNewPingMechanism", (PpidChecker) null ); - assertThat( canUse ).isFalse(); - - when( pluginProcessChecker.canUse() ).thenReturn( false ); - canUse = invokeMethod( ForkedBooter.class, "canUseNewPingMechanism", pluginProcessChecker ); - assertThat( canUse ).isFalse(); - - when( pluginProcessChecker.canUse() ).thenReturn( true ); - canUse = invokeMethod( ForkedBooter.class, "canUseNewPingMechanism", pluginProcessChecker ); - assertThat( canUse ).isTrue(); + public void shouldCheckNewPingMechanism() throws Exception { + boolean canUse = invokeMethod(ForkedBooter.class, "canUseNewPingMechanism", (PpidChecker) null); + assertThat(canUse).isFalse(); + + when(pluginProcessChecker.canUse()).thenReturn(false); + canUse = invokeMethod(ForkedBooter.class, "canUseNewPingMechanism", pluginProcessChecker); + assertThat(canUse).isFalse(); + + when(pluginProcessChecker.canUse()).thenReturn(true); + canUse = invokeMethod(ForkedBooter.class, "canUseNewPingMechanism", pluginProcessChecker); + assertThat(canUse).isTrue(); } @Test - public void testMain() throws Exception - { - mockStatic( ForkedBooter.class ); - - doCallRealMethod() - .when( ForkedBooter.class, "run", capturedBooter.capture(), capturedArgs.capture() ); - - String[] args = new String[]{ "/", "dump", "surefire.properties", "surefire-effective.properties" }; - invokeMethod( ForkedBooter.class, "run", booter, args ); - - assertThat( capturedBooter.getAllValues() ) - .hasSize( 1 ) - .contains( booter ); - - assertThat( capturedArgs.getAllValues() ) - .hasSize( 1 ); - assertThat( capturedArgs.getAllValues().get( 0 )[0] ) - .isEqualTo( "/" ); - assertThat( capturedArgs.getAllValues().get( 0 )[1] ) - .isEqualTo( "dump" ); - assertThat( capturedArgs.getAllValues().get( 0 )[2] ) - .isEqualTo( "surefire.properties" ); - assertThat( capturedArgs.getAllValues().get( 0 )[3] ) - .isEqualTo( "surefire-effective.properties" ); - - verifyPrivate( booter, times( 1 ) ) - .invoke( "setupBooter", same( args[0] ), same( args[1] ), same( args[2] ), same( args[3] ) ); - - verifyPrivate( booter, times( 1 ) ) - .invoke( "execute" ); - - verifyNoMoreInteractions( booter ); + public void testMain() throws Exception { + mockStatic(ForkedBooter.class); + + doCallRealMethod().when(ForkedBooter.class, "run", capturedBooter.capture(), capturedArgs.capture()); + + String[] args = new String[] {"/", "dump", "surefire.properties", "surefire-effective.properties"}; + invokeMethod(ForkedBooter.class, "run", booter, args); + + assertThat(capturedBooter.getAllValues()).hasSize(1).contains(booter); + + assertThat(capturedArgs.getAllValues()).hasSize(1); + assertThat(capturedArgs.getAllValues().get(0)[0]).isEqualTo("/"); + assertThat(capturedArgs.getAllValues().get(0)[1]).isEqualTo("dump"); + assertThat(capturedArgs.getAllValues().get(0)[2]).isEqualTo("surefire.properties"); + assertThat(capturedArgs.getAllValues().get(0)[3]).isEqualTo("surefire-effective.properties"); + + verifyPrivate(booter, times(1)) + .invoke("setupBooter", same(args[0]), same(args[1]), same(args[2]), same(args[3])); + + verifyPrivate(booter, times(1)).invoke("execute"); + + verifyNoMoreInteractions(booter); } @Test - public void testMainWithError() throws Exception - { - mockStatic( ForkedBooter.class ); + public void testMainWithError() throws Exception { + mockStatic(ForkedBooter.class); - doCallRealMethod() - .when( ForkedBooter.class, "run", any( ForkedBooter.class ), any( String[].class ) ); + doCallRealMethod().when(ForkedBooter.class, "run", any(ForkedBooter.class), any(String[].class)); - doThrow( new RuntimeException( "dummy exception" ) ) - .when( booter, "execute" ); + doThrow(new RuntimeException("dummy exception")).when(booter, "execute"); doNothing() - .when( booter, "setupBooter", - any( String.class ), any( String.class ), any( String.class ), any( String.class ) ); + .when( + booter, + "setupBooter", + any(String.class), + any(String.class), + any(String.class), + any(String.class)); - setInternalState( booter, "logger", logger ); + setInternalState(booter, "logger", logger); - String[] args = new String[]{ "/", "dump", "surefire.properties", "surefire-effective.properties" }; - invokeMethod( ForkedBooter.class, "run", booter, args ); + String[] args = new String[] {"/", "dump", "surefire.properties", "surefire-effective.properties"}; + invokeMethod(ForkedBooter.class, "run", booter, args); - verifyPrivate( booter, times( 1 ) ) - .invoke( "setupBooter", same( args[0] ), same( args[1] ), same( args[2] ), same( args[3] ) ); + verifyPrivate(booter, times(1)) + .invoke("setupBooter", same(args[0]), same(args[1]), same(args[2]), same(args[3])); - verifyPrivate( booter, times( 1 ) ) - .invoke( "execute" ); + verifyPrivate(booter, times(1)).invoke("execute"); - verify( logger, times( 1 ) ) - .error( eq( "dummy exception" ), any( RuntimeException.class ) ); + verify(logger, times(1)).error(eq("dummy exception"), any(RuntimeException.class)); - verifyPrivate( booter, times( 1 ) ) - .invoke( "cancelPingScheduler" ); + verifyPrivate(booter, times(1)).invoke("cancelPingScheduler"); - verifyPrivate( booter, times( 1 ) ) - .invoke( "exit1" ); + verifyPrivate(booter, times(1)).invoke("exit1"); - verifyNoMoreInteractions( booter ); + verifyNoMoreInteractions(booter); } @Test - public void shouldNotCloseChannelProcessorFactory() throws Exception - { - setInternalState( booter, "channelProcessorFactory", (MasterProcessChannelProcessorFactory) null ); + public void shouldNotCloseChannelProcessorFactory() throws Exception { + setInternalState(booter, "channelProcessorFactory", (MasterProcessChannelProcessorFactory) null); - doCallRealMethod() - .when( booter, "closeForkChannel" ); + doCallRealMethod().when(booter, "closeForkChannel"); - invokeMethod( booter, "closeForkChannel" ); + invokeMethod(booter, "closeForkChannel"); - verifyZeroInteractions( channelProcessorFactory ); + verifyZeroInteractions(channelProcessorFactory); } @Test - public void shouldCloseChannelProcessorFactory() throws Exception - { - setInternalState( booter, "channelProcessorFactory", channelProcessorFactory ); + public void shouldCloseChannelProcessorFactory() throws Exception { + setInternalState(booter, "channelProcessorFactory", channelProcessorFactory); - doCallRealMethod() - .when( booter, "closeForkChannel" ); + doCallRealMethod().when(booter, "closeForkChannel"); - invokeMethod( booter, "closeForkChannel" ); + invokeMethod(booter, "closeForkChannel"); - verify( channelProcessorFactory, times( 1 ) ) - .close(); - verifyNoMoreInteractions( channelProcessorFactory ); + verify(channelProcessorFactory, times(1)).close(); + verifyNoMoreInteractions(channelProcessorFactory); } @Test - public void shouldFailOnCloseChannelProcessorFactory() throws Exception - { - setInternalState( booter, "channelProcessorFactory", channelProcessorFactory ); + public void shouldFailOnCloseChannelProcessorFactory() throws Exception { + setInternalState(booter, "channelProcessorFactory", channelProcessorFactory); - doThrow( new IOException() ) - .when( channelProcessorFactory ) - .close(); + doThrow(new IOException()).when(channelProcessorFactory).close(); - doCallRealMethod() - .when( booter, "closeForkChannel" ); + doCallRealMethod().when(booter, "closeForkChannel"); - invokeMethod( booter, "closeForkChannel" ); + invokeMethod(booter, "closeForkChannel"); - verify( channelProcessorFactory, times( 1 ) ) - .close(); - verifyNoMoreInteractions( channelProcessorFactory ); + verify(channelProcessorFactory, times(1)).close(); + verifyNoMoreInteractions(channelProcessorFactory); } @Test - public void shouldLookupLegacyDecoderFactory() throws Exception - { - mockStatic( ForkedBooter.class ); + public void shouldLookupLegacyDecoderFactory() throws Exception { + mockStatic(ForkedBooter.class); - doCallRealMethod() - .when( ForkedBooter.class, "lookupDecoderFactory", anyString() ); + doCallRealMethod().when(ForkedBooter.class, "lookupDecoderFactory", anyString()); - try ( final MasterProcessChannelProcessorFactory factory = - invokeMethod( ForkedBooter.class, "lookupDecoderFactory", "pipe://3" ) ) - { - assertThat( factory ).isInstanceOf( LegacyMasterProcessChannelProcessorFactory.class ); + try (MasterProcessChannelProcessorFactory factory = + invokeMethod(ForkedBooter.class, "lookupDecoderFactory", "pipe://3")) { + assertThat(factory).isInstanceOf(LegacyMasterProcessChannelProcessorFactory.class); - assertThat( factory.canUse( "pipe://3" ) ).isTrue(); + assertThat(factory.canUse("pipe://3")).isTrue(); - assertThat( factory.canUse( "-- whatever --" ) ).isFalse(); + assertThat(factory.canUse("-- whatever --")).isFalse(); - errorCollector.checkThrows( MalformedURLException.class, new ThrowingRunnable() - { + errorCollector.checkThrows(MalformedURLException.class, new ThrowingRunnable() { @Override - public void run() throws Throwable - { - factory.connect( "tcp://localhost:123" ); - fail( "should not connect to the port 123" ); + public void run() throws Throwable { + factory.connect("tcp://localhost:123"); + fail("should not connect to the port 123"); } - } ); + }); - factory.connect( "pipe://3" ); + factory.connect("pipe://3"); - ForkNodeArguments args = new ForkedNodeArg( 1, false ); - MasterProcessChannelDecoder decoder = factory.createDecoder( args ); - assertThat( decoder ).isInstanceOf( CommandChannelDecoder.class ); - MasterProcessChannelEncoder encoder = factory.createEncoder( args ); - assertThat( encoder ).isInstanceOf( EventChannelEncoder.class ); + ForkNodeArguments args = new ForkedNodeArg(1, false); + MasterProcessChannelDecoder decoder = factory.createDecoder(args); + assertThat(decoder).isInstanceOf(CommandChannelDecoder.class); + MasterProcessChannelEncoder encoder = factory.createEncoder(args); + assertThat(encoder).isInstanceOf(EventChannelEncoder.class); } } @Test - @SuppressWarnings( "checkstyle:magicnumber" ) - public void shouldScheduleFlushes() throws Exception - { + @SuppressWarnings("checkstyle:magicnumber") + public void shouldScheduleFlushes() throws Exception { final ByteArrayOutputStream out = new ByteArrayOutputStream(); - class Factory extends AbstractMasterProcessChannelProcessorFactory - { + class Factory extends AbstractMasterProcessChannelProcessorFactory { @Override - public boolean canUse( String channelConfig ) - { + public boolean canUse(String channelConfig) { return false; } @Override - public void connect( String channelConfig ) - { - } + public void connect(String channelConfig) {} @Override - public MasterProcessChannelDecoder createDecoder( @Nonnull ForkNodeArguments args ) - { + public MasterProcessChannelDecoder createDecoder(@Nonnull ForkNodeArguments args) { return null; } @Override - public MasterProcessChannelEncoder createEncoder( @Nonnull ForkNodeArguments args ) - { + public MasterProcessChannelEncoder createEncoder(@Nonnull ForkNodeArguments args) { return null; } - public void runScheduler() throws InterruptedException - { - final WritableBufferedByteChannel channel = newBufferedChannel( out ); - schedulePeriodicFlusher( 100, channel ); - Thread t = new Thread() - { + public void runScheduler() throws InterruptedException { + final WritableBufferedByteChannel channel = newBufferedChannel(out); + schedulePeriodicFlusher(100, channel); + Thread t = new Thread() { @Override - public void run() - { - for ( int i = 0; i < 10; i++ ) - { - try - { - channel.write( ByteBuffer.wrap( new byte[] {1} ) ); - Thread.sleep( 75 ); - } - catch ( Exception e ) - { + public void run() { + for (int i = 0; i < 10; i++) { + try { + channel.write(ByteBuffer.wrap(new byte[] {1})); + Thread.sleep(75); + } catch (Exception e) { // } } } }; - t.setDaemon( true ); + t.setDaemon(true); t.start(); - t.join( 5000L ); + t.join(5000L); } } Factory factory = new Factory(); factory.runScheduler(); factory.close(); - assertThat( out.size() ).isPositive(); - assertThat( out.size() ).isLessThanOrEqualTo( 10 ); + assertThat(out.size()).isPositive(); + assertThat(out.size()).isLessThanOrEqualTo(10); } @Test - public void shouldLookupSurefireDecoderFactory() throws Exception - { - mockStatic( ForkedBooter.class ); + public void shouldLookupSurefireDecoderFactory() throws Exception { + mockStatic(ForkedBooter.class); - doCallRealMethod() - .when( ForkedBooter.class, "lookupDecoderFactory", anyString() ); + doCallRealMethod().when(ForkedBooter.class, "lookupDecoderFactory", anyString()); - try ( ServerSocketChannel server = ServerSocketChannel.open() ) - { - server.bind( new InetSocketAddress( 0 ) ); - int serverPort = ( (InetSocketAddress) server.getLocalAddress() ).getPort(); + try (ServerSocketChannel server = ServerSocketChannel.open()) { + server.bind(new InetSocketAddress(0)); + int serverPort = ((InetSocketAddress) server.getLocalAddress()).getPort(); - try ( MasterProcessChannelProcessorFactory factory = - invokeMethod( ForkedBooter.class, "lookupDecoderFactory", "tcp://localhost:" + serverPort ) ) - { - assertThat( factory ) - .isInstanceOf( SurefireMasterProcessChannelProcessorFactory.class ); + try (MasterProcessChannelProcessorFactory factory = + invokeMethod(ForkedBooter.class, "lookupDecoderFactory", "tcp://localhost:" + serverPort)) { + assertThat(factory).isInstanceOf(SurefireMasterProcessChannelProcessorFactory.class); - assertThat( factory.canUse( "tcp://localhost:" + serverPort ) ) - .isTrue(); + assertThat(factory.canUse("tcp://localhost:" + serverPort)).isTrue(); - assertThat( factory.canUse( "-- whatever --" ) ) - .isFalse(); + assertThat(factory.canUse("-- whatever --")).isFalse(); - errorCollector.checkThrows( MalformedURLException.class, new ThrowingRunnable() - { + errorCollector.checkThrows(MalformedURLException.class, new ThrowingRunnable() { @Override - public void run() throws Throwable - { - factory.connect( "pipe://1" ); - fail( "should not connect" ); + public void run() throws Throwable { + factory.connect("pipe://1"); + fail("should not connect"); } - } ); + }); - errorCollector.checkThrows( IOException.class, new ThrowingRunnable() - { + errorCollector.checkThrows(IOException.class, new ThrowingRunnable() { @Override - public void run() throws Throwable - { - factory.connect( "tcp://localhost:123\u0000\u0000\u0000" ); - fail( "should not connect to incorrect uri" ); + public void run() throws Throwable { + factory.connect("tcp://localhost:123\u0000\u0000\u0000"); + fail("should not connect to incorrect uri"); } - } ); - - factory.connect( "tcp://localhost:" + serverPort ); - ForkNodeArguments args = new ForkedNodeArg( 1, false ); - MasterProcessChannelDecoder decoder = factory.createDecoder( args ); - assertThat( decoder ) - .isInstanceOf( CommandChannelDecoder.class ); - MasterProcessChannelEncoder encoder = factory.createEncoder( args ); - assertThat( encoder ) - .isInstanceOf( EventChannelEncoder.class ); + }); + + factory.connect("tcp://localhost:" + serverPort); + ForkNodeArguments args = new ForkedNodeArg(1, false); + MasterProcessChannelDecoder decoder = factory.createDecoder(args); + assertThat(decoder).isInstanceOf(CommandChannelDecoder.class); + MasterProcessChannelEncoder encoder = factory.createEncoder(args); + assertThat(encoder).isInstanceOf(EventChannelEncoder.class); } } } @Test - public void shouldAuthenticate() throws Exception - { - mockStatic( ForkedBooter.class ); + public void shouldAuthenticate() throws Exception { + mockStatic(ForkedBooter.class); - doCallRealMethod() - .when( ForkedBooter.class, "lookupDecoderFactory", anyString() ); + doCallRealMethod().when(ForkedBooter.class, "lookupDecoderFactory", anyString()); - try ( final ServerSocketChannel server = ServerSocketChannel.open() ) - { - server.bind( new InetSocketAddress( 0 ) ); - int serverPort = ( (InetSocketAddress) server.getLocalAddress() ).getPort(); + try (ServerSocketChannel server = ServerSocketChannel.open()) { + server.bind(new InetSocketAddress(0)); + int serverPort = ((InetSocketAddress) server.getLocalAddress()).getPort(); final String uuid = UUID.randomUUID().toString(); String url = "tcp://localhost:" + serverPort + "?sessionId=" + uuid; - try ( final MasterProcessChannelProcessorFactory factory = - invokeMethod( ForkedBooter.class, "lookupDecoderFactory", url ) ) - { - assertThat( factory ) - .isInstanceOf( SurefireMasterProcessChannelProcessorFactory.class ); - - FutureTask task = new FutureTask<>( new Callable() - { + try (MasterProcessChannelProcessorFactory factory = + invokeMethod(ForkedBooter.class, "lookupDecoderFactory", url)) { + assertThat(factory).isInstanceOf(SurefireMasterProcessChannelProcessorFactory.class); + + FutureTask task = new FutureTask<>(new Callable() { @Override - public Boolean call() - { - try - { + public Boolean call() { + try { SocketChannel channel = server.accept(); - ByteBuffer bb = ByteBuffer.allocate( uuid.length() ); - int read = channel.read( bb ); - assertThat( read ) - .isEqualTo( uuid.length() ); - ( (Buffer) bb ).flip(); - assertThat( new String( bb.array(), US_ASCII ) ) - .isEqualTo( uuid ); + ByteBuffer bb = ByteBuffer.allocate(uuid.length()); + int read = channel.read(bb); + assertThat(read).isEqualTo(uuid.length()); + ((Buffer) bb).flip(); + assertThat(new String(bb.array(), US_ASCII)).isEqualTo(uuid); return true; - } - catch ( IOException e ) - { + } catch (IOException e) { return false; } } - } ); + }); - Thread t = new Thread( task ); - t.setDaemon( true ); + Thread t = new Thread(task); + t.setDaemon(true); t.start(); - factory.connect( url ); + factory.connect(url); - try - { - task.get( 10, SECONDS ); - } - finally - { + try { + task.get(10, SECONDS); + } finally { factory.close(); } } @@ -475,46 +399,40 @@ public Boolean call() } @Test - public void testFlushEventChannelOnExit() throws Exception - { - mockStatic( ShutdownHookUtils.class ); + public void testFlushEventChannelOnExit() throws Exception { + mockStatic(ShutdownHookUtils.class); - final MasterProcessChannelEncoder eventChannel = mock( MasterProcessChannelEncoder.class ); + final MasterProcessChannelEncoder eventChannel = mock(MasterProcessChannelEncoder.class); ForkedBooter booter = new ForkedBooter(); - setInternalState( booter, "eventChannel", eventChannel ); + setInternalState(booter, "eventChannel", eventChannel); - doAnswer( new Answer() - { - @Override - public Object answer( InvocationOnMock invocation ) - { - Thread t = invocation.getArgument( 0 ); - assertThat( t.isDaemon() ).isTrue(); - t.run(); - verify( eventChannel, times( 1 ) ).onJvmExit(); - return null; - } - } ).when( ShutdownHookUtils.class, "addShutDownHook", any( Thread.class ) ); - invokeMethod( booter, "flushEventChannelOnExit" ); + doAnswer(new Answer() { + @Override + public Object answer(InvocationOnMock invocation) { + Thread t = invocation.getArgument(0); + assertThat(t.isDaemon()).isTrue(); + t.run(); + verify(eventChannel, times(1)).onJvmExit(); + return null; + } + }) + .when(ShutdownHookUtils.class, "addShutDownHook", any(Thread.class)); + invokeMethod(booter, "flushEventChannelOnExit"); } @Test - public void shouldParseUUID() throws Exception - { + public void shouldParseUUID() throws Exception { UUID uuid = UUID.randomUUID(); - URI uri = new URI( "tcp://localhost:12345?sessionId=" + uuid ); - String parsed = invokeMethod( SurefireMasterProcessChannelProcessorFactory.class, "extractSessionId", uri ); - assertThat( parsed ) - .isEqualTo( uuid.toString() ); + URI uri = new URI("tcp://localhost:12345?sessionId=" + uuid); + String parsed = invokeMethod(SurefireMasterProcessChannelProcessorFactory.class, "extractSessionId", uri); + assertThat(parsed).isEqualTo(uuid.toString()); } @Test - public void shouldNotParseUUID() throws Exception - { + public void shouldNotParseUUID() throws Exception { UUID uuid = UUID.randomUUID(); - URI uri = new URI( "tcp://localhost:12345?xxx=" + uuid ); - String parsed = invokeMethod( SurefireMasterProcessChannelProcessorFactory.class, "extractSessionId", uri ); - assertThat( parsed ) - .isNull(); + URI uri = new URI("tcp://localhost:12345?xxx=" + uuid); + String parsed = invokeMethod(SurefireMasterProcessChannelProcessorFactory.class, "extractSessionId", uri); + assertThat(parsed).isNull(); } } diff --git a/surefire-booter/src/test/java/org/apache/maven/surefire/booter/ForkedBooterTest.java b/surefire-booter/src/test/java/org/apache/maven/surefire/booter/ForkedBooterTest.java index a710824158..515bee6b5a 100644 --- a/surefire-booter/src/test/java/org/apache/maven/surefire/booter/ForkedBooterTest.java +++ b/surefire-booter/src/test/java/org/apache/maven/surefire/booter/ForkedBooterTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.booter; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,10 +16,7 @@ * specific language governing permissions and limitations * under the License. */ - -import org.apache.maven.surefire.api.util.SureFireFileManager; -import org.apache.maven.surefire.shared.io.FileUtils; -import org.junit.Test; +package org.apache.maven.surefire.booter; import java.io.File; import java.io.FileInputStream; @@ -36,6 +31,10 @@ import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.Semaphore; +import org.apache.maven.surefire.api.util.SureFireFileManager; +import org.apache.maven.surefire.shared.io.FileUtils; +import org.junit.Test; + import static java.nio.charset.StandardCharsets.UTF_8; import static org.assertj.core.api.Assertions.assertThat; import static org.powermock.reflect.Whitebox.invokeMethod; @@ -43,190 +42,154 @@ /** * Tests for {@link ForkedBooter}. */ -@SuppressWarnings( "checkstyle:magicnumber" ) -public class ForkedBooterTest -{ +@SuppressWarnings("checkstyle:magicnumber") +public class ForkedBooterTest { @Test - public void shouldGenerateThreadDump() throws Exception - { + public void shouldGenerateThreadDump() throws Exception { Collection threadNames = new ArrayList<>(); ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean(); - for ( ThreadInfo threadInfo : threadMXBean.getThreadInfo( threadMXBean.getAllThreadIds(), 100 ) ) - { - threadNames.add( threadInfo.getThreadName() ); + for (ThreadInfo threadInfo : threadMXBean.getThreadInfo(threadMXBean.getAllThreadIds(), 100)) { + threadNames.add(threadInfo.getThreadName()); } - String dump = invokeMethod( ForkedBooter.class, "generateThreadDump" ); + String dump = invokeMethod(ForkedBooter.class, "generateThreadDump"); - for ( String threadName : threadNames ) - { - assertThat( dump ) - .contains( "\"" + threadName + "\"" ); + for (String threadName : threadNames) { + assertThat(dump).contains("\"" + threadName + "\""); } - assertThat( dump ) - .contains( " java.lang.Thread.State: " ) - .contains( " at " ); + assertThat(dump).contains(" java.lang.Thread.State: ").contains(" at "); } @Test - public void shouldFindCurrentProcessName() throws Exception - { + public void shouldFindCurrentProcessName() throws Exception { String process = ManagementFactory.getRuntimeMXBean().getName(); - String expected = invokeMethod( ForkedBooter.class, "getProcessName" ); - assertThat( process ).isEqualTo( expected ); + String expected = invokeMethod(ForkedBooter.class, "getProcessName"); + assertThat(process).isEqualTo(expected); } @Test - public void shouldNotBeDebugMode() throws Exception - { - boolean expected = invokeMethod( ForkedBooter.class, "isDebugging" ); - assertThat( expected ).isFalse(); + public void shouldNotBeDebugMode() throws Exception { + boolean expected = invokeMethod(ForkedBooter.class, "isDebugging"); + assertThat(expected).isFalse(); } @Test - public void shouldReadSurefireProperties() throws Exception - { - File target = new File( System.getProperty( "user.dir", "target" ) ); - File tmpDir = new File( target, "ForkedBooterTest.1" ); - assertThat( tmpDir.mkdirs() ) - .isTrue(); - - try - { - try ( InputStream is = invokeMethod( ForkedBooter.class, "createSurefirePropertiesIfFileExists", - tmpDir.getCanonicalPath(), "surefire.properties" ) ) - { - assertThat( is ) - .isNull(); + public void shouldReadSurefireProperties() throws Exception { + File target = new File(System.getProperty("user.dir", "target")); + File tmpDir = new File(target, "ForkedBooterTest.1"); + assertThat(tmpDir.mkdirs()).isTrue(); + + try { + try (InputStream is = invokeMethod( + ForkedBooter.class, + "createSurefirePropertiesIfFileExists", + tmpDir.getCanonicalPath(), + "surefire.properties")) { + assertThat(is).isNull(); } - File props = new File( tmpDir, "surefire.properties" ); + File props = new File(tmpDir, "surefire.properties"); - assertThat( props.createNewFile() ) - .isTrue(); + assertThat(props.createNewFile()).isTrue(); - FileUtils.write( props, "key=value", UTF_8 ); + FileUtils.write(props, "key=value", UTF_8); - try ( InputStream is2 = invokeMethod( ForkedBooter.class, "createSurefirePropertiesIfFileExists", - tmpDir.getCanonicalPath(), "surefire.properties" ) ) - { - assertThat( is2 ) - .isNotNull() - .isInstanceOf( FileInputStream.class ); + try (InputStream is2 = invokeMethod( + ForkedBooter.class, + "createSurefirePropertiesIfFileExists", + tmpDir.getCanonicalPath(), + "surefire.properties")) { + assertThat(is2).isNotNull().isInstanceOf(FileInputStream.class); byte[] propsContent = new byte[20]; - int length = is2.read( propsContent ); + int length = is2.read(propsContent); - assertThat( new String( propsContent, 0, length ) ) - .isEqualTo( "key=value" ); + assertThat(new String(propsContent, 0, length)).isEqualTo("key=value"); } - } - finally - { - FileUtils.deleteDirectory( tmpDir ); + } finally { + FileUtils.deleteDirectory(tmpDir); } } @Test - public void shouldCreateScheduler() throws Exception - { + public void shouldCreateScheduler() throws Exception { ScheduledExecutorService scheduler = null; - try - { - scheduler = invokeMethod( ForkedBooter.class, "createScheduler", "thread name" ); - assertThat( scheduler ) - .isNotNull(); - } - finally - { - if ( scheduler != null ) - { + try { + scheduler = invokeMethod(ForkedBooter.class, "createScheduler", "thread name"); + assertThat(scheduler).isNotNull(); + } finally { + if (scheduler != null) { scheduler.shutdownNow(); } } } - @Test( timeout = 10_000 ) - public void testBarrier1() throws Exception - { - Semaphore semaphore = new Semaphore( 2 ); - boolean acquiredOnePermit = invokeMethod( ForkedBooter.class, "acquireOnePermit", semaphore ); + @Test(timeout = 10_000) + public void testBarrier1() throws Exception { + Semaphore semaphore = new Semaphore(2); + boolean acquiredOnePermit = invokeMethod(ForkedBooter.class, "acquireOnePermit", semaphore); - assertThat( acquiredOnePermit ).isTrue(); - assertThat( semaphore.availablePermits() ).isEqualTo( 1 ); + assertThat(acquiredOnePermit).isTrue(); + assertThat(semaphore.availablePermits()).isEqualTo(1); } @Test - public void testBarrier2() throws Exception - { - Semaphore semaphore = new Semaphore( 0 ); + public void testBarrier2() throws Exception { + Semaphore semaphore = new Semaphore(0); Thread.currentThread().interrupt(); - try - { - boolean acquiredOnePermit = invokeMethod( ForkedBooter.class, "acquireOnePermit", semaphore ); + try { + boolean acquiredOnePermit = invokeMethod(ForkedBooter.class, "acquireOnePermit", semaphore); - assertThat( acquiredOnePermit ).isFalse(); - assertThat( semaphore.availablePermits() ).isEqualTo( 0 ); - } - finally - { - assertThat( Thread.interrupted() ).isFalse(); + assertThat(acquiredOnePermit).isFalse(); + assertThat(semaphore.availablePermits()).isEqualTo(0); + } finally { + assertThat(Thread.interrupted()).isFalse(); } } @Test - public void testScheduler() throws Exception - { - ScheduledThreadPoolExecutor executor = invokeMethod( ForkedBooter.class, "createScheduler", "thread name" ); + public void testScheduler() throws Exception { + ScheduledThreadPoolExecutor executor = invokeMethod(ForkedBooter.class, "createScheduler", "thread name"); executor.shutdown(); - assertThat( executor.getCorePoolSize() ).isEqualTo( 1 ); - assertThat( executor.getMaximumPoolSize() ).isEqualTo( 1 ); + assertThat(executor.getCorePoolSize()).isEqualTo(1); + assertThat(executor.getMaximumPoolSize()).isEqualTo(1); } @Test - public void testIsDebug() throws Exception - { - boolean isDebug = invokeMethod( ForkedBooter.class, "isDebugging" ); - assertThat( isDebug ).isFalse(); + public void testIsDebug() throws Exception { + boolean isDebug = invokeMethod(ForkedBooter.class, "isDebugging"); + assertThat(isDebug).isFalse(); } @Test - public void testPropsNotExist() throws Exception - { - String target = System.getProperty( "user.dir" ); + public void testPropsNotExist() throws Exception { + String target = System.getProperty("user.dir"); String file = "not exists"; - InputStream is = invokeMethod( ForkedBooter.class, "createSurefirePropertiesIfFileExists", target, file ); - assertThat( is ).isNull(); + InputStream is = invokeMethod(ForkedBooter.class, "createSurefirePropertiesIfFileExists", target, file); + assertThat(is).isNull(); } @Test - public void testPropsExist() throws Exception - { - File props = SureFireFileManager.createTempFile( "surefire", ".properties" ); + public void testPropsExist() throws Exception { + File props = SureFireFileManager.createTempFile("surefire", ".properties"); String target = props.getParent(); String file = props.getName(); - FileUtils.write( props, "Hi", StandardCharsets.US_ASCII ); - try ( InputStream is = - invokeMethod( ForkedBooter.class, "createSurefirePropertiesIfFileExists", target, file ) ) - { - assertThat( is ).isNotNull(); + FileUtils.write(props, "Hi", StandardCharsets.US_ASCII); + try (InputStream is = invokeMethod(ForkedBooter.class, "createSurefirePropertiesIfFileExists", target, file)) { + assertThat(is).isNotNull(); byte[] data = new byte[5]; - int bytes = is.read( data ); - assertThat( bytes ).isEqualTo( 2 ); - assertThat( data[0] ).isEqualTo( (byte) 'H' ); - assertThat( data[1] ).isEqualTo( (byte) 'i' ); + int bytes = is.read(data); + assertThat(bytes).isEqualTo(2); + assertThat(data[0]).isEqualTo((byte) 'H'); + assertThat(data[1]).isEqualTo((byte) 'i'); } } @Test - public void testThreadDump() throws Exception - { - String threads = invokeMethod( ForkedBooter.class, "generateThreadDump" ); - assertThat( threads ) - .isNotNull(); - assertThat( threads ) - .contains( "\"main\"" ) - .contains( "java.lang.Thread.State: RUNNABLE" ); + public void testThreadDump() throws Exception { + String threads = invokeMethod(ForkedBooter.class, "generateThreadDump"); + assertThat(threads).isNotNull(); + assertThat(threads).contains("\"main\"").contains("java.lang.Thread.State: RUNNABLE"); } } diff --git a/surefire-booter/src/test/java/org/apache/maven/surefire/booter/IsolatedClassLoaderTest.java b/surefire-booter/src/test/java/org/apache/maven/surefire/booter/IsolatedClassLoaderTest.java index 8013466336..ccc1c1f661 100644 --- a/surefire-booter/src/test/java/org/apache/maven/surefire/booter/IsolatedClassLoaderTest.java +++ b/surefire-booter/src/test/java/org/apache/maven/surefire/booter/IsolatedClassLoaderTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.booter; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,15 +16,16 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.booter; + +import java.io.File; +import java.net.URL; import org.apache.maven.surefire.api.provider.AbstractProvider; import org.apache.maven.surefire.shared.utils.io.FileUtils; import org.junit.Before; import org.junit.Test; -import java.io.File; -import java.net.URL; - import static java.io.File.pathSeparator; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.not; @@ -36,31 +35,27 @@ /** * Tests isolated CL. */ -public class IsolatedClassLoaderTest -{ +public class IsolatedClassLoaderTest { private IsolatedClassLoader classLoader; @Before - public void prepareClassLoader() throws Exception - { - classLoader = new IsolatedClassLoader( null, false, "role" ); + public void prepareClassLoader() throws Exception { + classLoader = new IsolatedClassLoader(null, false, "role"); - String[] files = FileUtils.fileRead( new File( "target/test-classpath/cp.txt" ), "UTF-8" ) - .split( pathSeparator ); + String[] files = FileUtils.fileRead(new File("target/test-classpath/cp.txt"), "UTF-8") + .split(pathSeparator); - for ( String file : files ) - { - URL fileUrl = new File( file ).toURI().toURL(); - classLoader.addURL( fileUrl ); + for (String file : files) { + URL fileUrl = new File(file).toURI().toURL(); + classLoader.addURL(fileUrl); } } @Test - public void shouldLoadIsolatedClass() throws Exception - { - Class isolatedClass = classLoader.loadClass( AbstractProvider.class.getName() ); - assertThat( isolatedClass, is( notNullValue() ) ); - assertThat( isolatedClass.getName(), is( AbstractProvider.class.getName() ) ); - assertThat( isolatedClass, is( not( (Class) AbstractProvider.class ) ) ); + public void shouldLoadIsolatedClass() throws Exception { + Class isolatedClass = classLoader.loadClass(AbstractProvider.class.getName()); + assertThat(isolatedClass, is(notNullValue())); + assertThat(isolatedClass.getName(), is(AbstractProvider.class.getName())); + assertThat(isolatedClass, is(not((Class) AbstractProvider.class))); } } diff --git a/surefire-booter/src/test/java/org/apache/maven/surefire/booter/JUnit4SuiteTest.java b/surefire-booter/src/test/java/org/apache/maven/surefire/booter/JUnit4SuiteTest.java index 6c14e0e07a..4881bb3692 100644 --- a/surefire-booter/src/test/java/org/apache/maven/surefire/booter/JUnit4SuiteTest.java +++ b/surefire-booter/src/test/java/org/apache/maven/surefire/booter/JUnit4SuiteTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.booter; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.booter; import junit.framework.JUnit4TestAdapter; import junit.framework.Test; @@ -32,23 +31,21 @@ * @author Tibor Digana (tibor17) * @since 2.19 */ -public class JUnit4SuiteTest extends TestCase -{ - public static Test suite() - { +public class JUnit4SuiteTest extends TestCase { + public static Test suite() { TestSuite suite = new TestSuite(); - suite.addTest( new JUnit4TestAdapter( CommandReaderTest.class ) ); - suite.addTest( new JUnit4TestAdapter( PpidCheckerTest.class ) ); - suite.addTest( new JUnit4TestAdapter( SystemUtilsTest.class ) ); - suite.addTest( new JUnit4TestAdapter( IsolatedClassLoaderTest.class ) ); - suite.addTest( new JUnit4TestAdapter( ForkedBooterTest.class ) ); - suite.addTest( new JUnit4TestAdapter( ForkedBooterMockTest.class ) ); - suite.addTest( new JUnit4TestAdapter( BooterDeserializerTest.class ) ); - suite.addTestSuite( ClasspathTest.class ); - suite.addTestSuite( PropertiesWrapperTest.class ); - suite.addTest( new JUnit4TestAdapter( CommandChannelDecoderTest.class ) ); - suite.addTest( new JUnit4TestAdapter( EventChannelEncoderTest.class ) ); - suite.addTestSuite( SurefireReflectorTest.class ); + suite.addTest(new JUnit4TestAdapter(CommandReaderTest.class)); + suite.addTest(new JUnit4TestAdapter(PpidCheckerTest.class)); + suite.addTest(new JUnit4TestAdapter(SystemUtilsTest.class)); + suite.addTest(new JUnit4TestAdapter(IsolatedClassLoaderTest.class)); + suite.addTest(new JUnit4TestAdapter(ForkedBooterTest.class)); + suite.addTest(new JUnit4TestAdapter(ForkedBooterMockTest.class)); + suite.addTest(new JUnit4TestAdapter(BooterDeserializerTest.class)); + suite.addTestSuite(ClasspathTest.class); + suite.addTestSuite(PropertiesWrapperTest.class); + suite.addTest(new JUnit4TestAdapter(CommandChannelDecoderTest.class)); + suite.addTest(new JUnit4TestAdapter(EventChannelEncoderTest.class)); + suite.addTestSuite(SurefireReflectorTest.class); return suite; } } diff --git a/surefire-booter/src/test/java/org/apache/maven/surefire/booter/NewClassLoaderRunner.java b/surefire-booter/src/test/java/org/apache/maven/surefire/booter/NewClassLoaderRunner.java index ecc997d97d..1bb96440c5 100644 --- a/surefire-booter/src/test/java/org/apache/maven/surefire/booter/NewClassLoaderRunner.java +++ b/surefire-booter/src/test/java/org/apache/maven/surefire/booter/NewClassLoaderRunner.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.booter; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,17 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.booter; + +import java.io.File; +import java.io.IOException; +import java.lang.annotation.Annotation; +import java.net.MalformedURLException; +import java.net.URL; +import java.net.URLClassLoader; +import java.util.Collection; +import java.util.HashSet; +import java.util.List; import org.apache.maven.surefire.shared.utils.io.FileUtils; import org.junit.After; @@ -35,16 +44,6 @@ import org.junit.runners.model.Statement; import org.junit.runners.model.TestClass; -import java.io.File; -import java.io.IOException; -import java.lang.annotation.Annotation; -import java.net.MalformedURLException; -import java.net.URL; -import java.net.URLClassLoader; -import java.util.Collection; -import java.util.HashSet; -import java.util.List; - import static java.io.File.pathSeparator; /** @@ -53,150 +52,109 @@ * @author Tibor Digana (tibor17) * @since 2.19 */ -public class NewClassLoaderRunner - extends BlockJUnit4ClassRunner -{ - private static final String PROJECT_DIR = System.getProperty( "java.dir" ); +public class NewClassLoaderRunner extends BlockJUnit4ClassRunner { + private static final String PROJECT_DIR = System.getProperty("java.dir"); private Class cls; - public NewClassLoaderRunner( Class clazz ) - throws InitializationError - { - super( clazz ); + public NewClassLoaderRunner(Class clazz) throws InitializationError { + super(clazz); } @Override - protected void runChild( FrameworkMethod method, RunNotifier notifier ) - { + protected void runChild(FrameworkMethod method, RunNotifier notifier) { ClassLoader backup = Thread.currentThread().getContextClassLoader(); - try - { + try { TestClassLoader loader = new TestClassLoader(); - Thread.currentThread().setContextClassLoader( loader ); - cls = getFromTestClassLoader( getTestClass().getName(), loader ); - method = new FrameworkMethod( cls.getMethod( method.getName() ) ); - super.runChild( method, notifier ); - } - catch ( NoSuchMethodException e ) - { - throw new IllegalStateException( e ); - } - finally - { - Thread.currentThread().setContextClassLoader( backup ); + Thread.currentThread().setContextClassLoader(loader); + cls = getFromTestClassLoader(getTestClass().getName(), loader); + method = new FrameworkMethod(cls.getMethod(method.getName())); + super.runChild(method, notifier); + } catch (NoSuchMethodException e) { + throw new IllegalStateException(e); + } finally { + Thread.currentThread().setContextClassLoader(backup); } } @Override - protected Statement methodBlock( FrameworkMethod method ) - { - try - { - Object test = new ReflectiveCallable() - { + protected Statement methodBlock(FrameworkMethod method) { + try { + Object test = new ReflectiveCallable() { @Override - protected Object runReflectiveCall() - throws Throwable - { + protected Object runReflectiveCall() throws Throwable { return createTest(); } }.run(); - Statement statement = methodInvoker( method, test ); - statement = possiblyExpectingExceptions( method, test, statement ); - statement = withBefores( method, test, statement ); - statement = withAfters( method, test, statement ); + Statement statement = methodInvoker(method, test); + statement = possiblyExpectingExceptions(method, test, statement); + statement = withBefores(method, test, statement); + statement = withAfters(method, test, statement); return statement; - } - catch ( Throwable e ) - { - return new Fail( e ); + } catch (Throwable e) { + return new Fail(e); } } @Override - @SuppressWarnings( "unchecked" ) - protected Statement possiblyExpectingExceptions( FrameworkMethod method, Object test, Statement next ) - { - try - { - Class t = - (Class) Thread.currentThread().getContextClassLoader().loadClass( - Test.class.getName() ); - Annotation annotation = method.getAnnotation( t ); + @SuppressWarnings("unchecked") + protected Statement possiblyExpectingExceptions(FrameworkMethod method, Object test, Statement next) { + try { + Class t = (Class) + Thread.currentThread().getContextClassLoader().loadClass(Test.class.getName()); + Annotation annotation = method.getAnnotation(t); Class exp = - (Class) t.getMethod( "expected" ).invoke( annotation ); - boolean isException = exp != null && !Test.None.class.getName().equals( exp.getName() ); - return isException ? new ExpectException( next, exp ) : next; - } - catch ( Exception e ) - { - throw new IllegalStateException( e ); + (Class) t.getMethod("expected").invoke(annotation); + boolean isException = exp != null && !Test.None.class.getName().equals(exp.getName()); + return isException ? new ExpectException(next, exp) : next; + } catch (Exception e) { + throw new IllegalStateException(e); } } @Override - @SuppressWarnings( "unchecked" ) - protected Statement withBefores( FrameworkMethod method, Object target, Statement statement ) - { - try - { - Class before = - (Class) Thread.currentThread().getContextClassLoader().loadClass( - Before.class.getName() ); - List befores = new TestClass( target.getClass() ).getAnnotatedMethods( before ); - return befores.isEmpty() ? statement : new RunBefores( statement, befores, target ); - } - catch ( ClassNotFoundException e ) - { - throw new IllegalStateException( e ); + @SuppressWarnings("unchecked") + protected Statement withBefores(FrameworkMethod method, Object target, Statement statement) { + try { + Class before = (Class) + Thread.currentThread().getContextClassLoader().loadClass(Before.class.getName()); + List befores = new TestClass(target.getClass()).getAnnotatedMethods(before); + return befores.isEmpty() ? statement : new RunBefores(statement, befores, target); + } catch (ClassNotFoundException e) { + throw new IllegalStateException(e); } } @Override - @SuppressWarnings( "unchecked" ) - protected Statement withAfters( FrameworkMethod method, Object target, Statement statement ) - { - try - { - Class after = - (Class) Thread.currentThread().getContextClassLoader().loadClass( - After.class.getName() ); - List afters = new TestClass( target.getClass() ).getAnnotatedMethods( after ); - return afters.isEmpty() ? statement : new RunAfters( statement, afters, target ); - } - catch ( ClassNotFoundException e ) - { - throw new IllegalStateException( e ); + @SuppressWarnings("unchecked") + protected Statement withAfters(FrameworkMethod method, Object target, Statement statement) { + try { + Class after = (Class) + Thread.currentThread().getContextClassLoader().loadClass(After.class.getName()); + List afters = new TestClass(target.getClass()).getAnnotatedMethods(after); + return afters.isEmpty() ? statement : new RunAfters(statement, afters, target); + } catch (ClassNotFoundException e) { + throw new IllegalStateException(e); } } @Override - protected Object createTest() - throws Exception - { + protected Object createTest() throws Exception { return cls == null ? super.createTest() : cls.getConstructor().newInstance(); } - private static Class getFromTestClassLoader( String clazz, TestClassLoader loader ) - { - try - { - return Class.forName( clazz, true, loader ); - } - catch ( ClassNotFoundException e ) - { - throw new IllegalStateException( e ); + private static Class getFromTestClassLoader(String clazz, TestClassLoader loader) { + try { + return Class.forName(clazz, true, loader); + } catch (ClassNotFoundException e) { + throw new IllegalStateException(e); } } - private static class TestClassLoader - extends URLClassLoader - { - TestClassLoader() - { - super( toClassPath(), null ); + private static class TestClassLoader extends URLClassLoader { + TestClassLoader() { + super(toClassPath(), null); } /** @@ -204,51 +162,40 @@ private static class TestClassLoader * * @return classpath */ - private static URL[] toClassPath() - { - try - { + private static URL[] toClassPath() { + try { Collection cp = toPathList(); // if Maven run - if ( cp.isEmpty() ) - { + if (cp.isEmpty()) { // if IDE - cp = toPathList( System.getProperty( "java.class.path" ) ); + cp = toPathList(System.getProperty("java.class.path")); } - return cp.toArray( new URL[cp.size()] ); - } - catch ( IOException e ) - { + return cp.toArray(new URL[cp.size()]); + } catch (IOException e) { e.printStackTrace(); return new URL[0]; } } - private static Collection toPathList( String path ) throws MalformedURLException - { + private static Collection toPathList(String path) throws MalformedURLException { Collection classPath = new HashSet<>(); - for ( String file : path.split( pathSeparator ) ) - { - classPath.add( new File( file ).toURI().toURL() ); + for (String file : path.split(pathSeparator)) { + classPath.add(new File(file).toURI().toURL()); } return classPath; } - private static Collection toPathList() - { + private static Collection toPathList() { Collection classPath = new HashSet<>(); - try - { - File classPathFile = new File( PROJECT_DIR, "target/test-classpath/cp.txt" ); - String[] files = FileUtils.fileRead( classPathFile, "UTF-8" ).split( pathSeparator ); - for ( String file : files ) - { - classPath.add( new File( file ).toURI().toURL() ); + try { + File classPathFile = new File(PROJECT_DIR, "target/test-classpath/cp.txt"); + String[] files = FileUtils.fileRead(classPathFile, "UTF-8").split(pathSeparator); + for (String file : files) { + classPath.add(new File(file).toURI().toURL()); } - classPath.add( new File( PROJECT_DIR, "target/classes" ).toURI().toURL() ); - classPath.add( new File( PROJECT_DIR, "target/test-classes" ).toURI().toURL() ); - } - catch ( IOException e ) - { + classPath.add(new File(PROJECT_DIR, "target/classes").toURI().toURL()); + classPath.add( + new File(PROJECT_DIR, "target/test-classes").toURI().toURL()); + } catch (IOException e) { e.printStackTrace(); // turn to java.class.path classPath.clear(); diff --git a/surefire-booter/src/test/java/org/apache/maven/surefire/booter/PpidCheckerTest.java b/surefire-booter/src/test/java/org/apache/maven/surefire/booter/PpidCheckerTest.java index 33dc7f92e2..c0473800b3 100644 --- a/surefire-booter/src/test/java/org/apache/maven/surefire/booter/PpidCheckerTest.java +++ b/surefire-booter/src/test/java/org/apache/maven/surefire/booter/PpidCheckerTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.booter; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,16 +16,10 @@ * specific language governing permissions and limitations * under the License. */ - -import org.apache.maven.surefire.api.booter.DumpErrorSingleton; -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.rules.TemporaryFolder; +package org.apache.maven.surefire.booter; import javax.annotation.Nonnull; + import java.io.File; import java.io.IOException; import java.io.InterruptedIOException; @@ -35,13 +27,21 @@ import java.util.Random; import java.util.regex.Matcher; +import org.apache.maven.surefire.api.booter.DumpErrorSingleton; +import org.junit.After; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.junit.rules.TemporaryFolder; + import static java.nio.charset.StandardCharsets.US_ASCII; import static java.nio.file.Files.readAllBytes; import static java.util.concurrent.TimeUnit.SECONDS; -import static org.apache.maven.surefire.shared.lang3.SystemUtils.IS_OS_UNIX; -import static org.apache.maven.surefire.shared.lang3.SystemUtils.IS_OS_WINDOWS; import static org.apache.maven.surefire.booter.ProcessInfo.unixProcessInfo; import static org.apache.maven.surefire.booter.ProcessInfo.windowsProcessInfo; +import static org.apache.maven.surefire.shared.lang3.SystemUtils.IS_OS_UNIX; +import static org.apache.maven.surefire.shared.lang3.SystemUtils.IS_OS_WINDOWS; import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.not; @@ -58,9 +58,8 @@ * @author Tibor Digana (tibor17) * @since 2.20.1 */ -@SuppressWarnings( "checkstyle:magicnumber" ) -public class PpidCheckerTest -{ +@SuppressWarnings("checkstyle:magicnumber") +public class PpidCheckerTest { private static final Random RND = new Random(); @Rule @@ -73,436 +72,361 @@ public class PpidCheckerTest private String dumpFileName; @Before - public void initTmpFile() - { + public void initTmpFile() { reportsDir = tempFolder.getRoot(); dumpFileName = "surefire-" + RND.nextLong(); } @After - public void deleteTmpFiles() - { + public void deleteTmpFiles() { tempFolder.delete(); } @Test - public void canExecuteUnixPs() - { - assumeTrue( IS_OS_UNIX ); - assertThat( PpidChecker.canExecuteUnixPs() ) - .as( "Surefire should be tested on real box OS, e.g. Ubuntu or FreeBSD." ) + public void canExecuteUnixPs() { + assumeTrue(IS_OS_UNIX); + assertThat(PpidChecker.canExecuteUnixPs()) + .as("Surefire should be tested on real box OS, e.g. Ubuntu or FreeBSD.") .isTrue(); } @Test - public void shouldHavePidAtBegin() - { - String expectedPid = ManagementFactory.getRuntimeMXBean().getName().split( "@" )[0].trim(); + public void shouldHavePidAtBegin() { + String expectedPid = + ManagementFactory.getRuntimeMXBean().getName().split("@")[0].trim(); - PpidChecker checker = new PpidChecker( expectedPid ); + PpidChecker checker = new PpidChecker(expectedPid); ProcessInfo processInfo = IS_OS_UNIX ? checker.unix() : checker.windows(); - assertThat( processInfo ) - .isNotNull(); + assertThat(processInfo).isNotNull(); - assertThat( checker.canUse() ) - .isTrue(); + assertThat(checker.canUse()).isTrue(); - assertThat( checker.isProcessAlive() ) - .isTrue(); + assertThat(checker.isProcessAlive()).isTrue(); - assertThat( processInfo.getPID() ) - .isEqualTo( expectedPid ); + assertThat(processInfo.getPID()).isEqualTo(expectedPid); - assertThat( processInfo.getTime() ) - .isGreaterThan( 0L ); + assertThat(processInfo.getTime()).isGreaterThan(0L); } @Test - public void shouldHavePid() throws Exception - { - String expectedPid = ManagementFactory.getRuntimeMXBean().getName().split( "@" )[0].trim(); - - PpidChecker checker = new PpidChecker( expectedPid ); - setInternalState( checker, "parentProcessInfo", + public void shouldHavePid() throws Exception { + String expectedPid = + ManagementFactory.getRuntimeMXBean().getName().split("@")[0].trim(); + + PpidChecker checker = new PpidChecker(expectedPid); + setInternalState( + checker, + "parentProcessInfo", IS_OS_UNIX - ? unixProcessInfo( expectedPid, 0L ) - : windowsProcessInfo( expectedPid, windowsProcessStartTime( checker ) ) ); + ? unixProcessInfo(expectedPid, 0L) + : windowsProcessInfo(expectedPid, windowsProcessStartTime(checker))); // the etime in Unix is measured in seconds. So let's wait 1s at least. - SECONDS.sleep( 1L ); + SECONDS.sleep(1L); ProcessInfo processInfo = IS_OS_UNIX ? checker.unix() : checker.windows(); - assertThat( processInfo ) - .isNotNull(); + assertThat(processInfo).isNotNull(); - assertThat( checker.canUse() ) - .isTrue(); + assertThat(checker.canUse()).isTrue(); - assertThat( checker.isProcessAlive() ) - .isTrue(); + assertThat(checker.isProcessAlive()).isTrue(); - assertThat( processInfo.getPID() ) - .isEqualTo( expectedPid ); + assertThat(processInfo.getPID()).isEqualTo(expectedPid); - assertThat( processInfo.getTime() ) - .isGreaterThan( 0L ); + assertThat(processInfo.getTime()).isGreaterThan(0L); - assertThat( checker.toString() ) - .contains( "ppid=" + expectedPid ) - .contains( "stopped=false" ) - .contains( "invalid=false" ) - .contains( "error=false" ); + assertThat(checker.toString()) + .contains("ppid=" + expectedPid) + .contains("stopped=false") + .contains("invalid=false") + .contains("error=false"); checker.destroyActiveCommands(); - assertThat( checker.canUse() ) - .isFalse(); - assertThat( (boolean) invokeMethod( checker, "isStopped" ) ) - .isTrue(); + assertThat(checker.canUse()).isFalse(); + assertThat((boolean) invokeMethod(checker, "isStopped")).isTrue(); } @Test - public void shouldBeStopped() - { - PpidChecker checker = new PpidChecker( "0" ); + public void shouldBeStopped() { + PpidChecker checker = new PpidChecker("0"); checker.stop(); - assertThat( checker.canUse() ) - .isFalse(); + assertThat(checker.canUse()).isFalse(); - exceptions.expect( IllegalStateException.class ); - exceptions.expectMessage( "irrelevant to call isProcessAlive()" ); + exceptions.expect(IllegalStateException.class); + exceptions.expectMessage("irrelevant to call isProcessAlive()"); checker.isProcessAlive(); - fail( "this test should throw exception" ); + fail("this test should throw exception"); } @Test - public void shouldBeStoppedCheckerWithError() throws Exception - { - String expectedPid = ManagementFactory.getRuntimeMXBean().getName().split( "@" )[0].trim(); - DumpErrorSingleton.getSingleton().init( reportsDir, dumpFileName ); + public void shouldBeStoppedCheckerWithError() throws Exception { + String expectedPid = + ManagementFactory.getRuntimeMXBean().getName().split("@")[0].trim(); + DumpErrorSingleton.getSingleton().init(reportsDir, dumpFileName); - PpidChecker checker = new PpidChecker( expectedPid ); + PpidChecker checker = new PpidChecker(expectedPid); checker.stop(); ProcessInfo processInfo = IS_OS_UNIX ? checker.unix() : checker.windows(); - assertThat( processInfo.isError() ).isTrue(); + assertThat(processInfo.isError()).isTrue(); - String error = new String( readAllBytes( new File( reportsDir, dumpFileName + ".dump" ).toPath() ) ); + String error = new String(readAllBytes(new File(reportsDir, dumpFileName + ".dump").toPath())); - assertThat( error ) - .contains( "<> <<0>>" ) - .contains( "<> <>" ); + assertThat(error).contains("<> <<0>>").contains("<> <>"); } @Test - public void shouldBeEmptyDump() throws Exception - { - String expectedPid = ManagementFactory.getRuntimeMXBean().getName().split( "@" )[0].trim(); - DumpErrorSingleton.getSingleton().init( reportsDir, dumpFileName ); + public void shouldBeEmptyDump() throws Exception { + String expectedPid = + ManagementFactory.getRuntimeMXBean().getName().split("@")[0].trim(); + DumpErrorSingleton.getSingleton().init(reportsDir, dumpFileName); - PpidChecker checker = new PpidChecker( expectedPid ); + PpidChecker checker = new PpidChecker(expectedPid); - try - { + try { Thread.currentThread().interrupt(); ProcessInfo processInfo = IS_OS_UNIX ? checker.unix() : checker.windows(); //noinspection ResultOfMethodCallIgnored Thread.interrupted(); - assertThat( processInfo.isError() ).isTrue(); + assertThat(processInfo.isError()).isTrue(); - File dumpFile = new File( reportsDir, dumpFileName + ".dump" ); - if ( dumpFile.exists() ) - { - String error = new String( readAllBytes( dumpFile.toPath() ) ); + File dumpFile = new File(reportsDir, dumpFileName + ".dump"); + if (dumpFile.exists()) { + String error = new String(readAllBytes(dumpFile.toPath())); - assertThat( error ) - .contains( "<>" ) - .contains( "<> <>" ); + assertThat(error).contains("<>").contains("<> <>"); } - } - finally - { + } finally { //noinspection ResultOfMethodCallIgnored Thread.interrupted(); } } @Test - public void shouldStartedProcessThrowInterruptedException() throws Exception - { - String expectedPid = ManagementFactory.getRuntimeMXBean().getName().split( "@" )[0].trim(); - DumpErrorSingleton.getSingleton().init( reportsDir, dumpFileName ); + public void shouldStartedProcessThrowInterruptedException() throws Exception { + String expectedPid = + ManagementFactory.getRuntimeMXBean().getName().split("@")[0].trim(); + DumpErrorSingleton.getSingleton().init(reportsDir, dumpFileName); - PpidChecker checker = new PpidChecker( expectedPid ); + PpidChecker checker = new PpidChecker(expectedPid); - PpidChecker.ProcessInfoConsumer consumer = checker.new ProcessInfoConsumer( US_ASCII.name() ) - { + PpidChecker.ProcessInfoConsumer consumer = checker.new ProcessInfoConsumer(US_ASCII.name()) { @Nonnull @Override - ProcessInfo consumeLine( String line, ProcessInfo previousProcessInfo ) - throws Exception - { + ProcessInfo consumeLine(String line, ProcessInfo previousProcessInfo) throws Exception { throw new InterruptedException(); } }; String[] cmd = - IS_OS_WINDOWS - ? new String[]{"CMD", "/A", "/X", "/C", "dir"} - : new String[]{"/bin/sh", "-c", "ls"}; + IS_OS_WINDOWS ? new String[] {"CMD", "/A", "/X", "/C", "dir"} : new String[] {"/bin/sh", "-c", "ls"}; - assertThat( consumer.execute( cmd ).isError() ).isTrue(); - assertThat( new File( reportsDir, dumpFileName + ".dump" ) ).doesNotExist(); + assertThat(consumer.execute(cmd).isError()).isTrue(); + assertThat(new File(reportsDir, dumpFileName + ".dump")).doesNotExist(); } @Test - public void shouldStartedProcessThrowInterruptedIOException() throws Exception - { - String expectedPid = ManagementFactory.getRuntimeMXBean().getName().split( "@" )[0].trim(); - DumpErrorSingleton.getSingleton().init( reportsDir, dumpFileName ); + public void shouldStartedProcessThrowInterruptedIOException() throws Exception { + String expectedPid = + ManagementFactory.getRuntimeMXBean().getName().split("@")[0].trim(); + DumpErrorSingleton.getSingleton().init(reportsDir, dumpFileName); - PpidChecker checker = new PpidChecker( expectedPid ); + PpidChecker checker = new PpidChecker(expectedPid); - PpidChecker.ProcessInfoConsumer consumer = checker.new ProcessInfoConsumer( US_ASCII.name() ) - { + PpidChecker.ProcessInfoConsumer consumer = checker.new ProcessInfoConsumer(US_ASCII.name()) { @Nonnull @Override - ProcessInfo consumeLine( String line, ProcessInfo previousProcessInfo ) - throws Exception - { + ProcessInfo consumeLine(String line, ProcessInfo previousProcessInfo) throws Exception { throw new InterruptedIOException(); } }; String[] cmd = - IS_OS_WINDOWS - ? new String[]{"CMD", "/A", "/X", "/C", "dir"} - : new String[]{"/bin/sh", "-c", "ls"}; + IS_OS_WINDOWS ? new String[] {"CMD", "/A", "/X", "/C", "dir"} : new String[] {"/bin/sh", "-c", "ls"}; - assertThat( consumer.execute( cmd ).isError() ).isTrue(); - assertThat( new File( reportsDir, dumpFileName + ".dump" ) ).doesNotExist(); + assertThat(consumer.execute(cmd).isError()).isTrue(); + assertThat(new File(reportsDir, dumpFileName + ".dump")).doesNotExist(); } @Test - public void shouldStartedProcessThrowIOException() throws Exception - { - String expectedPid = ManagementFactory.getRuntimeMXBean().getName().split( "@" )[0].trim(); - DumpErrorSingleton.getSingleton().init( reportsDir, dumpFileName ); + public void shouldStartedProcessThrowIOException() throws Exception { + String expectedPid = + ManagementFactory.getRuntimeMXBean().getName().split("@")[0].trim(); + DumpErrorSingleton.getSingleton().init(reportsDir, dumpFileName); - PpidChecker checker = new PpidChecker( expectedPid ); + PpidChecker checker = new PpidChecker(expectedPid); - PpidChecker.ProcessInfoConsumer consumer = checker.new ProcessInfoConsumer( US_ASCII.name() ) - { + PpidChecker.ProcessInfoConsumer consumer = checker.new ProcessInfoConsumer(US_ASCII.name()) { @Nonnull @Override - ProcessInfo consumeLine( String line, ProcessInfo previousProcessInfo ) - throws Exception - { - throw new IOException( "wrong command" ); + ProcessInfo consumeLine(String line, ProcessInfo previousProcessInfo) throws Exception { + throw new IOException("wrong command"); } }; String[] cmd = - IS_OS_WINDOWS - ? new String[]{"CMD", "/A", "/X", "/C", "dir"} - : new String[]{"/bin/sh", "-c", "ls"}; + IS_OS_WINDOWS ? new String[] {"CMD", "/A", "/X", "/C", "dir"} : new String[] {"/bin/sh", "-c", "ls"}; - assertThat( consumer.execute( cmd ).isError() ).isTrue(); + assertThat(consumer.execute(cmd).isError()).isTrue(); - File dumpFile = new File( reportsDir, dumpFileName + ".dump" ); + File dumpFile = new File(reportsDir, dumpFileName + ".dump"); - String error = new String( readAllBytes( dumpFile.toPath() ) ); + String error = new String(readAllBytes(dumpFile.toPath())); - assertThat( error ) - .contains( IOException.class.getName() ) - .contains( "wrong command" ); + assertThat(error).contains(IOException.class.getName()).contains("wrong command"); } @Test - public void shouldNotFindSuchPID() - { - PpidChecker checker = new PpidChecker( "1000000" ); - setInternalState( checker, "parentProcessInfo", ProcessInfo.ERR_PROCESS_INFO ); + public void shouldNotFindSuchPID() { + PpidChecker checker = new PpidChecker("1000000"); + setInternalState(checker, "parentProcessInfo", ProcessInfo.ERR_PROCESS_INFO); - assertThat( checker.canUse() ) - .isFalse(); + assertThat(checker.canUse()).isFalse(); - exceptions.expect( IllegalStateException.class ); - exceptions.expectMessage( "irrelevant to call isProcessAlive()" ); + exceptions.expect(IllegalStateException.class); + exceptions.expectMessage("irrelevant to call isProcessAlive()"); checker.isProcessAlive(); - fail( "this test should throw exception" ); + fail("this test should throw exception"); } @Test - public void shouldNotBeAlive() - { - PpidChecker checker = new PpidChecker( "1000000" ); + public void shouldNotBeAlive() { + PpidChecker checker = new PpidChecker("1000000"); - assertThat( checker.canUse() ) - .isTrue(); + assertThat(checker.canUse()).isTrue(); - assertThat( checker.isProcessAlive() ) - .isFalse(); + assertThat(checker.isProcessAlive()).isFalse(); } @Test - public void shouldParseEtime() - { - Matcher m = PpidChecker.UNIX_CMD_OUT_PATTERN.matcher( "38 1234567890" ); - assertThat( m.matches() ) - .isFalse(); - - m = PpidChecker.UNIX_CMD_OUT_PATTERN.matcher( "05:38 1234567890" ); - assertThat( m.matches() ) - .isTrue(); - assertThat( PpidChecker.fromDays( m ) ).isEqualTo( 0L ); - assertThat( PpidChecker.fromHours( m ) ).isEqualTo( 0L ); - assertThat( PpidChecker.fromMinutes( m ) ).isEqualTo( 300L ); - assertThat( PpidChecker.fromSeconds( m ) ).isEqualTo( 38L ); - assertThat( PpidChecker.fromPID( m ) ).isEqualTo( "1234567890" ); - - m = PpidChecker.UNIX_CMD_OUT_PATTERN.matcher( "00:05:38 1234567890" ); - assertThat( m.matches() ) - .isTrue(); - assertThat( PpidChecker.fromDays( m ) ).isEqualTo( 0L ); - assertThat( PpidChecker.fromHours( m ) ).isEqualTo( 0L ); - assertThat( PpidChecker.fromMinutes( m ) ).isEqualTo( 300L ); - assertThat( PpidChecker.fromSeconds( m ) ).isEqualTo( 38L ); - assertThat( PpidChecker.fromPID( m ) ).isEqualTo( "1234567890" ); - - m = PpidChecker.UNIX_CMD_OUT_PATTERN.matcher( "01:05:38 1234567890" ); - assertThat( m.matches() ) - .isTrue(); - assertThat( PpidChecker.fromDays( m ) ).isEqualTo( 0L ); - assertThat( PpidChecker.fromHours( m ) ).isEqualTo( 3600L ); - assertThat( PpidChecker.fromMinutes( m ) ).isEqualTo( 300L ); - assertThat( PpidChecker.fromSeconds( m ) ).isEqualTo( 38L ); - assertThat( PpidChecker.fromPID( m ) ).isEqualTo( "1234567890" ); - - m = PpidChecker.UNIX_CMD_OUT_PATTERN.matcher( "02-01:05:38 1234567890" ); - assertThat( m.matches() ) - .isTrue(); - assertThat( PpidChecker.fromDays( m ) ).isEqualTo( 2 * 24 * 3600L ); - assertThat( PpidChecker.fromHours( m ) ).isEqualTo( 3600L ); - assertThat( PpidChecker.fromMinutes( m ) ).isEqualTo( 300L ); - assertThat( PpidChecker.fromSeconds( m ) ).isEqualTo( 38L ); - assertThat( PpidChecker.fromPID( m ) ).isEqualTo( "1234567890" ); - - m = PpidChecker.UNIX_CMD_OUT_PATTERN.matcher( "02-1:5:3 1234567890" ); - assertThat( m.matches() ) - .isTrue(); - assertThat( PpidChecker.fromDays( m ) ).isEqualTo( 2 * 24 * 3600L ); - assertThat( PpidChecker.fromHours( m ) ).isEqualTo( 3600L ); - assertThat( PpidChecker.fromMinutes( m ) ).isEqualTo( 300L ); - assertThat( PpidChecker.fromSeconds( m ) ).isEqualTo( 3L ); - assertThat( PpidChecker.fromPID( m ) ).isEqualTo( "1234567890" ); + public void shouldParseEtime() { + Matcher m = PpidChecker.UNIX_CMD_OUT_PATTERN.matcher("38 1234567890"); + assertThat(m.matches()).isFalse(); + + m = PpidChecker.UNIX_CMD_OUT_PATTERN.matcher("05:38 1234567890"); + assertThat(m.matches()).isTrue(); + assertThat(PpidChecker.fromDays(m)).isEqualTo(0L); + assertThat(PpidChecker.fromHours(m)).isEqualTo(0L); + assertThat(PpidChecker.fromMinutes(m)).isEqualTo(300L); + assertThat(PpidChecker.fromSeconds(m)).isEqualTo(38L); + assertThat(PpidChecker.fromPID(m)).isEqualTo("1234567890"); + + m = PpidChecker.UNIX_CMD_OUT_PATTERN.matcher("00:05:38 1234567890"); + assertThat(m.matches()).isTrue(); + assertThat(PpidChecker.fromDays(m)).isEqualTo(0L); + assertThat(PpidChecker.fromHours(m)).isEqualTo(0L); + assertThat(PpidChecker.fromMinutes(m)).isEqualTo(300L); + assertThat(PpidChecker.fromSeconds(m)).isEqualTo(38L); + assertThat(PpidChecker.fromPID(m)).isEqualTo("1234567890"); + + m = PpidChecker.UNIX_CMD_OUT_PATTERN.matcher("01:05:38 1234567890"); + assertThat(m.matches()).isTrue(); + assertThat(PpidChecker.fromDays(m)).isEqualTo(0L); + assertThat(PpidChecker.fromHours(m)).isEqualTo(3600L); + assertThat(PpidChecker.fromMinutes(m)).isEqualTo(300L); + assertThat(PpidChecker.fromSeconds(m)).isEqualTo(38L); + assertThat(PpidChecker.fromPID(m)).isEqualTo("1234567890"); + + m = PpidChecker.UNIX_CMD_OUT_PATTERN.matcher("02-01:05:38 1234567890"); + assertThat(m.matches()).isTrue(); + assertThat(PpidChecker.fromDays(m)).isEqualTo(2 * 24 * 3600L); + assertThat(PpidChecker.fromHours(m)).isEqualTo(3600L); + assertThat(PpidChecker.fromMinutes(m)).isEqualTo(300L); + assertThat(PpidChecker.fromSeconds(m)).isEqualTo(38L); + assertThat(PpidChecker.fromPID(m)).isEqualTo("1234567890"); + + m = PpidChecker.UNIX_CMD_OUT_PATTERN.matcher("02-1:5:3 1234567890"); + assertThat(m.matches()).isTrue(); + assertThat(PpidChecker.fromDays(m)).isEqualTo(2 * 24 * 3600L); + assertThat(PpidChecker.fromHours(m)).isEqualTo(3600L); + assertThat(PpidChecker.fromMinutes(m)).isEqualTo(300L); + assertThat(PpidChecker.fromSeconds(m)).isEqualTo(3L); + assertThat(PpidChecker.fromPID(m)).isEqualTo("1234567890"); } @Test - public void shouldParseBusyboxHoursEtime() - { - Matcher m = PpidChecker.BUSYBOX_CMD_OUT_PATTERN.matcher( "38 1234567890" ); - assertThat( m.matches() ) - .isFalse(); - - m = PpidChecker.BUSYBOX_CMD_OUT_PATTERN.matcher( "05h38 1234567890" ); - assertThat( m.matches() ) - .isTrue(); - assertThat( PpidChecker.fromBusyboxHours( m ) ).isEqualTo( 3600 * 5L ); - assertThat( PpidChecker.fromBusyboxMinutes( m ) ).isEqualTo( 60 * 38L ); - assertThat( PpidChecker.fromBusyboxPID( m ) ).isEqualTo( "1234567890" ); + public void shouldParseBusyboxHoursEtime() { + Matcher m = PpidChecker.BUSYBOX_CMD_OUT_PATTERN.matcher("38 1234567890"); + assertThat(m.matches()).isFalse(); + + m = PpidChecker.BUSYBOX_CMD_OUT_PATTERN.matcher("05h38 1234567890"); + assertThat(m.matches()).isTrue(); + assertThat(PpidChecker.fromBusyboxHours(m)).isEqualTo(3600 * 5L); + assertThat(PpidChecker.fromBusyboxMinutes(m)).isEqualTo(60 * 38L); + assertThat(PpidChecker.fromBusyboxPID(m)).isEqualTo("1234567890"); } @Test - public void shouldHaveSystemPathToWmicOnWindows() throws Exception - { - assumeTrue( IS_OS_WINDOWS ); - assumeThat( System.getenv( "SystemRoot" ), is( notNullValue() ) ); - assumeThat( System.getenv( "SystemRoot" ), is( not( "" ) ) ); - assumeTrue( new File( System.getenv( "SystemRoot" ), "System32\\Wbem" ).isDirectory() ); - assumeTrue( new File( System.getenv( "SystemRoot" ), "System32\\Wbem\\wmic.exe" ).isFile() ); - assertThat( (Boolean) invokeMethod( PpidChecker.class, "hasWmicStandardSystemPath" ) ).isTrue(); - assertThat( new File( System.getenv( "SystemRoot" ), "System32\\Wbem\\wmic.exe" ) ).isFile(); + public void shouldHaveSystemPathToWmicOnWindows() throws Exception { + assumeTrue(IS_OS_WINDOWS); + assumeThat(System.getenv("SystemRoot"), is(notNullValue())); + assumeThat(System.getenv("SystemRoot"), is(not(""))); + assumeTrue(new File(System.getenv("SystemRoot"), "System32\\Wbem").isDirectory()); + assumeTrue(new File(System.getenv("SystemRoot"), "System32\\Wbem\\wmic.exe").isFile()); + assertThat((Boolean) invokeMethod(PpidChecker.class, "hasWmicStandardSystemPath")) + .isTrue(); + assertThat(new File(System.getenv("SystemRoot"), "System32\\Wbem\\wmic.exe")) + .isFile(); } @Test - public void shouldBeTypeNull() - { - assertThat( ProcessCheckerType.toEnum( null ) ) - .isNull(); + public void shouldBeTypeNull() { + assertThat(ProcessCheckerType.toEnum(null)).isNull(); - assertThat( ProcessCheckerType.toEnum( " " ) ) - .isNull(); + assertThat(ProcessCheckerType.toEnum(" ")).isNull(); - assertThat( ProcessCheckerType.isValid( null ) ) - .isTrue(); + assertThat(ProcessCheckerType.isValid(null)).isTrue(); } @Test - public void shouldBeException() - { - exceptions.expect( IllegalArgumentException.class ); - exceptions.expectMessage( "unknown process checker" ); + public void shouldBeException() { + exceptions.expect(IllegalArgumentException.class); + exceptions.expectMessage("unknown process checker"); - assertThat( ProcessCheckerType.toEnum( "anything else" ) ) - .isNull(); + assertThat(ProcessCheckerType.toEnum("anything else")).isNull(); } @Test - public void shouldNotBeValid() - { - assertThat( ProcessCheckerType.isValid( "anything" ) ) - .isFalse(); + public void shouldNotBeValid() { + assertThat(ProcessCheckerType.isValid("anything")).isFalse(); } @Test - public void shouldBeTypePing() - { - assertThat( ProcessCheckerType.toEnum( "ping" ) ) - .isEqualTo( ProcessCheckerType.PING ); + public void shouldBeTypePing() { + assertThat(ProcessCheckerType.toEnum("ping")).isEqualTo(ProcessCheckerType.PING); - assertThat( ProcessCheckerType.isValid( "ping" ) ) - .isTrue(); + assertThat(ProcessCheckerType.isValid("ping")).isTrue(); - assertThat( ProcessCheckerType.PING.getType() ) - .isEqualTo( "ping" ); + assertThat(ProcessCheckerType.PING.getType()).isEqualTo("ping"); } @Test - public void shouldBeTypeNative() - { - assertThat( ProcessCheckerType.toEnum( "native" ) ) - .isEqualTo( ProcessCheckerType.NATIVE ); + public void shouldBeTypeNative() { + assertThat(ProcessCheckerType.toEnum("native")).isEqualTo(ProcessCheckerType.NATIVE); - assertThat( ProcessCheckerType.isValid( "native" ) ) - .isTrue(); + assertThat(ProcessCheckerType.isValid("native")).isTrue(); - assertThat( ProcessCheckerType.NATIVE.getType() ) - .isEqualTo( "native" ); + assertThat(ProcessCheckerType.NATIVE.getType()).isEqualTo("native"); } @Test - public void shouldBeTypeAll() - { - assertThat( ProcessCheckerType.toEnum( "all" ) ) - .isEqualTo( ProcessCheckerType.ALL ); + public void shouldBeTypeAll() { + assertThat(ProcessCheckerType.toEnum("all")).isEqualTo(ProcessCheckerType.ALL); - assertThat( ProcessCheckerType.isValid( "all" ) ) - .isTrue(); + assertThat(ProcessCheckerType.isValid("all")).isTrue(); - assertThat( ProcessCheckerType.ALL.getType() ) - .isEqualTo( "all" ); + assertThat(ProcessCheckerType.ALL.getType()).isEqualTo("all"); } - private static long windowsProcessStartTime( PpidChecker checker ) - { + private static long windowsProcessStartTime(PpidChecker checker) { return checker.windows().getTime(); } } diff --git a/surefire-booter/src/test/java/org/apache/maven/surefire/booter/PropertiesWrapperTest.java b/surefire-booter/src/test/java/org/apache/maven/surefire/booter/PropertiesWrapperTest.java index 06b08aa11b..072fbf7000 100644 --- a/surefire-booter/src/test/java/org/apache/maven/surefire/booter/PropertiesWrapperTest.java +++ b/surefire-booter/src/test/java/org/apache/maven/surefire/booter/PropertiesWrapperTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.booter; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.booter; import java.util.ArrayList; import java.util.HashMap; @@ -29,24 +28,21 @@ /** * @author Kristian Rosenvold */ -public class PropertiesWrapperTest - extends TestCase -{ - public void testAddList() - { - PropertiesWrapper propertiesWrapper = new PropertiesWrapper( new HashMap() ); +public class PropertiesWrapperTest extends TestCase { + public void testAddList() { + PropertiesWrapper propertiesWrapper = new PropertiesWrapper(new HashMap()); List items = new ArrayList<>(); - items.add( "String1" ); - items.add( "String2,String3" ); - items.add( "String4" ); - items.add( "String5," ); - propertiesWrapper.addList( items, "Test" ); - - final List test = propertiesWrapper.getStringList( "Test" ); - assertEquals( 5, test.size() ); - assertEquals( "String5", test.get( 4 ) ); - assertEquals( "String3", test.get( 2 ) ); - assertEquals( "String2", test.get( 1 ) ); + items.add("String1"); + items.add("String2,String3"); + items.add("String4"); + items.add("String5,"); + propertiesWrapper.addList(items, "Test"); + + final List test = propertiesWrapper.getStringList("Test"); + assertEquals(5, test.size()); + assertEquals("String5", test.get(4)); + assertEquals("String3", test.get(2)); + assertEquals("String2", test.get(1)); } private static final String DUMMY_PREFIX = "dummyPrefix"; @@ -57,47 +53,39 @@ public void testAddList() private final Map properties = new HashMap<>(); - private final PropertiesWrapper mapper = new PropertiesWrapper( properties ); + private final PropertiesWrapper mapper = new PropertiesWrapper(properties); private final Classpath classpathWithTwoElements = createClasspathWithTwoElements(); - public void testReadFromProperties() - { - properties.put( DUMMY_PREFIX + "0", FIRST_ELEMENT ); - properties.put( DUMMY_PREFIX + "1", SECOND_ELEMENT ); + public void testReadFromProperties() { + properties.put(DUMMY_PREFIX + "0", FIRST_ELEMENT); + properties.put(DUMMY_PREFIX + "1", SECOND_ELEMENT); Classpath recreatedClasspath = readClasspathFromProperties(); - assertEquals( classpathWithTwoElements, recreatedClasspath ); + assertEquals(classpathWithTwoElements, recreatedClasspath); } - public void testReadFromPropertiesWithEmptyProperties() - { + public void testReadFromPropertiesWithEmptyProperties() { Classpath recreatedClasspath = readClasspathFromProperties(); - assertTrue( recreatedClasspath.getClassPath().isEmpty() ); + assertTrue(recreatedClasspath.getClassPath().isEmpty()); } - public void testWriteToProperties() - { - mapper.setClasspath( DUMMY_PREFIX, classpathWithTwoElements ); - assertEquals( FIRST_ELEMENT, mapper.getProperty( DUMMY_PREFIX + "0" ) ); - assertEquals( SECOND_ELEMENT, mapper.getProperty( DUMMY_PREFIX + "1" ) ); + public void testWriteToProperties() { + mapper.setClasspath(DUMMY_PREFIX, classpathWithTwoElements); + assertEquals(FIRST_ELEMENT, mapper.getProperty(DUMMY_PREFIX + "0")); + assertEquals(SECOND_ELEMENT, mapper.getProperty(DUMMY_PREFIX + "1")); } - public void testRoundtrip() - { - mapper.setClasspath( DUMMY_PREFIX, classpathWithTwoElements ); + public void testRoundtrip() { + mapper.setClasspath(DUMMY_PREFIX, classpathWithTwoElements); Classpath recreatedClasspath = readClasspathFromProperties(); - assertEquals( classpathWithTwoElements, recreatedClasspath ); + assertEquals(classpathWithTwoElements, recreatedClasspath); } - private Classpath createClasspathWithTwoElements() - { - return Classpath.emptyClasspath() - .addClassPathElementUrl( FIRST_ELEMENT ) - .addClassPathElementUrl( SECOND_ELEMENT ); + private Classpath createClasspathWithTwoElements() { + return Classpath.emptyClasspath().addClassPathElementUrl(FIRST_ELEMENT).addClassPathElementUrl(SECOND_ELEMENT); } - private Classpath readClasspathFromProperties() - { - return mapper.getClasspath( DUMMY_PREFIX ); + private Classpath readClasspathFromProperties() { + return mapper.getClasspath(DUMMY_PREFIX); } } diff --git a/surefire-booter/src/test/java/org/apache/maven/surefire/booter/SurefireReflectorTest.java b/surefire-booter/src/test/java/org/apache/maven/surefire/booter/SurefireReflectorTest.java index 18e34a0671..4e90ffd3b1 100644 --- a/surefire-booter/src/test/java/org/apache/maven/surefire/booter/SurefireReflectorTest.java +++ b/surefire-booter/src/test/java/org/apache/maven/surefire/booter/SurefireReflectorTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.booter; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,13 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.booter; + +import java.io.File; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; import junit.framework.TestCase; import org.apache.maven.surefire.api.booter.BaseProviderFactory; @@ -34,12 +39,6 @@ import org.apache.maven.surefire.api.testset.TestRequest; import org.apache.maven.surefire.api.util.RunOrder; -import java.io.File; -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; - import static java.util.Arrays.asList; import static org.apache.maven.surefire.api.cli.CommandLineOption.LOGGING_LEVEL_DEBUG; import static org.apache.maven.surefire.api.cli.CommandLineOption.SHOW_ERRORS; @@ -47,385 +46,337 @@ /** * */ -public class SurefireReflectorTest - extends TestCase -{ - public void testShouldCreateFactoryWithoutException() - { - ReporterFactory factory = new ReporterFactory() - { +public class SurefireReflectorTest extends TestCase { + public void testShouldCreateFactoryWithoutException() { + ReporterFactory factory = new ReporterFactory() { @Override - public TestReportListener createTestReportListener() - { + public TestReportListener createTestReportListener() { return null; } @Override - public RunResult close() - { + public RunResult close() { return null; } }; ClassLoader cl = Thread.currentThread().getContextClassLoader(); - SurefireReflector reflector = new SurefireReflector( cl ); - BaseProviderFactory bpf = (BaseProviderFactory) reflector.createBooterConfiguration( cl, true ); - bpf.setReporterFactory( factory ); - assertNotNull( bpf.getReporterFactory() ); - assertSame( factory, bpf.getReporterFactory() ); + SurefireReflector reflector = new SurefireReflector(cl); + BaseProviderFactory bpf = (BaseProviderFactory) reflector.createBooterConfiguration(cl, true); + bpf.setReporterFactory(factory); + assertNotNull(bpf.getReporterFactory()); + assertSame(factory, bpf.getReporterFactory()); } - public void testSetDirectoryScannerParameters() - { + public void testSetDirectoryScannerParameters() { SurefireReflector surefireReflector = getReflector(); Object foo = getFoo(); - DirectoryScannerParameters directoryScannerParameters = - new DirectoryScannerParameters( new File( "ABC" ), new ArrayList(), new ArrayList(), - new ArrayList(), "hourly" ); - surefireReflector.setDirectoryScannerParameters( foo, directoryScannerParameters ); - assertTrue( isCalled( foo ) ); - assertNotNull( ( (Foo) foo ).getDirectoryScannerParameters() ); + DirectoryScannerParameters directoryScannerParameters = new DirectoryScannerParameters( + new File("ABC"), new ArrayList(), new ArrayList(), new ArrayList(), "hourly"); + surefireReflector.setDirectoryScannerParameters(foo, directoryScannerParameters); + assertTrue(isCalled(foo)); + assertNotNull(((Foo) foo).getDirectoryScannerParameters()); } - public void testNullSetDirectoryScannerParameters() - { + public void testNullSetDirectoryScannerParameters() { SurefireReflector surefireReflector = getReflector(); Object foo = getFoo(); - surefireReflector.setDirectoryScannerParameters( foo, null ); - assertTrue( isCalled( foo ) ); - assertNull( ( (Foo) foo ).getDirectoryScannerParameters() ); + surefireReflector.setDirectoryScannerParameters(foo, null); + assertTrue(isCalled(foo)); + assertNull(((Foo) foo).getDirectoryScannerParameters()); } - public void testSetIfDirScannerAware() - { + public void testSetIfDirScannerAware() { SurefireReflector surefireReflector = getReflector(); Object foo = getFoo(); - DirectoryScannerParameters directoryScannerParameters = - new DirectoryScannerParameters( new File( "ABC" ), new ArrayList(), new ArrayList(), - new ArrayList(), "hourly" ); - surefireReflector.setIfDirScannerAware( foo, directoryScannerParameters ); - assertTrue( isCalled( foo ) ); + DirectoryScannerParameters directoryScannerParameters = new DirectoryScannerParameters( + new File("ABC"), new ArrayList(), new ArrayList(), new ArrayList(), "hourly"); + surefireReflector.setIfDirScannerAware(foo, directoryScannerParameters); + assertTrue(isCalled(foo)); } - public void testRunOrderParameters() - { + public void testRunOrderParameters() { SurefireReflector surefireReflector = getReflector(); Object foo = getFoo(); - RunOrderParameters runOrderParameters = new RunOrderParameters( RunOrder.DEFAULT, new File( "." ) ); - surefireReflector.setRunOrderParameters( foo, runOrderParameters ); - assertTrue( isCalled( foo ) ); + RunOrderParameters runOrderParameters = new RunOrderParameters(RunOrder.DEFAULT, new File(".")); + surefireReflector.setRunOrderParameters(foo, runOrderParameters); + assertTrue(isCalled(foo)); } - public void testRunOrderParametersWithRunOrderRandomSeed() - { + public void testRunOrderParametersWithRunOrderRandomSeed() { SurefireReflector surefireReflector = getReflector(); Object foo = getFoo(); // Arbitrary random seed that should be ignored because RunOrder is not RANDOM Long runOrderRandomSeed = 5L; - RunOrderParameters runOrderParameters = new RunOrderParameters( RunOrder.DEFAULT, new File( "." ), - runOrderRandomSeed ); - surefireReflector.setRunOrderParameters( foo, runOrderParameters ); - assertTrue( isCalled( foo ) ); + RunOrderParameters runOrderParameters = + new RunOrderParameters(RunOrder.DEFAULT, new File("."), runOrderRandomSeed); + surefireReflector.setRunOrderParameters(foo, runOrderParameters); + assertTrue(isCalled(foo)); } - public void testNullRunOrderParameters() - { + public void testNullRunOrderParameters() { SurefireReflector surefireReflector = getReflector(); Object foo = getFoo(); - surefireReflector.setRunOrderParameters( foo, null ); - assertTrue( isCalled( foo ) ); - try - { - ( (Foo) foo ).getRunOrderCalculator(); - } - catch ( NullPointerException e ) - { + surefireReflector.setRunOrderParameters(foo, null); + assertTrue(isCalled(foo)); + try { + ((Foo) foo).getRunOrderCalculator(); + } catch (NullPointerException e) { return; } fail(); } - public void testTestSuiteDefinition() - { + public void testTestSuiteDefinition() { SurefireReflector surefireReflector = getReflector(); Object foo = getFoo(); - TestRequest testSuiteDefinition = - new TestRequest( asList( new File( "file1" ), new File( "file2" ) ), - new File( "TestSOurce" ), new TestListResolver( "aUserRequestedTest#aMethodRequested" ) ); - surefireReflector.setTestSuiteDefinition( foo, testSuiteDefinition ); - assertTrue( isCalled( foo ) ); - assertNotNull( ( (Foo) foo ).getTestRequest() ); + TestRequest testSuiteDefinition = new TestRequest( + asList(new File("file1"), new File("file2")), + new File("TestSOurce"), + new TestListResolver("aUserRequestedTest#aMethodRequested")); + surefireReflector.setTestSuiteDefinition(foo, testSuiteDefinition); + assertTrue(isCalled(foo)); + assertNotNull(((Foo) foo).getTestRequest()); } - public void testNullTestSuiteDefinition() - { + public void testNullTestSuiteDefinition() { SurefireReflector surefireReflector = getReflector(); Object foo = getFoo(); - surefireReflector.setTestSuiteDefinition( foo, null ); - assertTrue( isCalled( foo ) ); - assertNull( ( (Foo) foo ).getTestRequest() ); + surefireReflector.setTestSuiteDefinition(foo, null); + assertTrue(isCalled(foo)); + assertNull(((Foo) foo).getTestRequest()); } - public void testProviderProperties() - { + public void testProviderProperties() { SurefireReflector surefireReflector = getReflector(); Object foo = getFoo(); - surefireReflector.setProviderProperties( foo, new HashMap() ); - assertTrue( isCalled( foo ) ); + surefireReflector.setProviderProperties(foo, new HashMap()); + assertTrue(isCalled(foo)); } - public void testReporterConfiguration() - { + public void testReporterConfiguration() { SurefireReflector surefireReflector = getReflector(); Object foo = getFoo(); ReporterConfiguration reporterConfiguration = getReporterConfiguration(); - surefireReflector.setReporterConfigurationAware( foo, reporterConfiguration ); - assertTrue( isCalled( foo ) ); + surefireReflector.setReporterConfigurationAware(foo, reporterConfiguration); + assertTrue(isCalled(foo)); } - private ReporterConfiguration getReporterConfiguration() - { - return new ReporterConfiguration( new File( "CDE" ), true ); + private ReporterConfiguration getReporterConfiguration() { + return new ReporterConfiguration(new File("CDE"), true); } - public void testTestClassLoader() - { + public void testTestClassLoader() { SurefireReflector surefireReflector = getReflector(); Object foo = getFoo(); - surefireReflector.setTestClassLoader( foo, getClass().getClassLoader() ); - assertTrue( isCalled( foo ) ); + surefireReflector.setTestClassLoader(foo, getClass().getClassLoader()); + assertTrue(isCalled(foo)); } - public void testTestClassLoaderAware() - { + public void testTestClassLoaderAware() { SurefireReflector surefireReflector = getReflector(); Object foo = getFoo(); - surefireReflector.setTestClassLoaderAware( foo, getClass().getClassLoader() ); - assertTrue( isCalled( foo ) ); + surefireReflector.setTestClassLoaderAware(foo, getClass().getClassLoader()); + assertTrue(isCalled(foo)); } - public void testArtifactInfo() - { + public void testArtifactInfo() { SurefireReflector surefireReflector = getReflector(); Object foo = getFoo(); - TestArtifactInfo testArtifactInfo = new TestArtifactInfo( "12.3", "test" ); - surefireReflector.setTestArtifactInfo( foo, testArtifactInfo ); - assertTrue( isCalled( foo ) ); + TestArtifactInfo testArtifactInfo = new TestArtifactInfo("12.3", "test"); + surefireReflector.setTestArtifactInfo(foo, testArtifactInfo); + assertTrue(isCalled(foo)); } - public void testNullArtifactInfo() - { + public void testNullArtifactInfo() { SurefireReflector surefireReflector = getReflector(); Object foo = getFoo(); - surefireReflector.setTestArtifactInfo( foo, null ); - assertTrue( isCalled( foo ) ); - assertNull( ( (Foo) foo ).getTestArtifactInfo() ); + surefireReflector.setTestArtifactInfo(foo, null); + assertTrue(isCalled(foo)); + assertNull(((Foo) foo).getTestArtifactInfo()); } - public void testArtifactInfoAware() - { + public void testArtifactInfoAware() { SurefireReflector surefireReflector = getReflector(); Object foo = getFoo(); - TestArtifactInfo testArtifactInfo = new TestArtifactInfo( "12.3", "test" ); - surefireReflector.setTestArtifactInfoAware( foo, testArtifactInfo ); - assertTrue( isCalled( foo ) ); - assertEquals( testArtifactInfo.getClassifier(), "test" ); - assertEquals( testArtifactInfo.getVersion(), "12.3" ); + TestArtifactInfo testArtifactInfo = new TestArtifactInfo("12.3", "test"); + surefireReflector.setTestArtifactInfoAware(foo, testArtifactInfo); + assertTrue(isCalled(foo)); + assertEquals(testArtifactInfo.getClassifier(), "test"); + assertEquals(testArtifactInfo.getVersion(), "12.3"); } - public void testReporterFactory() - { + public void testReporterFactory() { SurefireReflector surefireReflector = getReflector(); Object foo = getFoo(); - ReporterFactory reporterFactory = new ReporterFactory() - { + ReporterFactory reporterFactory = new ReporterFactory() { @Override - public TestReportListener createTestReportListener() - { + public TestReportListener createTestReportListener() { return null; } @Override - public RunResult close() - { + public RunResult close() { return null; } }; - surefireReflector.setReporterFactory( foo, reporterFactory ); - assertTrue( isCalled( foo ) ); + surefireReflector.setReporterFactory(foo, reporterFactory); + assertTrue(isCalled(foo)); } - public void testReporterFactoryAware() - { + public void testReporterFactoryAware() { SurefireReflector surefireReflector = getReflector(); Object foo = getFoo(); - ReporterFactory reporterFactory = new ReporterFactory() - { + ReporterFactory reporterFactory = new ReporterFactory() { @Override - public TestReportListener createTestReportListener() - { + public TestReportListener createTestReportListener() { return null; } @Override - public RunResult close() - { + public RunResult close() { return null; } }; - surefireReflector.setReporterFactoryAware( foo, reporterFactory ); - assertTrue( isCalled( foo ) ); - assertSame( ( (Foo) foo ).getReporterFactory(), reporterFactory ); + surefireReflector.setReporterFactoryAware(foo, reporterFactory); + assertTrue(isCalled(foo)); + assertSame(((Foo) foo).getReporterFactory(), reporterFactory); } - @SuppressWarnings( "checkstyle:magicnumber" ) - public void testConvertIfRunResult() - { - RunResult runResult = new RunResult( 20, 1, 2, 3, 4, "IOException", true ); - SurefireReflector reflector = new SurefireReflector( Thread.currentThread().getContextClassLoader() ); - RunResult obj = (RunResult) reflector.convertIfRunResult( runResult ); - assertEquals( obj.getCompletedCount(), 20 ); - assertEquals( obj.getErrors(), 1 ); - assertEquals( obj.getFailures(), 2 ); - assertEquals( obj.getSkipped(), 3 ); - assertFalse( obj.isErrorFree() ); - assertFalse( obj.isInternalError() ); - assertEquals( obj.getFailsafeCode(), (Integer) RunResult.FAILURE ); - - assertNull( reflector.convertIfRunResult( null ) ); - assertEquals( reflector.convertIfRunResult( "" ), "" ); + @SuppressWarnings("checkstyle:magicnumber") + public void testConvertIfRunResult() { + RunResult runResult = new RunResult(20, 1, 2, 3, 4, "IOException", true); + SurefireReflector reflector = + new SurefireReflector(Thread.currentThread().getContextClassLoader()); + RunResult obj = (RunResult) reflector.convertIfRunResult(runResult); + assertEquals(obj.getCompletedCount(), 20); + assertEquals(obj.getErrors(), 1); + assertEquals(obj.getFailures(), 2); + assertEquals(obj.getSkipped(), 3); + assertFalse(obj.isErrorFree()); + assertFalse(obj.isInternalError()); + assertEquals(obj.getFailsafeCode(), (Integer) RunResult.FAILURE); + + assertNull(reflector.convertIfRunResult(null)); + assertEquals(reflector.convertIfRunResult(""), ""); } - public void testInstantiateProvider() - { - SurefireReflector reflector = new SurefireReflector( Thread.currentThread().getContextClassLoader() ); + public void testInstantiateProvider() { + SurefireReflector reflector = + new SurefireReflector(Thread.currentThread().getContextClassLoader()); Object booterParams = getFoo(); - Object provider = reflector.instantiateProvider( DummyProvider.class.getName(), booterParams ); - assertNotNull( provider ); - assertEquals( provider.getClass(), DummyProvider.class ); + Object provider = reflector.instantiateProvider(DummyProvider.class.getName(), booterParams); + assertNotNull(provider); + assertEquals(provider.getClass(), DummyProvider.class); } - public void testSetMainCliOptions() - { - SurefireReflector reflector = new SurefireReflector( Thread.currentThread().getContextClassLoader() ); + public void testSetMainCliOptions() { + SurefireReflector reflector = + new SurefireReflector(Thread.currentThread().getContextClassLoader()); Object booterParams = getFoo(); - reflector.setMainCliOptions( booterParams, asList( SHOW_ERRORS, LOGGING_LEVEL_DEBUG ) ); - assertEquals( ( (BaseProviderFactory) booterParams ).getMainCliOptions().size(), 2 ); - assertEquals( ( (BaseProviderFactory) booterParams ).getMainCliOptions().get( 0 ), SHOW_ERRORS ); - assertEquals( ( (BaseProviderFactory) booterParams ).getMainCliOptions().get( 1 ), LOGGING_LEVEL_DEBUG ); + reflector.setMainCliOptions(booterParams, asList(SHOW_ERRORS, LOGGING_LEVEL_DEBUG)); + assertEquals(((BaseProviderFactory) booterParams).getMainCliOptions().size(), 2); + assertEquals(((BaseProviderFactory) booterParams).getMainCliOptions().get(0), SHOW_ERRORS); + assertEquals(((BaseProviderFactory) booterParams).getMainCliOptions().get(1), LOGGING_LEVEL_DEBUG); } - public void testSetSkipAfterFailureCount() - { - SurefireReflector reflector = new SurefireReflector( Thread.currentThread().getContextClassLoader() ); + public void testSetSkipAfterFailureCount() { + SurefireReflector reflector = + new SurefireReflector(Thread.currentThread().getContextClassLoader()); Foo booterParams = (Foo) getFoo(); - assertEquals( booterParams.getSkipAfterFailureCount(), 0 ); - reflector.setSkipAfterFailureCount( booterParams, 5 ); - assertEquals( booterParams.getSkipAfterFailureCount(), 5 ); + assertEquals(booterParams.getSkipAfterFailureCount(), 0); + reflector.setSkipAfterFailureCount(booterParams, 5); + assertEquals(booterParams.getSkipAfterFailureCount(), 5); } - @SuppressWarnings( "checkstyle:magicnumber" ) - public void testSetSystemExitTimeout() - { - SurefireReflector reflector = new SurefireReflector( Thread.currentThread().getContextClassLoader() ); + @SuppressWarnings("checkstyle:magicnumber") + public void testSetSystemExitTimeout() { + SurefireReflector reflector = + new SurefireReflector(Thread.currentThread().getContextClassLoader()); Foo booterParams = (Foo) getFoo(); - assertNull( booterParams.getSystemExitTimeout() ); - reflector.setSystemExitTimeout( booterParams, 60 ); - assertEquals( booterParams.getSystemExitTimeout(), (Integer) 60 ); + assertNull(booterParams.getSystemExitTimeout()); + reflector.setSystemExitTimeout(booterParams, 60); + assertEquals(booterParams.getSystemExitTimeout(), (Integer) 60); } - public void testSetTestSuiteDefinitionAware() - { - SurefireReflector reflector = new SurefireReflector( Thread.currentThread().getContextClassLoader() ); + public void testSetTestSuiteDefinitionAware() { + SurefireReflector reflector = + new SurefireReflector(Thread.currentThread().getContextClassLoader()); Foo booterParams = (Foo) getFoo(); - TestRequest request = new TestRequest( Collections.emptyList(), null, null ); - reflector.setTestSuiteDefinitionAware( booterParams, request ); - assertTrue( booterParams.isCalled() ); - assertNotNull( booterParams.getTestRequest() ); - assertTrue( booterParams.getTestRequest().getSuiteXmlFiles().isEmpty() ); - assertNull( booterParams.getTestRequest().getTestSourceDirectory() ); - assertNull( booterParams.getTestRequest().getTestListResolver() ); - assertEquals( booterParams.getTestRequest().getRerunFailingTestsCount(), 0 ); + TestRequest request = new TestRequest(Collections.emptyList(), null, null); + reflector.setTestSuiteDefinitionAware(booterParams, request); + assertTrue(booterParams.isCalled()); + assertNotNull(booterParams.getTestRequest()); + assertTrue(booterParams.getTestRequest().getSuiteXmlFiles().isEmpty()); + assertNull(booterParams.getTestRequest().getTestSourceDirectory()); + assertNull(booterParams.getTestRequest().getTestListResolver()); + assertEquals(booterParams.getTestRequest().getRerunFailingTestsCount(), 0); } - public void testSetProviderPropertiesAware() - { - SurefireReflector reflector = new SurefireReflector( Thread.currentThread().getContextClassLoader() ); + public void testSetProviderPropertiesAware() { + SurefireReflector reflector = + new SurefireReflector(Thread.currentThread().getContextClassLoader()); Foo booterParams = (Foo) getFoo(); - reflector.setProviderPropertiesAware( booterParams, Collections.singletonMap( "k", "v" ) ); - assertTrue( booterParams.isCalled() ); - assertNotNull( booterParams.getProviderProperties() ); - assertEquals( booterParams.getProviderProperties().size(), 1 ); - assertEquals( booterParams.getProviderProperties().get( "k" ), "v" ); + reflector.setProviderPropertiesAware(booterParams, Collections.singletonMap("k", "v")); + assertTrue(booterParams.isCalled()); + assertNotNull(booterParams.getProviderProperties()); + assertEquals(booterParams.getProviderProperties().size(), 1); + assertEquals(booterParams.getProviderProperties().get("k"), "v"); } - private SurefireReflector getReflector() - { - return new SurefireReflector( getClass().getClassLoader() ); + private SurefireReflector getReflector() { + return new SurefireReflector(getClass().getClassLoader()); } - private Object getFoo() - { // Todo: Setup a different classloader so we can really test crossing + private Object getFoo() { // Todo: Setup a different classloader so we can really test crossing return new Foo(); } - private Boolean isCalled( Object foo ) - { + private Boolean isCalled(Object foo) { final Method isCalled; - try - { - isCalled = foo.getClass().getMethod( "isCalled" ); - return (Boolean) isCalled.invoke( foo ); - } - catch ( ReflectiveOperationException e ) - { - throw new RuntimeException( e ); + try { + isCalled = foo.getClass().getMethod("isCalled"); + return (Boolean) isCalled.invoke(foo); + } catch (ReflectiveOperationException e) { + throw new RuntimeException(e); } } /** * */ - public static final class DummyProvider implements SurefireProvider - { - public DummyProvider( ProviderParameters providerParameters ) - { - } + public static final class DummyProvider implements SurefireProvider { + public DummyProvider(ProviderParameters providerParameters) {} @Override - public Iterable> getSuites() - { + public Iterable> getSuites() { return null; } @Override - public RunResult invoke( Object forkTestSet ) - { + public RunResult invoke(Object forkTestSet) { return null; } @Override - public void cancel() - { - - } + public void cancel() {} } } diff --git a/surefire-booter/src/test/java/org/apache/maven/surefire/booter/SystemUtilsTest.java b/surefire-booter/src/test/java/org/apache/maven/surefire/booter/SystemUtilsTest.java index 6b2ac265fc..2e7017d0fc 100644 --- a/surefire-booter/src/test/java/org/apache/maven/surefire/booter/SystemUtilsTest.java +++ b/surefire-booter/src/test/java/org/apache/maven/surefire/booter/SystemUtilsTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.booter; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,12 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.booter; + +import java.io.File; +import java.io.IOException; +import java.lang.management.ManagementFactory; +import java.math.BigDecimal; import org.junit.Test; import org.junit.experimental.runners.Enclosed; @@ -26,11 +30,6 @@ import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; -import java.io.File; -import java.io.IOException; -import java.lang.management.ManagementFactory; -import java.math.BigDecimal; - import static java.io.File.separator; import static org.apache.maven.surefire.shared.lang3.JavaVersion.JAVA_9; import static org.apache.maven.surefire.shared.lang3.JavaVersion.JAVA_RECENT; @@ -53,305 +52,256 @@ * @author Tibor Digana (tibor17) * @since 2.20.1 */ -@SuppressWarnings( "checkstyle:magicnumber" ) -@RunWith( Enclosed.class ) -public class SystemUtilsTest -{ +@SuppressWarnings("checkstyle:magicnumber") +@RunWith(Enclosed.class) +public class SystemUtilsTest { /** * */ - public static class PlainUnitTests - { + public static class PlainUnitTests { @Test - public void shouldParseProprietaryReleaseFile() throws IOException - { - String classes = new File( "." ).getCanonicalPath() + separator + "target" + separator + "test-classes"; + public void shouldParseProprietaryReleaseFile() throws IOException { + String classes = new File(".").getCanonicalPath() + separator + "target" + separator + "test-classes"; - File path = new File( classes, "jdk8-IBM" + separator + "bin" + separator + "java" ); - assertThat( SystemUtils.isJava9AtLeast( path.getAbsolutePath() ) ).isFalse(); + File path = new File(classes, "jdk8-IBM" + separator + "bin" + separator + "java"); + assertThat(SystemUtils.isJava9AtLeast(path.getAbsolutePath())).isFalse(); - path = new File( classes, "jdk8-oracle" + separator + "bin" + separator + "java" ); - assertThat( SystemUtils.isJava9AtLeast( path.getAbsolutePath() ) ).isFalse(); + path = new File(classes, "jdk8-oracle" + separator + "bin" + separator + "java"); + assertThat(SystemUtils.isJava9AtLeast(path.getAbsolutePath())).isFalse(); - path = new File( classes, "jdk9-oracle" + separator + "bin" + separator + "java" ); - assertThat( SystemUtils.isJava9AtLeast( path.getAbsolutePath() ) ).isTrue(); + path = new File(classes, "jdk9-oracle" + separator + "bin" + separator + "java"); + assertThat(SystemUtils.isJava9AtLeast(path.getAbsolutePath())).isTrue(); } @Test - public void incorrectJdkPath() - { - File jre = new File( System.getProperty( "java.home" ) ); + public void incorrectJdkPath() { + File jre = new File(System.getProperty("java.home")); File jdk = jre.getParentFile(); File incorrect = jdk.getParentFile(); - assertThat( SystemUtils.isJava9AtLeast( incorrect.getAbsolutePath() ) ).isFalse(); + assertThat(SystemUtils.isJava9AtLeast(incorrect.getAbsolutePath())).isFalse(); } @Test - public void shouldHaveJavaPath() - { - String javaPath = System.getProperty( "java.home" ) + separator + "bin" + separator + "java"; - assertThat( SystemUtils.endsWithJavaPath( javaPath ) ).isTrue(); + public void shouldHaveJavaPath() { + String javaPath = System.getProperty("java.home") + separator + "bin" + separator + "java"; + assertThat(SystemUtils.endsWithJavaPath(javaPath)).isTrue(); } @Test - public void shouldNotHaveJavaPath() - { - assertThat( SystemUtils.endsWithJavaPath( "/jdk" ) ).isFalse(); + public void shouldNotHaveJavaPath() { + assertThat(SystemUtils.endsWithJavaPath("/jdk")).isFalse(); } @Test - public void shouldNotExtractJdkHomeFromJavaExec() - { - File pathToJdk = SystemUtils.toJdkHomeFromJvmExec( "/jdk/binx/java" ); - assertThat( pathToJdk ).isNull(); + public void shouldNotExtractJdkHomeFromJavaExec() { + File pathToJdk = SystemUtils.toJdkHomeFromJvmExec("/jdk/binx/java"); + assertThat(pathToJdk).isNull(); } @Test - public void shouldExtractJdkHomeFromJavaExec() - { - File pathToJdk = SystemUtils.toJdkHomeFromJvmExec( "/jdk/bin/java" ); - assertThat( pathToJdk ).isEqualTo( new File( "/jdk" ).getAbsoluteFile() ); + public void shouldExtractJdkHomeFromJavaExec() { + File pathToJdk = SystemUtils.toJdkHomeFromJvmExec("/jdk/bin/java"); + assertThat(pathToJdk).isEqualTo(new File("/jdk").getAbsoluteFile()); } @Test - public void shouldNotExtractJdkHomeFromJreExec() throws IOException - { - String classes = new File( "." ).getCanonicalPath() + separator + "target" + separator + "test-classes"; - File jdk = new File( classes, "jdk" ); + public void shouldNotExtractJdkHomeFromJreExec() throws IOException { + String classes = new File(".").getCanonicalPath() + separator + "target" + separator + "test-classes"; + File jdk = new File(classes, "jdk"); String pathToJreExec = jdk.getAbsolutePath() + separator + "jre" + separator + "binx" + separator + "java"; - File pathToJdk = SystemUtils.toJdkHomeFromJvmExec( pathToJreExec ); - assertThat( pathToJdk ).isNull(); + File pathToJdk = SystemUtils.toJdkHomeFromJvmExec(pathToJreExec); + assertThat(pathToJdk).isNull(); } @Test - public void shouldExtractJdkHomeFromJreExec() throws IOException - { - String classes = new File( "." ).getCanonicalPath() + separator + "target" + separator + "test-classes"; - File jdk = new File( classes, "jdk" ); + public void shouldExtractJdkHomeFromJreExec() throws IOException { + String classes = new File(".").getCanonicalPath() + separator + "target" + separator + "test-classes"; + File jdk = new File(classes, "jdk"); String pathToJreExec = jdk.getAbsolutePath() + separator + "jre" + separator + "bin" + separator + "java"; - File pathToJdk = SystemUtils.toJdkHomeFromJvmExec( pathToJreExec ); - assertThat( pathToJdk ).isEqualTo( jdk ); + File pathToJdk = SystemUtils.toJdkHomeFromJvmExec(pathToJreExec); + assertThat(pathToJdk).isEqualTo(jdk); } @Test - public void shouldExtractJdkHomeFromJre() - { - File pathToJdk = SystemUtils.toJdkHomeFromJre( "/jdk/jre" ); - assertThat( pathToJdk ).isEqualTo( new File( "/jdk" ).getAbsoluteFile() ); + public void shouldExtractJdkHomeFromJre() { + File pathToJdk = SystemUtils.toJdkHomeFromJre("/jdk/jre"); + assertThat(pathToJdk).isEqualTo(new File("/jdk").getAbsoluteFile()); } @Test - public void shouldExtractJdkHomeFromJdk() - { - File pathToJdk = SystemUtils.toJdkHomeFromJre( "/jdk/" ); - assertThat( pathToJdk ).isEqualTo( new File( "/jdk" ).getAbsoluteFile() ); + public void shouldExtractJdkHomeFromJdk() { + File pathToJdk = SystemUtils.toJdkHomeFromJre("/jdk/"); + assertThat(pathToJdk).isEqualTo(new File("/jdk").getAbsoluteFile()); } @Test - public void shouldExtractJdkHomeFromRealPath() - { + public void shouldExtractJdkHomeFromRealPath() { File pathToJdk = SystemUtils.toJdkHomeFromJre(); - if ( JAVA_RECENT.atLeast( JAVA_9 ) ) - { - File realJdkHome = new File( System.getProperty( "java.home" ) ).getAbsoluteFile(); - assertThat( realJdkHome ).isDirectory(); - assertThat( realJdkHome.getName() ).isNotEqualTo( "jre" ); - assertThat( pathToJdk ).isEqualTo( realJdkHome ); - } - else - { - File realJreHome = new File( System.getProperty( "java.home" ) ).getAbsoluteFile(); - assertThat( realJreHome ).isDirectory(); - assertThat( realJreHome.getName() ).isEqualTo( "jre" ); + if (JAVA_RECENT.atLeast(JAVA_9)) { + File realJdkHome = new File(System.getProperty("java.home")).getAbsoluteFile(); + assertThat(realJdkHome).isDirectory(); + assertThat(realJdkHome.getName()).isNotEqualTo("jre"); + assertThat(pathToJdk).isEqualTo(realJdkHome); + } else { + File realJreHome = new File(System.getProperty("java.home")).getAbsoluteFile(); + assertThat(realJreHome).isDirectory(); + assertThat(realJreHome.getName()).isEqualTo("jre"); File realJdkHome = realJreHome.getParentFile(); - assertThat( pathToJdk ).isEqualTo( realJdkHome ); + assertThat(pathToJdk).isEqualTo(realJdkHome); } } @Test - public void shouldBeJavaVersion() - { - assertThat( SystemUtils.isJava9AtLeast( (BigDecimal ) null ) ).isFalse(); - assertThat( SystemUtils.isJava9AtLeast( new BigDecimal( "1.8" ) ) ).isFalse(); - assertThat( SystemUtils.isJava9AtLeast( new BigDecimal( 9 ) ) ).isTrue(); + public void shouldBeJavaVersion() { + assertThat(SystemUtils.isJava9AtLeast((BigDecimal) null)).isFalse(); + assertThat(SystemUtils.isJava9AtLeast(new BigDecimal("1.8"))).isFalse(); + assertThat(SystemUtils.isJava9AtLeast(new BigDecimal(9))).isTrue(); } @Test - public void shouldBePlatformClassLoader() - { + public void shouldBePlatformClassLoader() { ClassLoader cl = SystemUtils.platformClassLoader(); - if ( JAVA_RECENT.atLeast( JAVA_9 ) ) - { - assertThat( cl ).isNotNull(); - } - else - { - assertThat( cl ).isNull(); + if (JAVA_RECENT.atLeast(JAVA_9)) { + assertThat(cl).isNotNull(); + } else { + assertThat(cl).isNull(); } } @Test - public void shouldNotFindClassLoader() - { - ClassLoader cl = SystemUtils.reflectClassLoader( getClass(), "_getPlatformClassLoader_" ); - assertThat( cl ).isNull(); + public void shouldNotFindClassLoader() { + ClassLoader cl = SystemUtils.reflectClassLoader(getClass(), "_getPlatformClassLoader_"); + assertThat(cl).isNull(); } @Test - public void shouldFindClassLoader() - { - ClassLoader cl = SystemUtils.reflectClassLoader( getClass(), "getPlatformClassLoader" ); - assertThat( cl ).isSameAs( ClassLoader.getSystemClassLoader() ); + public void shouldFindClassLoader() { + ClassLoader cl = SystemUtils.reflectClassLoader(getClass(), "getPlatformClassLoader"); + assertThat(cl).isSameAs(ClassLoader.getSystemClassLoader()); } @Test - public void shouldBePidOnJigsaw() - { - assumeTrue( JAVA_RECENT.atLeast( JAVA_9 ) ); + public void shouldBePidOnJigsaw() { + assumeTrue(JAVA_RECENT.atLeast(JAVA_9)); Long actualPid = SystemUtils.pidOnJava9(); - String expectedPid = ManagementFactory.getRuntimeMXBean().getName().split( "@" )[0].trim(); + String expectedPid = + ManagementFactory.getRuntimeMXBean().getName().split("@")[0].trim(); - assertThat( actualPid + "" ) - .isEqualTo( expectedPid ); + assertThat(actualPid + "").isEqualTo(expectedPid); } @Test - public void shouldBePidStatusOnLinux() throws Exception - { - assumeTrue( IS_OS_LINUX ); + public void shouldBePidStatusOnLinux() throws Exception { + assumeTrue(IS_OS_LINUX); Long actualPid = SystemUtils.pidStatusOnLinux(); - String expectedPid = ManagementFactory.getRuntimeMXBean().getName().split( "@" )[0].trim(); + String expectedPid = + ManagementFactory.getRuntimeMXBean().getName().split("@")[0].trim(); - assertThat( actualPid + "" ) - .isEqualTo( expectedPid ); + assertThat(actualPid + "").isEqualTo(expectedPid); } @Test - public void shouldBeMockPidStatusOnLinux() throws Exception - { - String root = new File( System.getProperty( "user.dir" ), "target/test-classes" ).getAbsolutePath(); - Long actualPid = SystemUtils.pidStatusOnLinux( root ); - assertThat( actualPid ) - .isEqualTo( 48982L ); + public void shouldBeMockPidStatusOnLinux() throws Exception { + String root = new File(System.getProperty("user.dir"), "target/test-classes").getAbsolutePath(); + Long actualPid = SystemUtils.pidStatusOnLinux(root); + assertThat(actualPid).isEqualTo(48982L); } @Test - public void shouldBePidStatusOnBSD() throws Exception - { - assumeTrue( IS_OS_FREE_BSD || IS_OS_NET_BSD || IS_OS_OPEN_BSD ); + public void shouldBePidStatusOnBSD() throws Exception { + assumeTrue(IS_OS_FREE_BSD || IS_OS_NET_BSD || IS_OS_OPEN_BSD); Long actualPid = SystemUtils.pidStatusOnBSD(); - String expectedPid = ManagementFactory.getRuntimeMXBean().getName().split( "@" )[0].trim(); + String expectedPid = + ManagementFactory.getRuntimeMXBean().getName().split("@")[0].trim(); - assertThat( actualPid + "" ) - .isEqualTo( expectedPid ); + assertThat(actualPid + "").isEqualTo(expectedPid); } @Test - public void shouldBeMockPidStatusOnBSD() throws Exception - { - String root = new File( System.getProperty( "user.dir" ), "target/test-classes" ).getAbsolutePath(); - Long actualPid = SystemUtils.pidStatusOnBSD( root ); - assertThat( actualPid ) - .isEqualTo( 60424L ); + public void shouldBeMockPidStatusOnBSD() throws Exception { + String root = new File(System.getProperty("user.dir"), "target/test-classes").getAbsolutePath(); + Long actualPid = SystemUtils.pidStatusOnBSD(root); + assertThat(actualPid).isEqualTo(60424L); } @Test - public void shouldBePidOnJMX() - { + public void shouldBePidOnJMX() { Long actualPid = SystemUtils.pidOnJMX(); - String expectedPid = ManagementFactory.getRuntimeMXBean().getName().split( "@" )[0].trim(); + String expectedPid = + ManagementFactory.getRuntimeMXBean().getName().split("@")[0].trim(); - assertThat( actualPid + "" ) - .isEqualTo( expectedPid ); + assertThat(actualPid + "").isEqualTo(expectedPid); } @Test - public void shouldBePid() - { + public void shouldBePid() { Long actualPid = SystemUtils.pid(); - String expectedPid = ManagementFactory.getRuntimeMXBean().getName().split( "@" )[0].trim(); + String expectedPid = + ManagementFactory.getRuntimeMXBean().getName().split("@")[0].trim(); - assertThat( actualPid + "" ) - .isEqualTo( expectedPid ); + assertThat(actualPid + "").isEqualTo(expectedPid); } - @SuppressWarnings( "unused" ) - public static ClassLoader getPlatformClassLoader() - { + @SuppressWarnings("unused") + public static ClassLoader getPlatformClassLoader() { return ClassLoader.getSystemClassLoader(); } - } /** * */ - @RunWith( PowerMockRunner.class ) - @PrepareForTest( SystemUtils.class ) - @PowerMockIgnore( { "org.jacoco.agent.rt.*", "com.vladium.emma.rt.*" } ) - public static class MockTest - { + @RunWith(PowerMockRunner.class) + @PrepareForTest(SystemUtils.class) + @PowerMockIgnore({"org.jacoco.agent.rt.*", "com.vladium.emma.rt.*"}) + public static class MockTest { @Test - public void shouldBeDifferentJdk9() - { - testIsJava9AtLeast( new File( System.getProperty( "java.home" ) ) ); + public void shouldBeDifferentJdk9() { + testIsJava9AtLeast(new File(System.getProperty("java.home"))); } @Test - public void shouldBeSameJdk9() - { + public void shouldBeSameJdk9() { // PowerMockJUnit44RunnerDelegateImpl does not work with Assumptions: assumeFalse - if ( !JAVA_RECENT.atLeast( JAVA_9 ) ) - { - testIsJava9AtLeast( new File( System.getProperty( "java.home" ) ).getParentFile() ); + if (!JAVA_RECENT.atLeast(JAVA_9)) { + testIsJava9AtLeast(new File(System.getProperty("java.home")).getParentFile()); } } - private static void testIsJava9AtLeast( File pathInJdk ) - { - File path = new File( pathInJdk, "bin" + separator + "java" ); + private static void testIsJava9AtLeast(File pathInJdk) { + File path = new File(pathInJdk, "bin" + separator + "java"); - mockStatic( SystemUtils.class ); + mockStatic(SystemUtils.class); - when( SystemUtils.isJava9AtLeast( anyString() ) ) - .thenCallRealMethod(); + when(SystemUtils.isJava9AtLeast(anyString())).thenCallRealMethod(); - when( SystemUtils.toJdkHomeFromJvmExec( anyString() ) ) - .thenCallRealMethod(); + when(SystemUtils.toJdkHomeFromJvmExec(anyString())).thenCallRealMethod(); - when( SystemUtils.toJdkHomeFromJre() ) - .thenCallRealMethod(); + when(SystemUtils.toJdkHomeFromJre()).thenCallRealMethod(); - when( SystemUtils.toJdkHomeFromJre( anyString() ) ) - .thenCallRealMethod(); + when(SystemUtils.toJdkHomeFromJre(anyString())).thenCallRealMethod(); - when( SystemUtils.isBuiltInJava9AtLeast() ) - .thenCallRealMethod(); + when(SystemUtils.isBuiltInJava9AtLeast()).thenCallRealMethod(); - when( SystemUtils.toJdkVersionFromReleaseFile( any( File.class ) ) ) - .thenCallRealMethod(); + when(SystemUtils.toJdkVersionFromReleaseFile(any(File.class))).thenCallRealMethod(); - when( SystemUtils.isJava9AtLeast( any( BigDecimal.class ) ) ) - .thenCallRealMethod(); + when(SystemUtils.isJava9AtLeast(any(BigDecimal.class))).thenCallRealMethod(); - if ( JAVA_RECENT.atLeast( JAVA_9 ) ) - { - assertThat( SystemUtils.isJava9AtLeast( path.getAbsolutePath() ) ).isTrue(); - } - else - { - assertThat( SystemUtils.isJava9AtLeast( path.getAbsolutePath() ) ).isFalse(); + if (JAVA_RECENT.atLeast(JAVA_9)) { + assertThat(SystemUtils.isJava9AtLeast(path.getAbsolutePath())).isTrue(); + } else { + assertThat(SystemUtils.isJava9AtLeast(path.getAbsolutePath())).isFalse(); } - verifyStatic( SystemUtils.class, times( 0 ) ); - SystemUtils.toJdkVersionFromReleaseFile( any( File.class ) ); + verifyStatic(SystemUtils.class, times(0)); + SystemUtils.toJdkVersionFromReleaseFile(any(File.class)); - verifyStatic( SystemUtils.class, times( 1 ) ); + verifyStatic(SystemUtils.class, times(1)); SystemUtils.isBuiltInJava9AtLeast(); } } diff --git a/surefire-booter/src/test/java/org/apache/maven/surefire/booter/spi/CommandChannelDecoderTest.java b/surefire-booter/src/test/java/org/apache/maven/surefire/booter/spi/CommandChannelDecoderTest.java index d6c67761de..b75d68a426 100644 --- a/surefire-booter/src/test/java/org/apache/maven/surefire/booter/spi/CommandChannelDecoderTest.java +++ b/surefire-booter/src/test/java/org/apache/maven/surefire/booter/spi/CommandChannelDecoderTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.booter.spi; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,17 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.booter.spi; + +import javax.annotation.Nonnull; + +import java.io.ByteArrayInputStream; +import java.io.EOFException; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.util.Random; +import java.util.concurrent.ConcurrentLinkedQueue; import org.apache.maven.plugin.surefire.log.api.ConsoleLogger; import org.apache.maven.surefire.api.booter.Command; @@ -31,15 +40,6 @@ import org.junit.Test; import org.junit.rules.TemporaryFolder; -import javax.annotation.Nonnull; -import java.io.ByteArrayInputStream; -import java.io.EOFException; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.util.Random; -import java.util.concurrent.ConcurrentLinkedQueue; - import static java.nio.channels.Channels.newChannel; import static java.nio.charset.StandardCharsets.UTF_8; import static org.apache.maven.surefire.api.booter.MasterProcessCommand.BYE_ACK; @@ -59,359 +59,330 @@ /** * Tests for {@link CommandChannelDecoder}. */ -@SuppressWarnings( "checkstyle:magicnumber" ) -public class CommandChannelDecoderTest -{ +@SuppressWarnings("checkstyle:magicnumber") +public class CommandChannelDecoderTest { private static final Random RND = new Random(); @Rule public final TemporaryFolder tempFolder = new TemporaryFolder(); @Before - public void initTmpFile() - { + public void initTmpFile() { File reportsDir = tempFolder.getRoot(); String dumpFileName = "surefire-" + RND.nextLong(); - DumpErrorSingleton.getSingleton().init( reportsDir, dumpFileName ); + DumpErrorSingleton.getSingleton().init(reportsDir, dumpFileName); } @After - public void deleteTmpFiles() - { + public void deleteTmpFiles() { tempFolder.delete(); } @Test - public void testDecoderRunClass() throws IOException - { - assertEquals( String.class, RUN_CLASS.getDataType() ); - byte[] encoded = new StringBuilder( 512 ) - .append( ":maven-surefire-command:" ) - .append( (char) 13 ) - .append( ":run-testclass:" ) - .append( (char) 5 ) - .append( ":UTF-8:" ) - .append( (char) 0 ) - .append( (char) 0 ) - .append( (char) 0 ) - .append( (char) 8 ) - .append( ":" ) - .append( "pkg.Test" ) - .append( ":" ) - .toString() - .getBytes( UTF_8 ); - InputStream is = new ByteArrayInputStream( encoded ); - ForkNodeArguments args = new ForkedNodeArg( 1, false ); - CommandChannelDecoder decoder = new CommandChannelDecoder( newChannel( is ), args ); + public void testDecoderRunClass() throws IOException { + assertEquals(String.class, RUN_CLASS.getDataType()); + byte[] encoded = new StringBuilder(512) + .append(":maven-surefire-command:") + .append((char) 13) + .append(":run-testclass:") + .append((char) 5) + .append(":UTF-8:") + .append((char) 0) + .append((char) 0) + .append((char) 0) + .append((char) 8) + .append(":") + .append("pkg.Test") + .append(":") + .toString() + .getBytes(UTF_8); + InputStream is = new ByteArrayInputStream(encoded); + ForkNodeArguments args = new ForkedNodeArg(1, false); + CommandChannelDecoder decoder = new CommandChannelDecoder(newChannel(is), args); Command command = decoder.decode(); - assertThat( command.getCommandType() ).isSameAs( RUN_CLASS ); - assertThat( command.getData() ).isEqualTo( "pkg.Test" ); + assertThat(command.getCommandType()).isSameAs(RUN_CLASS); + assertThat(command.getData()).isEqualTo("pkg.Test"); } @Test - public void testDecoderTestsetFinished() throws IOException - { + public void testDecoderTestsetFinished() throws IOException { Command command = Command.TEST_SET_FINISHED; - assertThat( command.getCommandType() ).isSameAs( TEST_SET_FINISHED ); - assertEquals( Void.class, TEST_SET_FINISHED.getDataType() ); + assertThat(command.getCommandType()).isSameAs(TEST_SET_FINISHED); + assertEquals(Void.class, TEST_SET_FINISHED.getDataType()); byte[] encoded = ":maven-surefire-command:\u0010:testset-finished:".getBytes(); - ByteArrayInputStream is = new ByteArrayInputStream( encoded ); - ForkNodeArguments args = new ForkedNodeArg( 1, false ); - CommandChannelDecoder decoder = new CommandChannelDecoder( newChannel( is ), args ); + ByteArrayInputStream is = new ByteArrayInputStream(encoded); + ForkNodeArguments args = new ForkedNodeArg(1, false); + CommandChannelDecoder decoder = new CommandChannelDecoder(newChannel(is), args); command = decoder.decode(); - assertThat( command.getCommandType() ).isSameAs( TEST_SET_FINISHED ); - assertNull( command.getData() ); + assertThat(command.getCommandType()).isSameAs(TEST_SET_FINISHED); + assertNull(command.getData()); } @Test - public void testDecoderSkipSinceNextTest() throws IOException - { + public void testDecoderSkipSinceNextTest() throws IOException { Command command = Command.SKIP_SINCE_NEXT_TEST; - assertThat( command.getCommandType() ).isSameAs( SKIP_SINCE_NEXT_TEST ); - assertEquals( Void.class, SKIP_SINCE_NEXT_TEST.getDataType() ); + assertThat(command.getCommandType()).isSameAs(SKIP_SINCE_NEXT_TEST); + assertEquals(Void.class, SKIP_SINCE_NEXT_TEST.getDataType()); byte[] encoded = ":maven-surefire-command:\u0014:skip-since-next-test:".getBytes(); - ByteArrayInputStream is = new ByteArrayInputStream( encoded ); - ForkNodeArguments args = new ForkedNodeArg( 1, false ); - CommandChannelDecoder decoder = new CommandChannelDecoder( newChannel( is ), args ); + ByteArrayInputStream is = new ByteArrayInputStream(encoded); + ForkNodeArguments args = new ForkedNodeArg(1, false); + CommandChannelDecoder decoder = new CommandChannelDecoder(newChannel(is), args); command = decoder.decode(); - assertThat( command.getCommandType() ).isSameAs( SKIP_SINCE_NEXT_TEST ); - assertNull( command.getData() ); + assertThat(command.getCommandType()).isSameAs(SKIP_SINCE_NEXT_TEST); + assertNull(command.getData()); } @Test - public void testDecoderShutdownWithExit() throws IOException - { + public void testDecoderShutdownWithExit() throws IOException { Shutdown shutdownType = EXIT; - assertEquals( String.class, SHUTDOWN.getDataType() ); - byte[] encoded = ( ":maven-surefire-command:\u0008:shutdown:\u0005:UTF-8:\u0000\u0000\u0000\u0004:" - + shutdownType.getParam() + ":" ).getBytes(); - ByteArrayInputStream is = new ByteArrayInputStream( encoded ); - ForkNodeArguments args = new ForkedNodeArg( 1, false ); - CommandChannelDecoder decoder = new CommandChannelDecoder( newChannel( is ), args ); + assertEquals(String.class, SHUTDOWN.getDataType()); + byte[] encoded = (":maven-surefire-command:\u0008:shutdown:\u0005:UTF-8:\u0000\u0000\u0000\u0004:" + + shutdownType.getParam() + ":") + .getBytes(); + ByteArrayInputStream is = new ByteArrayInputStream(encoded); + ForkNodeArguments args = new ForkedNodeArg(1, false); + CommandChannelDecoder decoder = new CommandChannelDecoder(newChannel(is), args); Command command = decoder.decode(); - assertThat( command.getCommandType() ).isSameAs( SHUTDOWN ); - assertThat( command.getData() ).isEqualTo( shutdownType.name() ); + assertThat(command.getCommandType()).isSameAs(SHUTDOWN); + assertThat(command.getData()).isEqualTo(shutdownType.name()); } @Test - public void testDecoderShutdownWithKill() throws IOException - { + public void testDecoderShutdownWithKill() throws IOException { Shutdown shutdownType = KILL; - assertEquals( String.class, SHUTDOWN.getDataType() ); - byte[] encoded = ( ":maven-surefire-command:\u0008:shutdown:\u0005:UTF-8:\u0000\u0000\u0000\u0004:" - + shutdownType.getParam() + ":" ).getBytes(); - ByteArrayInputStream is = new ByteArrayInputStream( encoded ); - ForkNodeArguments args = new ForkedNodeArg( 1, false ); - CommandChannelDecoder decoder = new CommandChannelDecoder( newChannel( is ), args ); + assertEquals(String.class, SHUTDOWN.getDataType()); + byte[] encoded = (":maven-surefire-command:\u0008:shutdown:\u0005:UTF-8:\u0000\u0000\u0000\u0004:" + + shutdownType.getParam() + ":") + .getBytes(); + ByteArrayInputStream is = new ByteArrayInputStream(encoded); + ForkNodeArguments args = new ForkedNodeArg(1, false); + CommandChannelDecoder decoder = new CommandChannelDecoder(newChannel(is), args); Command command = decoder.decode(); - assertThat( command.getCommandType() ).isSameAs( SHUTDOWN ); - assertThat( command.getData() ).isEqualTo( shutdownType.name() ); + assertThat(command.getCommandType()).isSameAs(SHUTDOWN); + assertThat(command.getData()).isEqualTo(shutdownType.name()); } @Test - public void testDecoderShutdownWithDefault() throws IOException - { + public void testDecoderShutdownWithDefault() throws IOException { Shutdown shutdownType = DEFAULT; - assertEquals( String.class, SHUTDOWN.getDataType() ); - byte[] encoded = ( ":maven-surefire-command:\u0008:shutdown:\u0005:UTF-8:\u0000\u0000\u0000\u0007:" - + shutdownType.getParam() + ":" ).getBytes(); - ByteArrayInputStream is = new ByteArrayInputStream( encoded ); - ForkNodeArguments args = new ForkedNodeArg( 1, false ); - CommandChannelDecoder decoder = new CommandChannelDecoder( newChannel( is ), args ); + assertEquals(String.class, SHUTDOWN.getDataType()); + byte[] encoded = (":maven-surefire-command:\u0008:shutdown:\u0005:UTF-8:\u0000\u0000\u0000\u0007:" + + shutdownType.getParam() + ":") + .getBytes(); + ByteArrayInputStream is = new ByteArrayInputStream(encoded); + ForkNodeArguments args = new ForkedNodeArg(1, false); + CommandChannelDecoder decoder = new CommandChannelDecoder(newChannel(is), args); Command command = decoder.decode(); - assertThat( command.getCommandType() ).isSameAs( SHUTDOWN ); - assertThat( command.getData() ).isEqualTo( shutdownType.name() ); + assertThat(command.getCommandType()).isSameAs(SHUTDOWN); + assertThat(command.getData()).isEqualTo(shutdownType.name()); } @Test - public void testDecoderNoop() throws IOException - { - assertThat( NOOP ).isSameAs( Command.NOOP.getCommandType() ); - assertEquals( Void.class, NOOP.getDataType() ); + public void testDecoderNoop() throws IOException { + assertThat(NOOP).isSameAs(Command.NOOP.getCommandType()); + assertEquals(Void.class, NOOP.getDataType()); byte[] encoded = ":maven-surefire-command:\u0004:noop:".getBytes(); - ByteArrayInputStream is = new ByteArrayInputStream( encoded ); - ForkNodeArguments args = new ForkedNodeArg( 1, false ); - CommandChannelDecoder decoder = new CommandChannelDecoder( newChannel( is ), args ); + ByteArrayInputStream is = new ByteArrayInputStream(encoded); + ForkNodeArguments args = new ForkedNodeArg(1, false); + CommandChannelDecoder decoder = new CommandChannelDecoder(newChannel(is), args); Command command = decoder.decode(); - assertThat( command.getCommandType() ).isSameAs( NOOP ); - assertNull( command.getData() ); + assertThat(command.getCommandType()).isSameAs(NOOP); + assertNull(command.getData()); } @Test - public void shouldIgnoreDamagedStream() throws IOException - { - assertThat( BYE_ACK ).isSameAs( Command.BYE_ACK.getCommandType() ); - assertEquals( Void.class, BYE_ACK.getDataType() ); + public void shouldIgnoreDamagedStream() throws IOException { + assertThat(BYE_ACK).isSameAs(Command.BYE_ACK.getCommandType()); + assertEquals(Void.class, BYE_ACK.getDataType()); byte[] encoded = ":maven-surefire-command:\u0007:bye-ack:".getBytes(); - byte[] streamContent = ( "" + new String( encoded ) + "" ).getBytes(); - ByteArrayInputStream is = new ByteArrayInputStream( streamContent ); - ForkNodeArguments args = new ForkedNodeArg( 1, false ); - CommandChannelDecoder decoder = new CommandChannelDecoder( newChannel( is ), args ); + byte[] streamContent = ("" + new String(encoded) + "").getBytes(); + ByteArrayInputStream is = new ByteArrayInputStream(streamContent); + ForkNodeArguments args = new ForkedNodeArg(1, false); + CommandChannelDecoder decoder = new CommandChannelDecoder(newChannel(is), args); Command command = decoder.decode(); - assertThat( command.getCommandType() ).isSameAs( BYE_ACK ); - assertNull( command.getData() ); + assertThat(command.getCommandType()).isSameAs(BYE_ACK); + assertNull(command.getData()); } @Test - public void shouldIgnoreDamagedHeader() throws IOException - { - assertThat( BYE_ACK ).isSameAs( Command.BYE_ACK.getCommandType() ); - assertEquals( Void.class, BYE_ACK.getDataType() ); + public void shouldIgnoreDamagedHeader() throws IOException { + assertThat(BYE_ACK).isSameAs(Command.BYE_ACK.getCommandType()); + assertEquals(Void.class, BYE_ACK.getDataType()); byte[] encoded = ":maven-surefire-command:\u0007:bye-ack:".getBytes(); - byte[] streamContent = ( "::" + new String( encoded ) ).getBytes(); - ByteArrayInputStream is = new ByteArrayInputStream( streamContent ); - ForkNodeArguments args = new ForkedNodeArg( 1, false ); - CommandChannelDecoder decoder = new CommandChannelDecoder( newChannel( is ), args ); + byte[] streamContent = ("::" + new String(encoded)).getBytes(); + ByteArrayInputStream is = new ByteArrayInputStream(streamContent); + ForkNodeArguments args = new ForkedNodeArg(1, false); + CommandChannelDecoder decoder = new CommandChannelDecoder(newChannel(is), args); Command command = decoder.decode(); - assertThat( command.getCommandType() ).isSameAs( BYE_ACK ); - assertNull( command.getData() ); + assertThat(command.getCommandType()).isSameAs(BYE_ACK); + assertNull(command.getData()); } @Test - public void testDecoderByeAck() throws IOException - { - assertThat( BYE_ACK ).isSameAs( Command.BYE_ACK.getCommandType() ); - assertEquals( Void.class, BYE_ACK.getDataType() ); + public void testDecoderByeAck() throws IOException { + assertThat(BYE_ACK).isSameAs(Command.BYE_ACK.getCommandType()); + assertEquals(Void.class, BYE_ACK.getDataType()); byte[] encoded = ":maven-surefire-command:\u0007:bye-ack:".getBytes(); - ByteArrayInputStream is = new ByteArrayInputStream( encoded ); - ForkNodeArguments args = new ForkedNodeArg( 1, false ); - CommandChannelDecoder decoder = new CommandChannelDecoder( newChannel( is ), args ); + ByteArrayInputStream is = new ByteArrayInputStream(encoded); + ForkNodeArguments args = new ForkedNodeArg(1, false); + CommandChannelDecoder decoder = new CommandChannelDecoder(newChannel(is), args); Command command = decoder.decode(); - assertThat( command.getCommandType() ).isSameAs( BYE_ACK ); - assertNull( command.getData() ); + assertThat(command.getCommandType()).isSameAs(BYE_ACK); + assertNull(command.getData()); } @Test - public void shouldDecodeTwoCommands() throws IOException - { + public void shouldDecodeTwoCommands() throws IOException { String cmd = ":maven-surefire-command:\u0007:bye-ack:\r\n:maven-surefire-command:\u0007:bye-ack:"; - InputStream is = new ByteArrayInputStream( cmd.getBytes() ); - ForkNodeArguments args = new ForkedNodeArg( 1, false ); - CommandChannelDecoder decoder = new CommandChannelDecoder( newChannel( is ), args ); + InputStream is = new ByteArrayInputStream(cmd.getBytes()); + ForkNodeArguments args = new ForkedNodeArg(1, false); + CommandChannelDecoder decoder = new CommandChannelDecoder(newChannel(is), args); Command command = decoder.decode(); - assertThat( command.getCommandType() ).isEqualTo( BYE_ACK ); - assertThat( command.getData() ).isNull(); + assertThat(command.getCommandType()).isEqualTo(BYE_ACK); + assertThat(command.getData()).isNull(); command = decoder.decode(); - assertThat( command.getCommandType() ).isEqualTo( BYE_ACK ); - assertThat( command.getData() ).isNull(); + assertThat(command.getCommandType()).isEqualTo(BYE_ACK); + assertThat(command.getData()).isNull(); decoder.close(); } - @Test( expected = EOFException.class ) - public void testIncompleteCommand() throws IOException - { + @Test(expected = EOFException.class) + public void testIncompleteCommand() throws IOException { - ByteArrayInputStream is = new ByteArrayInputStream( ":maven-surefire-command:".getBytes() ); - ForkNodeArguments args = new ForkedNodeArg( 1, false ); - CommandChannelDecoder decoder = new CommandChannelDecoder( newChannel( is ), args ); + ByteArrayInputStream is = new ByteArrayInputStream(":maven-surefire-command:".getBytes()); + ForkNodeArguments args = new ForkedNodeArg(1, false); + CommandChannelDecoder decoder = new CommandChannelDecoder(newChannel(is), args); decoder.decode(); fail(); } - @Test( expected = EOFException.class ) - public void testIncompleteCommandStart() throws IOException - { + @Test(expected = EOFException.class) + public void testIncompleteCommandStart() throws IOException { - ByteArrayInputStream is = new ByteArrayInputStream( new byte[] {':', '\r'} ); - ForkNodeArguments args = new ForkedNodeArg( 1, false ); - CommandChannelDecoder decoder = new CommandChannelDecoder( newChannel( is ), args ); + ByteArrayInputStream is = new ByteArrayInputStream(new byte[] {':', '\r'}); + ForkNodeArguments args = new ForkedNodeArg(1, false); + CommandChannelDecoder decoder = new CommandChannelDecoder(newChannel(is), args); decoder.decode(); fail(); } - @Test( expected = EOFException.class ) - public void shouldNotDecodeCorruptedCommand() throws IOException - { + @Test(expected = EOFException.class) + public void shouldNotDecodeCorruptedCommand() throws IOException { String cmd = ":maven-surefire-command:\u0007:bye-ack ::maven-surefire-command:"; - InputStream is = new ByteArrayInputStream( cmd.getBytes() ); - ForkNodeArguments args = new ForkedNodeArg( 1, false ); - CommandChannelDecoder decoder = new CommandChannelDecoder( newChannel( is ), args ); + InputStream is = new ByteArrayInputStream(cmd.getBytes()); + ForkNodeArguments args = new ForkedNodeArg(1, false); + CommandChannelDecoder decoder = new CommandChannelDecoder(newChannel(is), args); decoder.decode(); } @Test - public void shouldSkipCorruptedCommand() throws IOException - { + public void shouldSkipCorruptedCommand() throws IOException { String cmd = ":maven-surefire-command:\0007:bye-ack\r\n::maven-surefire-command:\u0004:noop:"; - InputStream is = new ByteArrayInputStream( cmd.getBytes() ); - ForkNodeArguments args = new ForkedNodeArg( 1, false ); - CommandChannelDecoder decoder = new CommandChannelDecoder( newChannel( is ), args ); + InputStream is = new ByteArrayInputStream(cmd.getBytes()); + ForkNodeArguments args = new ForkedNodeArg(1, false); + CommandChannelDecoder decoder = new CommandChannelDecoder(newChannel(is), args); Command command = decoder.decode(); - assertThat( command.getCommandType() ).isSameAs( NOOP ); - assertNull( command.getData() ); + assertThat(command.getCommandType()).isSameAs(NOOP); + assertNull(command.getData()); } @Test - public void testBinaryCommandStream() throws Exception - { - InputStream commands = getClass().getResourceAsStream( "/binary-commands/75171711-encoder.bin" ); - assertThat( commands ).isNotNull(); - ConsoleLoggerMock logger = new ConsoleLoggerMock( true, true, true, true ); - ForkNodeArguments args = new ForkNodeArgumentsMock( logger, new File( "" ) ); - CommandChannelDecoder decoder = new CommandChannelDecoder( newChannel( commands ), args ); + public void testBinaryCommandStream() throws Exception { + InputStream commands = getClass().getResourceAsStream("/binary-commands/75171711-encoder.bin"); + assertThat(commands).isNotNull(); + ConsoleLoggerMock logger = new ConsoleLoggerMock(true, true, true, true); + ForkNodeArguments args = new ForkNodeArgumentsMock(logger, new File("")); + CommandChannelDecoder decoder = new CommandChannelDecoder(newChannel(commands), args); Command command = decoder.decode(); - assertThat( command ).isNotNull(); - assertThat( command.getCommandType() ).isEqualTo( NOOP ); - assertThat( command.getData() ).isNull(); + assertThat(command).isNotNull(); + assertThat(command.getCommandType()).isEqualTo(NOOP); + assertThat(command.getData()).isNull(); command = decoder.decode(); - assertThat( command ).isNotNull(); - assertThat( command.getCommandType() ).isEqualTo( RUN_CLASS ); - assertThat( command.getData() ).isEqualTo( "pkg.ATest" ); + assertThat(command).isNotNull(); + assertThat(command.getCommandType()).isEqualTo(RUN_CLASS); + assertThat(command.getData()).isEqualTo("pkg.ATest"); - for ( int i = 0; i < 24; i++ ) - { + for (int i = 0; i < 24; i++) { command = decoder.decode(); - assertThat( command ).isNotNull(); - assertThat( command.getCommandType() ).isEqualTo( NOOP ); - assertThat( command.getData() ).isNull(); + assertThat(command).isNotNull(); + assertThat(command.getCommandType()).isEqualTo(NOOP); + assertThat(command.getData()).isNull(); } } /** * Threadsafe impl. Mockito and Powermock are not thread-safe. */ - private static class ForkNodeArgumentsMock implements ForkNodeArguments - { + private static class ForkNodeArgumentsMock implements ForkNodeArguments { private final ConcurrentLinkedQueue dumpStreamText = new ConcurrentLinkedQueue<>(); private final ConcurrentLinkedQueue logWarningAtEnd = new ConcurrentLinkedQueue<>(); private final ConsoleLogger logger; private final File dumpStreamTextFile; - ForkNodeArgumentsMock( ConsoleLogger logger, File dumpStreamTextFile ) - { + ForkNodeArgumentsMock(ConsoleLogger logger, File dumpStreamTextFile) { this.logger = logger; this.dumpStreamTextFile = dumpStreamTextFile; } @Nonnull @Override - public String getSessionId() - { + public String getSessionId() { throw new UnsupportedOperationException(); } @Override - public int getForkChannelId() - { + public int getForkChannelId() { return 0; } @Nonnull @Override - public File dumpStreamText( @Nonnull String text ) - { - dumpStreamText.add( text ); + public File dumpStreamText(@Nonnull String text) { + dumpStreamText.add(text); return dumpStreamTextFile; } @Nonnull @Override - public File dumpStreamException( @Nonnull Throwable t ) - { + public File dumpStreamException(@Nonnull Throwable t) { throw new UnsupportedOperationException(); } @Override - public void logWarningAtEnd( @Nonnull String text ) - { - logWarningAtEnd.add( text ); + public void logWarningAtEnd(@Nonnull String text) { + logWarningAtEnd.add(text); } @Nonnull @Override - public ConsoleLogger getConsoleLogger() - { + public ConsoleLogger getConsoleLogger() { return logger; } @Nonnull @Override - public Object getConsoleLock() - { + public Object getConsoleLock() { return logger; } - boolean isCalled() - { + boolean isCalled() { return !dumpStreamText.isEmpty() || !logWarningAtEnd.isEmpty(); } @Override - public File getEventStreamBinaryFile() - { + public File getEventStreamBinaryFile() { return null; } @Override - public File getCommandStreamBinaryFile() - { + public File getCommandStreamBinaryFile() { return null; } } @@ -419,8 +390,7 @@ public File getCommandStreamBinaryFile() /** * Threadsafe impl. Mockito and Powermock are not thread-safe. */ - private static class ConsoleLoggerMock implements ConsoleLogger - { + private static class ConsoleLoggerMock implements ConsoleLogger { final ConcurrentLinkedQueue debug = new ConcurrentLinkedQueue<>(); final ConcurrentLinkedQueue info = new ConcurrentLinkedQueue<>(); final ConcurrentLinkedQueue error = new ConcurrentLinkedQueue<>(); @@ -432,8 +402,7 @@ private static class ConsoleLoggerMock implements ConsoleLogger private volatile boolean isDebugEnabledCalled; private volatile boolean isInfoEnabledCalled; - ConsoleLoggerMock( boolean isDebug, boolean isInfo, boolean isWarning, boolean isError ) - { + ConsoleLoggerMock(boolean isDebug, boolean isInfo, boolean isWarning, boolean isError) { this.isDebug = isDebug; this.isInfo = isInfo; this.isWarning = isWarning; @@ -441,76 +410,65 @@ private static class ConsoleLoggerMock implements ConsoleLogger } @Override - public synchronized boolean isDebugEnabled() - { + public synchronized boolean isDebugEnabled() { isDebugEnabledCalled = true; called = true; return isDebug; } @Override - public synchronized void debug( String message ) - { - debug.add( message ); + public synchronized void debug(String message) { + debug.add(message); called = true; } @Override - public synchronized boolean isInfoEnabled() - { + public synchronized boolean isInfoEnabled() { isInfoEnabledCalled = true; called = true; return isInfo; } @Override - public synchronized void info( String message ) - { - info.add( message ); + public synchronized void info(String message) { + info.add(message); called = true; } @Override - public synchronized boolean isWarnEnabled() - { + public synchronized boolean isWarnEnabled() { called = true; return isWarning; } @Override - public synchronized void warning( String message ) - { + public synchronized void warning(String message) { called = true; } @Override - public synchronized boolean isErrorEnabled() - { + public synchronized boolean isErrorEnabled() { called = true; return isError; } @Override - public synchronized void error( String message ) - { - error.add( message ); + public synchronized void error(String message) { + error.add(message); called = true; } @Override - public synchronized void error( String message, Throwable t ) - { + public synchronized void error(String message, Throwable t) { called = true; } @Override - public synchronized void error( Throwable t ) - { + public synchronized void error(Throwable t) { called = true; } - synchronized boolean isCalled() - { + synchronized boolean isCalled() { return called; } } diff --git a/surefire-booter/src/test/java/org/apache/maven/surefire/booter/spi/EventChannelEncoderTest.java b/surefire-booter/src/test/java/org/apache/maven/surefire/booter/spi/EventChannelEncoderTest.java index 9541448936..af15e68ff2 100644 --- a/surefire-booter/src/test/java/org/apache/maven/surefire/booter/spi/EventChannelEncoderTest.java +++ b/surefire-booter/src/test/java/org/apache/maven/surefire/booter/spi/EventChannelEncoderTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.booter.spi; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,15 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.booter.spi; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.PrintStream; +import java.nio.Buffer; +import java.nio.ByteBuffer; +import java.util.Map; +import java.util.Map.Entry; import org.apache.maven.plugin.surefire.log.api.ConsoleLoggerUtils; import org.apache.maven.surefire.api.report.ReportEntry; @@ -29,14 +36,6 @@ import org.apache.maven.surefire.api.util.internal.WritableBufferedByteChannel; import org.junit.Test; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.PrintStream; -import java.nio.Buffer; -import java.nio.ByteBuffer; -import java.util.Map; -import java.util.Map.Entry; - import static java.nio.charset.StandardCharsets.UTF_8; import static java.util.Arrays.copyOfRange; import static org.apache.maven.surefire.api.booter.ForkedProcessEventType.BOOTERCODE_TEST_ERROR; @@ -57,1181 +56,1139 @@ * @author Tibor Digana (tibor17) * @since 3.0.0-M4 */ -@SuppressWarnings( { "checkstyle:linelength", "checkstyle:magicnumber" } ) -public class EventChannelEncoderTest -{ +@SuppressWarnings({"checkstyle:linelength", "checkstyle:magicnumber"}) +public class EventChannelEncoderTest { private static final int ELAPSED_TIME = 102; private static final byte[] ELAPSED_TIME_HEXA = new byte[] {0, 0, 0, 0x66}; @Test - public void reportEntry() throws IOException - { + public void reportEntry() throws IOException { final String exceptionMessage = "msg"; final String smartStackTrace = "MyTest:86 >> Error"; final String stackTrace = "trace line 1\ntrace line 2"; final String trimmedStackTrace = "trace line 1\ntrace line 2"; - SafeThrowable safeThrowable = new SafeThrowable( new Exception( exceptionMessage ) ); - StackTraceWriter stackTraceWriter = mock( StackTraceWriter.class ); - when( stackTraceWriter.getThrowable() ).thenReturn( safeThrowable ); - when( stackTraceWriter.smartTrimmedStackTrace() ).thenReturn( smartStackTrace ); - when( stackTraceWriter.writeTrimmedTraceToString() ).thenReturn( trimmedStackTrace ); - when( stackTraceWriter.writeTraceToString() ).thenReturn( stackTrace ); - - TestSetReportEntry reportEntry = mock( TestSetReportEntry.class ); - when( reportEntry.getRunMode() ).thenReturn( NORMAL_RUN ); - when( reportEntry.getTestRunId() ).thenReturn( 1L ); - when( reportEntry.getElapsed() ).thenReturn( ELAPSED_TIME ); - when( reportEntry.getGroup() ).thenReturn( "this group" ); - when( reportEntry.getMessage() ).thenReturn( "skipped test" ); - when( reportEntry.getName() ).thenReturn( "my test" ); - when( reportEntry.getNameWithGroup() ).thenReturn( "name with group" ); - when( reportEntry.getSourceName() ).thenReturn( "pkg.MyTest" ); - when( reportEntry.getStackTraceWriter() ).thenReturn( stackTraceWriter ); + SafeThrowable safeThrowable = new SafeThrowable(new Exception(exceptionMessage)); + StackTraceWriter stackTraceWriter = mock(StackTraceWriter.class); + when(stackTraceWriter.getThrowable()).thenReturn(safeThrowable); + when(stackTraceWriter.smartTrimmedStackTrace()).thenReturn(smartStackTrace); + when(stackTraceWriter.writeTrimmedTraceToString()).thenReturn(trimmedStackTrace); + when(stackTraceWriter.writeTraceToString()).thenReturn(stackTrace); + + TestSetReportEntry reportEntry = mock(TestSetReportEntry.class); + when(reportEntry.getRunMode()).thenReturn(NORMAL_RUN); + when(reportEntry.getTestRunId()).thenReturn(1L); + when(reportEntry.getElapsed()).thenReturn(ELAPSED_TIME); + when(reportEntry.getGroup()).thenReturn("this group"); + when(reportEntry.getMessage()).thenReturn("skipped test"); + when(reportEntry.getName()).thenReturn("my test"); + when(reportEntry.getNameWithGroup()).thenReturn("name with group"); + when(reportEntry.getSourceName()).thenReturn("pkg.MyTest"); + when(reportEntry.getStackTraceWriter()).thenReturn(stackTraceWriter); Stream out = Stream.newStream(); - EventChannelEncoder encoder = new EventChannelEncoder( newBufferedChannel( out ) ); - ByteBuffer encoded = encoder.encode( BOOTERCODE_TEST_ERROR, reportEntry, false ); + EventChannelEncoder encoder = new EventChannelEncoder(newBufferedChannel(out)); + ByteBuffer encoded = encoder.encode(BOOTERCODE_TEST_ERROR, reportEntry, false); ByteArrayOutputStream expectedFrame = new ByteArrayOutputStream(); - expectedFrame.write( ":maven-surefire-event:".getBytes( UTF_8 ) ); - expectedFrame.write( (byte) 10 ); - expectedFrame.write( ":test-error:".getBytes( UTF_8 ) ); - expectedFrame.write( (byte) 10 ); - expectedFrame.write( ":normal-run:".getBytes( UTF_8 ) ); - expectedFrame.write( "\u0001\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0001".getBytes() ); - expectedFrame.write( ':' ); - expectedFrame.write( (byte) 5 ); - expectedFrame.write( ":UTF-8:".getBytes( UTF_8 ) ); - expectedFrame.write( new byte[] {0, 0, 0, 10} ); - expectedFrame.write( ':' ); - expectedFrame.write( reportEntry.getSourceName().getBytes( UTF_8 ) ); - expectedFrame.write( ':' ); - expectedFrame.write( new byte[] {0, 0, 0, 1} ); - expectedFrame.write( ':' ); - expectedFrame.write( 0 ); - expectedFrame.write( ':' ); - expectedFrame.write( new byte[] {0, 0, 0, 7} ); - expectedFrame.write( ':' ); - expectedFrame.write( reportEntry.getName().getBytes( UTF_8 ) ); - expectedFrame.write( ':' ); - expectedFrame.write( new byte[] {0, 0, 0, 1} ); - expectedFrame.write( ':' ); - expectedFrame.write( 0 ); - expectedFrame.write( ':' ); - expectedFrame.write( new byte[] {0, 0, 0, 10} ); - expectedFrame.write( ':' ); - expectedFrame.write( reportEntry.getGroup().getBytes( UTF_8 ) ); - expectedFrame.write( ':' ); - expectedFrame.write( new byte[] {0, 0, 0, 12} ); - expectedFrame.write( ':' ); - expectedFrame.write( reportEntry.getMessage().getBytes( UTF_8 ) ); - expectedFrame.write( ':' ); - expectedFrame.write( 0xff ); - expectedFrame.write( ELAPSED_TIME_HEXA ); - expectedFrame.write( ':' ); - expectedFrame.write( new byte[] {0, 0, 0, 3} ); - expectedFrame.write( ':' ); - expectedFrame.write( exceptionMessage.getBytes( UTF_8 ) ); - expectedFrame.write( ':' ); - expectedFrame.write( new byte[] {0, 0, 0, 18} ); - expectedFrame.write( ':' ); - expectedFrame.write( reportEntry.getStackTraceWriter().smartTrimmedStackTrace().getBytes( UTF_8 ) ); - expectedFrame.write( ':' ); - expectedFrame.write( new byte[] {0, 0, 0, 25} ); - expectedFrame.write( ':' ); - expectedFrame.write( stackTrace.getBytes( UTF_8 ) ); - expectedFrame.write( ':' ); - ( (Buffer) encoded ).flip(); - - assertThat( toArray( encoded ) ) - .isEqualTo( expectedFrame.toByteArray() ); + expectedFrame.write(":maven-surefire-event:".getBytes(UTF_8)); + expectedFrame.write((byte) 10); + expectedFrame.write(":test-error:".getBytes(UTF_8)); + expectedFrame.write((byte) 10); + expectedFrame.write(":normal-run:".getBytes(UTF_8)); + expectedFrame.write("\u0001\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0001".getBytes()); + expectedFrame.write(':'); + expectedFrame.write((byte) 5); + expectedFrame.write(":UTF-8:".getBytes(UTF_8)); + expectedFrame.write(new byte[] {0, 0, 0, 10}); + expectedFrame.write(':'); + expectedFrame.write(reportEntry.getSourceName().getBytes(UTF_8)); + expectedFrame.write(':'); + expectedFrame.write(new byte[] {0, 0, 0, 1}); + expectedFrame.write(':'); + expectedFrame.write(0); + expectedFrame.write(':'); + expectedFrame.write(new byte[] {0, 0, 0, 7}); + expectedFrame.write(':'); + expectedFrame.write(reportEntry.getName().getBytes(UTF_8)); + expectedFrame.write(':'); + expectedFrame.write(new byte[] {0, 0, 0, 1}); + expectedFrame.write(':'); + expectedFrame.write(0); + expectedFrame.write(':'); + expectedFrame.write(new byte[] {0, 0, 0, 10}); + expectedFrame.write(':'); + expectedFrame.write(reportEntry.getGroup().getBytes(UTF_8)); + expectedFrame.write(':'); + expectedFrame.write(new byte[] {0, 0, 0, 12}); + expectedFrame.write(':'); + expectedFrame.write(reportEntry.getMessage().getBytes(UTF_8)); + expectedFrame.write(':'); + expectedFrame.write(0xff); + expectedFrame.write(ELAPSED_TIME_HEXA); + expectedFrame.write(':'); + expectedFrame.write(new byte[] {0, 0, 0, 3}); + expectedFrame.write(':'); + expectedFrame.write(exceptionMessage.getBytes(UTF_8)); + expectedFrame.write(':'); + expectedFrame.write(new byte[] {0, 0, 0, 18}); + expectedFrame.write(':'); + expectedFrame.write( + reportEntry.getStackTraceWriter().smartTrimmedStackTrace().getBytes(UTF_8)); + expectedFrame.write(':'); + expectedFrame.write(new byte[] {0, 0, 0, 25}); + expectedFrame.write(':'); + expectedFrame.write(stackTrace.getBytes(UTF_8)); + expectedFrame.write(':'); + ((Buffer) encoded).flip(); + + assertThat(toArray(encoded)).isEqualTo(expectedFrame.toByteArray()); out = Stream.newStream(); - encoder = new EventChannelEncoder( newBufferedChannel( out ) ); - encoded = encoder.encode( BOOTERCODE_TEST_ERROR, reportEntry, true ); + encoder = new EventChannelEncoder(newBufferedChannel(out)); + encoded = encoder.encode(BOOTERCODE_TEST_ERROR, reportEntry, true); expectedFrame = new ByteArrayOutputStream(); - expectedFrame.write( ":maven-surefire-event:".getBytes( UTF_8 ) ); - expectedFrame.write( (byte) 10 ); - expectedFrame.write( ":test-error:".getBytes( UTF_8 ) ); - expectedFrame.write( (byte) 10 ); - expectedFrame.write( ":normal-run:".getBytes( UTF_8 ) ); - expectedFrame.write( "\u0001\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0001".getBytes() ); - expectedFrame.write( ':' ); - expectedFrame.write( (byte) 5 ); - expectedFrame.write( ":UTF-8:".getBytes( UTF_8 ) ); - expectedFrame.write( new byte[] {0, 0, 0, 10} ); - expectedFrame.write( ':' ); - expectedFrame.write( reportEntry.getSourceName().getBytes( UTF_8 ) ); - expectedFrame.write( ':' ); - expectedFrame.write( new byte[] {0, 0, 0, 1} ); - expectedFrame.write( ':' ); - expectedFrame.write( 0 ); - expectedFrame.write( ':' ); - expectedFrame.write( new byte[] {0, 0, 0, 7} ); - expectedFrame.write( ':' ); - expectedFrame.write( reportEntry.getName().getBytes( UTF_8 ) ); - expectedFrame.write( ':' ); - expectedFrame.write( new byte[] {0, 0, 0, 1} ); - expectedFrame.write( ':' ); - expectedFrame.write( 0 ); - expectedFrame.write( ':' ); - expectedFrame.write( new byte[] {0, 0, 0, 10} ); - expectedFrame.write( ':' ); - expectedFrame.write( reportEntry.getGroup().getBytes( UTF_8 ) ); - expectedFrame.write( ':' ); - expectedFrame.write( new byte[] {0, 0, 0, 12} ); - expectedFrame.write( ':' ); - expectedFrame.write( reportEntry.getMessage().getBytes( UTF_8 ) ); - expectedFrame.write( ':' ); - expectedFrame.write( 0xff ); - expectedFrame.write( ELAPSED_TIME_HEXA ); - expectedFrame.write( ':' ); - expectedFrame.write( new byte[] {0, 0, 0, 3} ); - expectedFrame.write( ':' ); - expectedFrame.write( exceptionMessage.getBytes( UTF_8 ) ); - expectedFrame.write( ':' ); - expectedFrame.write( new byte[] {0, 0, 0, 18} ); - expectedFrame.write( ':' ); - expectedFrame.write( reportEntry.getStackTraceWriter().smartTrimmedStackTrace().getBytes( UTF_8 ) ); - expectedFrame.write( ':' ); - expectedFrame.write( new byte[] {0, 0, 0, 25} ); - expectedFrame.write( ':' ); - expectedFrame.write( trimmedStackTrace.getBytes( UTF_8 ) ); - expectedFrame.write( ':' ); - ( (Buffer) encoded ).flip(); - - assertThat( toArray( encoded ) ) - .isEqualTo( expectedFrame.toByteArray() ); + expectedFrame.write(":maven-surefire-event:".getBytes(UTF_8)); + expectedFrame.write((byte) 10); + expectedFrame.write(":test-error:".getBytes(UTF_8)); + expectedFrame.write((byte) 10); + expectedFrame.write(":normal-run:".getBytes(UTF_8)); + expectedFrame.write("\u0001\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0001".getBytes()); + expectedFrame.write(':'); + expectedFrame.write((byte) 5); + expectedFrame.write(":UTF-8:".getBytes(UTF_8)); + expectedFrame.write(new byte[] {0, 0, 0, 10}); + expectedFrame.write(':'); + expectedFrame.write(reportEntry.getSourceName().getBytes(UTF_8)); + expectedFrame.write(':'); + expectedFrame.write(new byte[] {0, 0, 0, 1}); + expectedFrame.write(':'); + expectedFrame.write(0); + expectedFrame.write(':'); + expectedFrame.write(new byte[] {0, 0, 0, 7}); + expectedFrame.write(':'); + expectedFrame.write(reportEntry.getName().getBytes(UTF_8)); + expectedFrame.write(':'); + expectedFrame.write(new byte[] {0, 0, 0, 1}); + expectedFrame.write(':'); + expectedFrame.write(0); + expectedFrame.write(':'); + expectedFrame.write(new byte[] {0, 0, 0, 10}); + expectedFrame.write(':'); + expectedFrame.write(reportEntry.getGroup().getBytes(UTF_8)); + expectedFrame.write(':'); + expectedFrame.write(new byte[] {0, 0, 0, 12}); + expectedFrame.write(':'); + expectedFrame.write(reportEntry.getMessage().getBytes(UTF_8)); + expectedFrame.write(':'); + expectedFrame.write(0xff); + expectedFrame.write(ELAPSED_TIME_HEXA); + expectedFrame.write(':'); + expectedFrame.write(new byte[] {0, 0, 0, 3}); + expectedFrame.write(':'); + expectedFrame.write(exceptionMessage.getBytes(UTF_8)); + expectedFrame.write(':'); + expectedFrame.write(new byte[] {0, 0, 0, 18}); + expectedFrame.write(':'); + expectedFrame.write( + reportEntry.getStackTraceWriter().smartTrimmedStackTrace().getBytes(UTF_8)); + expectedFrame.write(':'); + expectedFrame.write(new byte[] {0, 0, 0, 25}); + expectedFrame.write(':'); + expectedFrame.write(trimmedStackTrace.getBytes(UTF_8)); + expectedFrame.write(':'); + ((Buffer) encoded).flip(); + + assertThat(toArray(encoded)).isEqualTo(expectedFrame.toByteArray()); out = Stream.newStream(); - encoder = new EventChannelEncoder( newBufferedChannel( out ) ); - encoder.testSetStarting( reportEntry, true ); + encoder = new EventChannelEncoder(newBufferedChannel(out)); + encoder.testSetStarting(reportEntry, true); expectedFrame = new ByteArrayOutputStream(); - expectedFrame.write( ":maven-surefire-event:".getBytes( UTF_8 ) ); - expectedFrame.write( (byte) 16 ); - expectedFrame.write( ":testset-starting:".getBytes( UTF_8 ) ); - expectedFrame.write( (byte) 10 ); - expectedFrame.write( ":normal-run:".getBytes( UTF_8 ) ); - expectedFrame.write( "\u0001\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0001".getBytes() ); - expectedFrame.write( ':' ); - expectedFrame.write( (byte) 5 ); - expectedFrame.write( ":UTF-8:".getBytes( UTF_8 ) ); - expectedFrame.write( new byte[] {0, 0, 0, 10} ); - expectedFrame.write( ':' ); - expectedFrame.write( reportEntry.getSourceName().getBytes( UTF_8 ) ); - expectedFrame.write( ':' ); - expectedFrame.write( new byte[] {0, 0, 0, 1} ); - expectedFrame.write( ':' ); - expectedFrame.write( 0 ); - expectedFrame.write( ':' ); - expectedFrame.write( new byte[] {0, 0, 0, 7} ); - expectedFrame.write( ':' ); - expectedFrame.write( reportEntry.getName().getBytes( UTF_8 ) ); - expectedFrame.write( ':' ); - expectedFrame.write( new byte[] {0, 0, 0, 1} ); - expectedFrame.write( ':' ); - expectedFrame.write( 0 ); - expectedFrame.write( ':' ); - expectedFrame.write( new byte[] {0, 0, 0, 10} ); - expectedFrame.write( ':' ); - expectedFrame.write( reportEntry.getGroup().getBytes( UTF_8 ) ); - expectedFrame.write( ':' ); - expectedFrame.write( new byte[] {0, 0, 0, 12} ); - expectedFrame.write( ':' ); - expectedFrame.write( reportEntry.getMessage().getBytes( UTF_8 ) ); - expectedFrame.write( ':' ); - expectedFrame.write( 0xff ); - expectedFrame.write( ELAPSED_TIME_HEXA ); - expectedFrame.write( ':' ); - expectedFrame.write( new byte[] {0, 0, 0, 3} ); - expectedFrame.write( ':' ); - expectedFrame.write( exceptionMessage.getBytes( UTF_8 ) ); - expectedFrame.write( ':' ); - expectedFrame.write( new byte[] {0, 0, 0, 18} ); - expectedFrame.write( ':' ); - expectedFrame.write( reportEntry.getStackTraceWriter().smartTrimmedStackTrace().getBytes( UTF_8 ) ); - expectedFrame.write( ':' ); - expectedFrame.write( new byte[] {0, 0, 0, 25} ); - expectedFrame.write( ':' ); - expectedFrame.write( trimmedStackTrace.getBytes( UTF_8 ) ); - expectedFrame.write( ':' ); - assertThat( out.toByteArray() ) - .isEqualTo( expectedFrame.toByteArray() ); + expectedFrame.write(":maven-surefire-event:".getBytes(UTF_8)); + expectedFrame.write((byte) 16); + expectedFrame.write(":testset-starting:".getBytes(UTF_8)); + expectedFrame.write((byte) 10); + expectedFrame.write(":normal-run:".getBytes(UTF_8)); + expectedFrame.write("\u0001\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0001".getBytes()); + expectedFrame.write(':'); + expectedFrame.write((byte) 5); + expectedFrame.write(":UTF-8:".getBytes(UTF_8)); + expectedFrame.write(new byte[] {0, 0, 0, 10}); + expectedFrame.write(':'); + expectedFrame.write(reportEntry.getSourceName().getBytes(UTF_8)); + expectedFrame.write(':'); + expectedFrame.write(new byte[] {0, 0, 0, 1}); + expectedFrame.write(':'); + expectedFrame.write(0); + expectedFrame.write(':'); + expectedFrame.write(new byte[] {0, 0, 0, 7}); + expectedFrame.write(':'); + expectedFrame.write(reportEntry.getName().getBytes(UTF_8)); + expectedFrame.write(':'); + expectedFrame.write(new byte[] {0, 0, 0, 1}); + expectedFrame.write(':'); + expectedFrame.write(0); + expectedFrame.write(':'); + expectedFrame.write(new byte[] {0, 0, 0, 10}); + expectedFrame.write(':'); + expectedFrame.write(reportEntry.getGroup().getBytes(UTF_8)); + expectedFrame.write(':'); + expectedFrame.write(new byte[] {0, 0, 0, 12}); + expectedFrame.write(':'); + expectedFrame.write(reportEntry.getMessage().getBytes(UTF_8)); + expectedFrame.write(':'); + expectedFrame.write(0xff); + expectedFrame.write(ELAPSED_TIME_HEXA); + expectedFrame.write(':'); + expectedFrame.write(new byte[] {0, 0, 0, 3}); + expectedFrame.write(':'); + expectedFrame.write(exceptionMessage.getBytes(UTF_8)); + expectedFrame.write(':'); + expectedFrame.write(new byte[] {0, 0, 0, 18}); + expectedFrame.write(':'); + expectedFrame.write( + reportEntry.getStackTraceWriter().smartTrimmedStackTrace().getBytes(UTF_8)); + expectedFrame.write(':'); + expectedFrame.write(new byte[] {0, 0, 0, 25}); + expectedFrame.write(':'); + expectedFrame.write(trimmedStackTrace.getBytes(UTF_8)); + expectedFrame.write(':'); + assertThat(out.toByteArray()).isEqualTo(expectedFrame.toByteArray()); out = Stream.newStream(); - encoder = new EventChannelEncoder( newBufferedChannel( out ) ); + encoder = new EventChannelEncoder(newBufferedChannel(out)); - encoder.testSetStarting( reportEntry, false ); + encoder.testSetStarting(reportEntry, false); expectedFrame = new ByteArrayOutputStream(); - expectedFrame.write( ":maven-surefire-event:".getBytes( UTF_8 ) ); - expectedFrame.write( (byte) 16 ); - expectedFrame.write( ":testset-starting:".getBytes( UTF_8 ) ); - expectedFrame.write( (byte) 10 ); - expectedFrame.write( ":normal-run:".getBytes( UTF_8 ) ); - expectedFrame.write( "\u0001\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0001".getBytes() ); - expectedFrame.write( ':' ); - expectedFrame.write( (byte) 5 ); - expectedFrame.write( ":UTF-8:".getBytes( UTF_8 ) ); - expectedFrame.write( new byte[] {0, 0, 0, 10} ); - expectedFrame.write( ':' ); - expectedFrame.write( reportEntry.getSourceName().getBytes( UTF_8 ) ); - expectedFrame.write( ':' ); - expectedFrame.write( new byte[] {0, 0, 0, 1} ); - expectedFrame.write( ':' ); - expectedFrame.write( 0 ); - expectedFrame.write( ':' ); - expectedFrame.write( new byte[] {0, 0, 0, 7} ); - expectedFrame.write( ':' ); - expectedFrame.write( reportEntry.getName().getBytes( UTF_8 ) ); - expectedFrame.write( ':' ); - expectedFrame.write( new byte[] {0, 0, 0, 1} ); - expectedFrame.write( ':' ); - expectedFrame.write( 0 ); - expectedFrame.write( ':' ); - expectedFrame.write( new byte[] {0, 0, 0, 10} ); - expectedFrame.write( ':' ); - expectedFrame.write( reportEntry.getGroup().getBytes( UTF_8 ) ); - expectedFrame.write( ':' ); - expectedFrame.write( new byte[] {0, 0, 0, 12} ); - expectedFrame.write( ':' ); - expectedFrame.write( reportEntry.getMessage().getBytes( UTF_8 ) ); - expectedFrame.write( ':' ); - expectedFrame.write( 0xff ); - expectedFrame.write( ELAPSED_TIME_HEXA ); - expectedFrame.write( ':' ); - expectedFrame.write( new byte[] {0, 0, 0, 3} ); - expectedFrame.write( ':' ); - expectedFrame.write( exceptionMessage.getBytes( UTF_8 ) ); - expectedFrame.write( ':' ); - expectedFrame.write( new byte[] {0, 0, 0, 18} ); - expectedFrame.write( ':' ); - expectedFrame.write( reportEntry.getStackTraceWriter().smartTrimmedStackTrace().getBytes( UTF_8 ) ); - expectedFrame.write( ':' ); - expectedFrame.write( new byte[] {0, 0, 0, 25} ); - expectedFrame.write( ':' ); - expectedFrame.write( stackTrace.getBytes( UTF_8 ) ); - expectedFrame.write( ':' ); - assertThat( out.toByteArray() ) - .isEqualTo( expectedFrame.toByteArray() ); + expectedFrame.write(":maven-surefire-event:".getBytes(UTF_8)); + expectedFrame.write((byte) 16); + expectedFrame.write(":testset-starting:".getBytes(UTF_8)); + expectedFrame.write((byte) 10); + expectedFrame.write(":normal-run:".getBytes(UTF_8)); + expectedFrame.write("\u0001\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0001".getBytes()); + expectedFrame.write(':'); + expectedFrame.write((byte) 5); + expectedFrame.write(":UTF-8:".getBytes(UTF_8)); + expectedFrame.write(new byte[] {0, 0, 0, 10}); + expectedFrame.write(':'); + expectedFrame.write(reportEntry.getSourceName().getBytes(UTF_8)); + expectedFrame.write(':'); + expectedFrame.write(new byte[] {0, 0, 0, 1}); + expectedFrame.write(':'); + expectedFrame.write(0); + expectedFrame.write(':'); + expectedFrame.write(new byte[] {0, 0, 0, 7}); + expectedFrame.write(':'); + expectedFrame.write(reportEntry.getName().getBytes(UTF_8)); + expectedFrame.write(':'); + expectedFrame.write(new byte[] {0, 0, 0, 1}); + expectedFrame.write(':'); + expectedFrame.write(0); + expectedFrame.write(':'); + expectedFrame.write(new byte[] {0, 0, 0, 10}); + expectedFrame.write(':'); + expectedFrame.write(reportEntry.getGroup().getBytes(UTF_8)); + expectedFrame.write(':'); + expectedFrame.write(new byte[] {0, 0, 0, 12}); + expectedFrame.write(':'); + expectedFrame.write(reportEntry.getMessage().getBytes(UTF_8)); + expectedFrame.write(':'); + expectedFrame.write(0xff); + expectedFrame.write(ELAPSED_TIME_HEXA); + expectedFrame.write(':'); + expectedFrame.write(new byte[] {0, 0, 0, 3}); + expectedFrame.write(':'); + expectedFrame.write(exceptionMessage.getBytes(UTF_8)); + expectedFrame.write(':'); + expectedFrame.write(new byte[] {0, 0, 0, 18}); + expectedFrame.write(':'); + expectedFrame.write( + reportEntry.getStackTraceWriter().smartTrimmedStackTrace().getBytes(UTF_8)); + expectedFrame.write(':'); + expectedFrame.write(new byte[] {0, 0, 0, 25}); + expectedFrame.write(':'); + expectedFrame.write(stackTrace.getBytes(UTF_8)); + expectedFrame.write(':'); + assertThat(out.toByteArray()).isEqualTo(expectedFrame.toByteArray()); } @Test - public void testSetCompleted() throws IOException - { + public void testSetCompleted() throws IOException { String exceptionMessage = "msg"; String smartStackTrace = "MyTest:86 >> Error"; String stackTrace = "trace line 1\ntrace line 2"; String trimmedStackTrace = "trace line 1\ntrace line 2"; - SafeThrowable safeThrowable = new SafeThrowable( new Exception( exceptionMessage ) ); - StackTraceWriter stackTraceWriter = mock( StackTraceWriter.class ); - when( stackTraceWriter.getThrowable() ).thenReturn( safeThrowable ); - when( stackTraceWriter.smartTrimmedStackTrace() ).thenReturn( smartStackTrace ); - when( stackTraceWriter.writeTrimmedTraceToString() ).thenReturn( trimmedStackTrace ); - when( stackTraceWriter.writeTraceToString() ).thenReturn( stackTrace ); + SafeThrowable safeThrowable = new SafeThrowable(new Exception(exceptionMessage)); + StackTraceWriter stackTraceWriter = mock(StackTraceWriter.class); + when(stackTraceWriter.getThrowable()).thenReturn(safeThrowable); + when(stackTraceWriter.smartTrimmedStackTrace()).thenReturn(smartStackTrace); + when(stackTraceWriter.writeTrimmedTraceToString()).thenReturn(trimmedStackTrace); + when(stackTraceWriter.writeTraceToString()).thenReturn(stackTrace); Map props = systemProps(); - TestSetReportEntry reportEntry = mock( TestSetReportEntry.class ); - when( reportEntry.getRunMode() ).thenReturn( NORMAL_RUN ); - when( reportEntry.getTestRunId() ).thenReturn( 1L ); - when( reportEntry.getElapsed() ).thenReturn( ELAPSED_TIME ); - when( reportEntry.getGroup() ).thenReturn( "this group" ); - when( reportEntry.getMessage() ).thenReturn( "skipped test" ); - when( reportEntry.getName() ).thenReturn( "my test" ); - when( reportEntry.getNameWithGroup() ).thenReturn( "name with group" ); - when( reportEntry.getSourceName() ).thenReturn( "pkg.MyTest" ); - when( reportEntry.getStackTraceWriter() ).thenReturn( stackTraceWriter ); - when( reportEntry.getSystemProperties() ).thenReturn( props ); + TestSetReportEntry reportEntry = mock(TestSetReportEntry.class); + when(reportEntry.getRunMode()).thenReturn(NORMAL_RUN); + when(reportEntry.getTestRunId()).thenReturn(1L); + when(reportEntry.getElapsed()).thenReturn(ELAPSED_TIME); + when(reportEntry.getGroup()).thenReturn("this group"); + when(reportEntry.getMessage()).thenReturn("skipped test"); + when(reportEntry.getName()).thenReturn("my test"); + when(reportEntry.getNameWithGroup()).thenReturn("name with group"); + when(reportEntry.getSourceName()).thenReturn("pkg.MyTest"); + when(reportEntry.getStackTraceWriter()).thenReturn(stackTraceWriter); + when(reportEntry.getSystemProperties()).thenReturn(props); Stream out = Stream.newStream(); - EventChannelEncoder encoder = new EventChannelEncoder( newBufferedChannel( out ) ); + EventChannelEncoder encoder = new EventChannelEncoder(newBufferedChannel(out)); - encoder.testSetCompleted( reportEntry, false ); + encoder.testSetCompleted(reportEntry, false); ByteArrayOutputStream expectedFrame = new ByteArrayOutputStream(); - for ( Entry entry : props.entrySet() ) - { - expectedFrame.write( ":maven-surefire-event:".getBytes() ); - expectedFrame.write( 8 ); - expectedFrame.write( ":sys-prop:".getBytes() ); - expectedFrame.write( 10 ); - expectedFrame.write( ":normal-run:".getBytes() ); - expectedFrame.write( "\u0001\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0001".getBytes() ); - expectedFrame.write( ":".getBytes() ); - expectedFrame.write( 5 ); - expectedFrame.write( ":UTF-8:".getBytes() ); - int[] k = toBytes( entry.getKey().length() ); - expectedFrame.write( k[0] ); - expectedFrame.write( k[1] ); - expectedFrame.write( k[2] ); - expectedFrame.write( k[3] ); - expectedFrame.write( ':' ); - expectedFrame.write( entry.getKey().getBytes( UTF_8 ) ); - expectedFrame.write( ':' ); - int[] v = toBytes( entry.getValue() == null ? 1 : entry.getValue().getBytes( UTF_8 ).length ); - expectedFrame.write( v[0] ); - expectedFrame.write( v[1] ); - expectedFrame.write( v[2] ); - expectedFrame.write( v[3] ); - expectedFrame.write( ':' ); - expectedFrame.write( ( entry.getValue() == null ? "\u0000" : entry.getValue() ).getBytes( UTF_8 ) ); - expectedFrame.write( ':' ); + for (Entry entry : props.entrySet()) { + expectedFrame.write(":maven-surefire-event:".getBytes()); + expectedFrame.write(8); + expectedFrame.write(":sys-prop:".getBytes()); + expectedFrame.write(10); + expectedFrame.write(":normal-run:".getBytes()); + expectedFrame.write("\u0001\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0001".getBytes()); + expectedFrame.write(":".getBytes()); + expectedFrame.write(5); + expectedFrame.write(":UTF-8:".getBytes()); + int[] k = toBytes(entry.getKey().length()); + expectedFrame.write(k[0]); + expectedFrame.write(k[1]); + expectedFrame.write(k[2]); + expectedFrame.write(k[3]); + expectedFrame.write(':'); + expectedFrame.write(entry.getKey().getBytes(UTF_8)); + expectedFrame.write(':'); + int[] v = toBytes(entry.getValue() == null ? 1 : entry.getValue().getBytes(UTF_8).length); + expectedFrame.write(v[0]); + expectedFrame.write(v[1]); + expectedFrame.write(v[2]); + expectedFrame.write(v[3]); + expectedFrame.write(':'); + expectedFrame.write((entry.getValue() == null ? "\u0000" : entry.getValue()).getBytes(UTF_8)); + expectedFrame.write(':'); } - expectedFrame.write( ":maven-surefire-event:".getBytes( UTF_8 ) ); - expectedFrame.write( (byte) 17 ); - expectedFrame.write( ":testset-completed:".getBytes( UTF_8 ) ); - expectedFrame.write( (byte) 10 ); - expectedFrame.write( ":normal-run:".getBytes( UTF_8 ) ); - expectedFrame.write( "\u0001\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0001".getBytes() ); - expectedFrame.write( ':' ); - expectedFrame.write( (byte) 5 ); - expectedFrame.write( ":UTF-8:".getBytes( UTF_8 ) ); - expectedFrame.write( new byte[] {0, 0, 0, 10} ); - expectedFrame.write( ':' ); - expectedFrame.write( reportEntry.getSourceName().getBytes( UTF_8 ) ); - expectedFrame.write( ':' ); - expectedFrame.write( new byte[] {0, 0, 0, 1} ); - expectedFrame.write( ':' ); - expectedFrame.write( 0 ); - expectedFrame.write( ':' ); - expectedFrame.write( new byte[] {0, 0, 0, 7} ); - expectedFrame.write( ':' ); - expectedFrame.write( reportEntry.getName().getBytes( UTF_8 ) ); - expectedFrame.write( ':' ); - expectedFrame.write( new byte[] {0, 0, 0, 1} ); - expectedFrame.write( ':' ); - expectedFrame.write( 0 ); - expectedFrame.write( ':' ); - expectedFrame.write( new byte[] {0, 0, 0, 10} ); - expectedFrame.write( ':' ); - expectedFrame.write( reportEntry.getGroup().getBytes( UTF_8 ) ); - expectedFrame.write( ':' ); - expectedFrame.write( new byte[] {0, 0, 0, 12} ); - expectedFrame.write( ':' ); - expectedFrame.write( reportEntry.getMessage().getBytes( UTF_8 ) ); - expectedFrame.write( ':' ); - expectedFrame.write( 0xff ); - expectedFrame.write( ELAPSED_TIME_HEXA ); - expectedFrame.write( ':' ); - expectedFrame.write( new byte[] {0, 0, 0, 3} ); - expectedFrame.write( ':' ); - expectedFrame.write( exceptionMessage.getBytes( UTF_8 ) ); - expectedFrame.write( ':' ); - expectedFrame.write( new byte[] {0, 0, 0, 18} ); - expectedFrame.write( ':' ); - expectedFrame.write( reportEntry.getStackTraceWriter().smartTrimmedStackTrace().getBytes( UTF_8 ) ); - expectedFrame.write( ':' ); - expectedFrame.write( new byte[] {0, 0, 0, 25} ); - expectedFrame.write( ':' ); - expectedFrame.write( stackTrace.getBytes( UTF_8 ) ); - expectedFrame.write( ':' ); - - assertThat( out.toByteArray() ) - .isEqualTo( expectedFrame.toByteArray() ); + expectedFrame.write(":maven-surefire-event:".getBytes(UTF_8)); + expectedFrame.write((byte) 17); + expectedFrame.write(":testset-completed:".getBytes(UTF_8)); + expectedFrame.write((byte) 10); + expectedFrame.write(":normal-run:".getBytes(UTF_8)); + expectedFrame.write("\u0001\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0001".getBytes()); + expectedFrame.write(':'); + expectedFrame.write((byte) 5); + expectedFrame.write(":UTF-8:".getBytes(UTF_8)); + expectedFrame.write(new byte[] {0, 0, 0, 10}); + expectedFrame.write(':'); + expectedFrame.write(reportEntry.getSourceName().getBytes(UTF_8)); + expectedFrame.write(':'); + expectedFrame.write(new byte[] {0, 0, 0, 1}); + expectedFrame.write(':'); + expectedFrame.write(0); + expectedFrame.write(':'); + expectedFrame.write(new byte[] {0, 0, 0, 7}); + expectedFrame.write(':'); + expectedFrame.write(reportEntry.getName().getBytes(UTF_8)); + expectedFrame.write(':'); + expectedFrame.write(new byte[] {0, 0, 0, 1}); + expectedFrame.write(':'); + expectedFrame.write(0); + expectedFrame.write(':'); + expectedFrame.write(new byte[] {0, 0, 0, 10}); + expectedFrame.write(':'); + expectedFrame.write(reportEntry.getGroup().getBytes(UTF_8)); + expectedFrame.write(':'); + expectedFrame.write(new byte[] {0, 0, 0, 12}); + expectedFrame.write(':'); + expectedFrame.write(reportEntry.getMessage().getBytes(UTF_8)); + expectedFrame.write(':'); + expectedFrame.write(0xff); + expectedFrame.write(ELAPSED_TIME_HEXA); + expectedFrame.write(':'); + expectedFrame.write(new byte[] {0, 0, 0, 3}); + expectedFrame.write(':'); + expectedFrame.write(exceptionMessage.getBytes(UTF_8)); + expectedFrame.write(':'); + expectedFrame.write(new byte[] {0, 0, 0, 18}); + expectedFrame.write(':'); + expectedFrame.write( + reportEntry.getStackTraceWriter().smartTrimmedStackTrace().getBytes(UTF_8)); + expectedFrame.write(':'); + expectedFrame.write(new byte[] {0, 0, 0, 25}); + expectedFrame.write(':'); + expectedFrame.write(stackTrace.getBytes(UTF_8)); + expectedFrame.write(':'); + + assertThat(out.toByteArray()).isEqualTo(expectedFrame.toByteArray()); } @Test - public void testStarting() throws IOException - { + public void testStarting() throws IOException { String exceptionMessage = "msg"; String smartStackTrace = "MyTest:86 >> Error"; String stackTrace = "trace line 1\ntrace line 2"; String trimmedStackTrace = "trace line 1\ntrace line 2"; - SafeThrowable safeThrowable = new SafeThrowable( new Exception( exceptionMessage ) ); - StackTraceWriter stackTraceWriter = mock( StackTraceWriter.class ); - when( stackTraceWriter.getThrowable() ).thenReturn( safeThrowable ); - when( stackTraceWriter.smartTrimmedStackTrace() ).thenReturn( smartStackTrace ); - when( stackTraceWriter.writeTrimmedTraceToString() ).thenReturn( trimmedStackTrace ); - when( stackTraceWriter.writeTraceToString() ).thenReturn( stackTrace ); - - ReportEntry reportEntry = mock( ReportEntry.class ); - when( reportEntry.getRunMode() ).thenReturn( NORMAL_RUN ); - when( reportEntry.getTestRunId() ).thenReturn( 1L ); - when( reportEntry.getElapsed() ).thenReturn( ELAPSED_TIME ); - when( reportEntry.getGroup() ).thenReturn( "this group" ); - when( reportEntry.getMessage() ).thenReturn( "skipped test" ); - when( reportEntry.getName() ).thenReturn( "my test" ); - when( reportEntry.getNameWithGroup() ).thenReturn( "name with group" ); - when( reportEntry.getSourceName() ).thenReturn( "pkg.MyTest" ); - when( reportEntry.getStackTraceWriter() ).thenReturn( stackTraceWriter ); + SafeThrowable safeThrowable = new SafeThrowable(new Exception(exceptionMessage)); + StackTraceWriter stackTraceWriter = mock(StackTraceWriter.class); + when(stackTraceWriter.getThrowable()).thenReturn(safeThrowable); + when(stackTraceWriter.smartTrimmedStackTrace()).thenReturn(smartStackTrace); + when(stackTraceWriter.writeTrimmedTraceToString()).thenReturn(trimmedStackTrace); + when(stackTraceWriter.writeTraceToString()).thenReturn(stackTrace); + + ReportEntry reportEntry = mock(ReportEntry.class); + when(reportEntry.getRunMode()).thenReturn(NORMAL_RUN); + when(reportEntry.getTestRunId()).thenReturn(1L); + when(reportEntry.getElapsed()).thenReturn(ELAPSED_TIME); + when(reportEntry.getGroup()).thenReturn("this group"); + when(reportEntry.getMessage()).thenReturn("skipped test"); + when(reportEntry.getName()).thenReturn("my test"); + when(reportEntry.getNameWithGroup()).thenReturn("name with group"); + when(reportEntry.getSourceName()).thenReturn("pkg.MyTest"); + when(reportEntry.getStackTraceWriter()).thenReturn(stackTraceWriter); Stream out = Stream.newStream(); - EventChannelEncoder encoder = new EventChannelEncoder( newBufferedChannel( out ) ); + EventChannelEncoder encoder = new EventChannelEncoder(newBufferedChannel(out)); - encoder.testStarting( reportEntry, true ); + encoder.testStarting(reportEntry, true); ByteArrayOutputStream expectedFrame = new ByteArrayOutputStream(); - expectedFrame.write( ":maven-surefire-event:".getBytes( UTF_8 ) ); - expectedFrame.write( (byte) 13 ); - expectedFrame.write( ":test-starting:".getBytes( UTF_8 ) ); - expectedFrame.write( (byte) 10 ); - expectedFrame.write( ":normal-run:".getBytes( UTF_8 ) ); - expectedFrame.write( "\u0001\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0001".getBytes() ); - expectedFrame.write( ':' ); - expectedFrame.write( (byte) 5 ); - expectedFrame.write( ":UTF-8:".getBytes( UTF_8 ) ); - expectedFrame.write( new byte[] {0, 0, 0, 10} ); - expectedFrame.write( ':' ); - expectedFrame.write( reportEntry.getSourceName().getBytes( UTF_8 ) ); - expectedFrame.write( ':' ); - expectedFrame.write( new byte[] {0, 0, 0, 1} ); - expectedFrame.write( ':' ); - expectedFrame.write( 0 ); - expectedFrame.write( ':' ); - expectedFrame.write( new byte[] {0, 0, 0, 7} ); - expectedFrame.write( ':' ); - expectedFrame.write( reportEntry.getName().getBytes( UTF_8 ) ); - expectedFrame.write( ':' ); - expectedFrame.write( new byte[] {0, 0, 0, 1} ); - expectedFrame.write( ':' ); - expectedFrame.write( 0 ); - expectedFrame.write( ':' ); - expectedFrame.write( new byte[] {0, 0, 0, 10} ); - expectedFrame.write( ':' ); - expectedFrame.write( reportEntry.getGroup().getBytes( UTF_8 ) ); - expectedFrame.write( ':' ); - expectedFrame.write( new byte[] {0, 0, 0, 12} ); - expectedFrame.write( ':' ); - expectedFrame.write( reportEntry.getMessage().getBytes( UTF_8 ) ); - expectedFrame.write( ':' ); - expectedFrame.write( 0xff ); - expectedFrame.write( ELAPSED_TIME_HEXA ); - expectedFrame.write( ':' ); - expectedFrame.write( new byte[] {0, 0, 0, 3} ); - expectedFrame.write( ':' ); - expectedFrame.write( exceptionMessage.getBytes( UTF_8 ) ); - expectedFrame.write( ':' ); - expectedFrame.write( new byte[] {0, 0, 0, 18} ); - expectedFrame.write( ':' ); - expectedFrame.write( reportEntry.getStackTraceWriter().smartTrimmedStackTrace().getBytes( UTF_8 ) ); - expectedFrame.write( ':' ); - expectedFrame.write( new byte[] {0, 0, 0, 25} ); - expectedFrame.write( ':' ); - expectedFrame.write( stackTrace.getBytes( UTF_8 ) ); - expectedFrame.write( ':' ); - assertThat( out.toByteArray() ) - .isEqualTo( expectedFrame.toByteArray() ); + expectedFrame.write(":maven-surefire-event:".getBytes(UTF_8)); + expectedFrame.write((byte) 13); + expectedFrame.write(":test-starting:".getBytes(UTF_8)); + expectedFrame.write((byte) 10); + expectedFrame.write(":normal-run:".getBytes(UTF_8)); + expectedFrame.write("\u0001\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0001".getBytes()); + expectedFrame.write(':'); + expectedFrame.write((byte) 5); + expectedFrame.write(":UTF-8:".getBytes(UTF_8)); + expectedFrame.write(new byte[] {0, 0, 0, 10}); + expectedFrame.write(':'); + expectedFrame.write(reportEntry.getSourceName().getBytes(UTF_8)); + expectedFrame.write(':'); + expectedFrame.write(new byte[] {0, 0, 0, 1}); + expectedFrame.write(':'); + expectedFrame.write(0); + expectedFrame.write(':'); + expectedFrame.write(new byte[] {0, 0, 0, 7}); + expectedFrame.write(':'); + expectedFrame.write(reportEntry.getName().getBytes(UTF_8)); + expectedFrame.write(':'); + expectedFrame.write(new byte[] {0, 0, 0, 1}); + expectedFrame.write(':'); + expectedFrame.write(0); + expectedFrame.write(':'); + expectedFrame.write(new byte[] {0, 0, 0, 10}); + expectedFrame.write(':'); + expectedFrame.write(reportEntry.getGroup().getBytes(UTF_8)); + expectedFrame.write(':'); + expectedFrame.write(new byte[] {0, 0, 0, 12}); + expectedFrame.write(':'); + expectedFrame.write(reportEntry.getMessage().getBytes(UTF_8)); + expectedFrame.write(':'); + expectedFrame.write(0xff); + expectedFrame.write(ELAPSED_TIME_HEXA); + expectedFrame.write(':'); + expectedFrame.write(new byte[] {0, 0, 0, 3}); + expectedFrame.write(':'); + expectedFrame.write(exceptionMessage.getBytes(UTF_8)); + expectedFrame.write(':'); + expectedFrame.write(new byte[] {0, 0, 0, 18}); + expectedFrame.write(':'); + expectedFrame.write( + reportEntry.getStackTraceWriter().smartTrimmedStackTrace().getBytes(UTF_8)); + expectedFrame.write(':'); + expectedFrame.write(new byte[] {0, 0, 0, 25}); + expectedFrame.write(':'); + expectedFrame.write(stackTrace.getBytes(UTF_8)); + expectedFrame.write(':'); + assertThat(out.toByteArray()).isEqualTo(expectedFrame.toByteArray()); } @Test - public void testSuccess() throws IOException - { + public void testSuccess() throws IOException { String exceptionMessage = "msg"; String smartStackTrace = "MyTest:86 >> Error"; String stackTrace = "trace line 1\ntrace line 2"; String trimmedStackTrace = "trace line 1\ntrace line 2"; - SafeThrowable safeThrowable = new SafeThrowable( new Exception( exceptionMessage ) ); - StackTraceWriter stackTraceWriter = mock( StackTraceWriter.class ); - when( stackTraceWriter.getThrowable() ).thenReturn( safeThrowable ); - when( stackTraceWriter.smartTrimmedStackTrace() ).thenReturn( smartStackTrace ); - when( stackTraceWriter.writeTrimmedTraceToString() ).thenReturn( trimmedStackTrace ); - when( stackTraceWriter.writeTraceToString() ).thenReturn( stackTrace ); - - ReportEntry reportEntry = mock( ReportEntry.class ); - when( reportEntry.getRunMode() ).thenReturn( NORMAL_RUN ); - when( reportEntry.getTestRunId() ).thenReturn( 1L ); - when( reportEntry.getElapsed() ).thenReturn( ELAPSED_TIME ); - when( reportEntry.getGroup() ).thenReturn( "this group" ); - when( reportEntry.getMessage() ).thenReturn( "skipped test" ); - when( reportEntry.getName() ).thenReturn( "my test" ); - when( reportEntry.getNameWithGroup() ).thenReturn( "name with group" ); - when( reportEntry.getSourceName() ).thenReturn( "pkg.MyTest" ); - when( reportEntry.getStackTraceWriter() ).thenReturn( stackTraceWriter ); + SafeThrowable safeThrowable = new SafeThrowable(new Exception(exceptionMessage)); + StackTraceWriter stackTraceWriter = mock(StackTraceWriter.class); + when(stackTraceWriter.getThrowable()).thenReturn(safeThrowable); + when(stackTraceWriter.smartTrimmedStackTrace()).thenReturn(smartStackTrace); + when(stackTraceWriter.writeTrimmedTraceToString()).thenReturn(trimmedStackTrace); + when(stackTraceWriter.writeTraceToString()).thenReturn(stackTrace); + + ReportEntry reportEntry = mock(ReportEntry.class); + when(reportEntry.getRunMode()).thenReturn(NORMAL_RUN); + when(reportEntry.getTestRunId()).thenReturn(1L); + when(reportEntry.getElapsed()).thenReturn(ELAPSED_TIME); + when(reportEntry.getGroup()).thenReturn("this group"); + when(reportEntry.getMessage()).thenReturn("skipped test"); + when(reportEntry.getName()).thenReturn("my test"); + when(reportEntry.getNameWithGroup()).thenReturn("name with group"); + when(reportEntry.getSourceName()).thenReturn("pkg.MyTest"); + when(reportEntry.getStackTraceWriter()).thenReturn(stackTraceWriter); Stream out = Stream.newStream(); - EventChannelEncoder encoder = new EventChannelEncoder( newBufferedChannel( out ) ); + EventChannelEncoder encoder = new EventChannelEncoder(newBufferedChannel(out)); - encoder.testSucceeded( reportEntry, true ); + encoder.testSucceeded(reportEntry, true); ByteArrayOutputStream expectedFrame = new ByteArrayOutputStream(); - expectedFrame.write( ":maven-surefire-event:".getBytes( UTF_8 ) ); - expectedFrame.write( (byte) 14 ); - expectedFrame.write( ":test-succeeded:".getBytes( UTF_8 ) ); - expectedFrame.write( (byte) 10 ); - expectedFrame.write( ":normal-run:".getBytes( UTF_8 ) ); - expectedFrame.write( "\u0001\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0001".getBytes() ); - expectedFrame.write( ':' ); - expectedFrame.write( (byte) 5 ); - expectedFrame.write( ":UTF-8:".getBytes( UTF_8 ) ); - expectedFrame.write( new byte[] {0, 0, 0, 10} ); - expectedFrame.write( ':' ); - expectedFrame.write( reportEntry.getSourceName().getBytes( UTF_8 ) ); - expectedFrame.write( ':' ); - expectedFrame.write( new byte[] {0, 0, 0, 1} ); - expectedFrame.write( ':' ); - expectedFrame.write( 0 ); - expectedFrame.write( ':' ); - expectedFrame.write( new byte[] {0, 0, 0, 7} ); - expectedFrame.write( ':' ); - expectedFrame.write( reportEntry.getName().getBytes( UTF_8 ) ); - expectedFrame.write( ':' ); - expectedFrame.write( new byte[] {0, 0, 0, 1} ); - expectedFrame.write( ':' ); - expectedFrame.write( 0 ); - expectedFrame.write( ':' ); - expectedFrame.write( new byte[] {0, 0, 0, 10} ); - expectedFrame.write( ':' ); - expectedFrame.write( reportEntry.getGroup().getBytes( UTF_8 ) ); - expectedFrame.write( ':' ); - expectedFrame.write( new byte[] {0, 0, 0, 12} ); - expectedFrame.write( ':' ); - expectedFrame.write( reportEntry.getMessage().getBytes( UTF_8 ) ); - expectedFrame.write( ':' ); - expectedFrame.write( 0xff ); - expectedFrame.write( ELAPSED_TIME_HEXA ); - expectedFrame.write( ':' ); - expectedFrame.write( new byte[] {0, 0, 0, 3} ); - expectedFrame.write( ':' ); - expectedFrame.write( exceptionMessage.getBytes( UTF_8 ) ); - expectedFrame.write( ':' ); - expectedFrame.write( new byte[] {0, 0, 0, 18} ); - expectedFrame.write( ':' ); - expectedFrame.write( reportEntry.getStackTraceWriter().smartTrimmedStackTrace().getBytes( UTF_8 ) ); - expectedFrame.write( ':' ); - expectedFrame.write( new byte[] {0, 0, 0, 25} ); - expectedFrame.write( ':' ); - expectedFrame.write( stackTrace.getBytes( UTF_8 ) ); - expectedFrame.write( ':' ); - assertThat( out.toByteArray() ) - .isEqualTo( expectedFrame.toByteArray() ); + expectedFrame.write(":maven-surefire-event:".getBytes(UTF_8)); + expectedFrame.write((byte) 14); + expectedFrame.write(":test-succeeded:".getBytes(UTF_8)); + expectedFrame.write((byte) 10); + expectedFrame.write(":normal-run:".getBytes(UTF_8)); + expectedFrame.write("\u0001\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0001".getBytes()); + expectedFrame.write(':'); + expectedFrame.write((byte) 5); + expectedFrame.write(":UTF-8:".getBytes(UTF_8)); + expectedFrame.write(new byte[] {0, 0, 0, 10}); + expectedFrame.write(':'); + expectedFrame.write(reportEntry.getSourceName().getBytes(UTF_8)); + expectedFrame.write(':'); + expectedFrame.write(new byte[] {0, 0, 0, 1}); + expectedFrame.write(':'); + expectedFrame.write(0); + expectedFrame.write(':'); + expectedFrame.write(new byte[] {0, 0, 0, 7}); + expectedFrame.write(':'); + expectedFrame.write(reportEntry.getName().getBytes(UTF_8)); + expectedFrame.write(':'); + expectedFrame.write(new byte[] {0, 0, 0, 1}); + expectedFrame.write(':'); + expectedFrame.write(0); + expectedFrame.write(':'); + expectedFrame.write(new byte[] {0, 0, 0, 10}); + expectedFrame.write(':'); + expectedFrame.write(reportEntry.getGroup().getBytes(UTF_8)); + expectedFrame.write(':'); + expectedFrame.write(new byte[] {0, 0, 0, 12}); + expectedFrame.write(':'); + expectedFrame.write(reportEntry.getMessage().getBytes(UTF_8)); + expectedFrame.write(':'); + expectedFrame.write(0xff); + expectedFrame.write(ELAPSED_TIME_HEXA); + expectedFrame.write(':'); + expectedFrame.write(new byte[] {0, 0, 0, 3}); + expectedFrame.write(':'); + expectedFrame.write(exceptionMessage.getBytes(UTF_8)); + expectedFrame.write(':'); + expectedFrame.write(new byte[] {0, 0, 0, 18}); + expectedFrame.write(':'); + expectedFrame.write( + reportEntry.getStackTraceWriter().smartTrimmedStackTrace().getBytes(UTF_8)); + expectedFrame.write(':'); + expectedFrame.write(new byte[] {0, 0, 0, 25}); + expectedFrame.write(':'); + expectedFrame.write(stackTrace.getBytes(UTF_8)); + expectedFrame.write(':'); + assertThat(out.toByteArray()).isEqualTo(expectedFrame.toByteArray()); } @Test - public void testFailed() throws IOException - { + public void testFailed() throws IOException { String exceptionMessage = "msg"; String smartStackTrace = "MyTest:86 >> Error"; String stackTrace = "trace line 1\ntrace line 2"; String trimmedStackTrace = "trace line 1\ntrace line 2"; - SafeThrowable safeThrowable = new SafeThrowable( new Exception( exceptionMessage ) ); - StackTraceWriter stackTraceWriter = mock( StackTraceWriter.class ); - when( stackTraceWriter.getThrowable() ).thenReturn( safeThrowable ); - when( stackTraceWriter.smartTrimmedStackTrace() ).thenReturn( smartStackTrace ); - when( stackTraceWriter.writeTrimmedTraceToString() ).thenReturn( trimmedStackTrace ); - when( stackTraceWriter.writeTraceToString() ).thenReturn( stackTrace ); - - ReportEntry reportEntry = mock( ReportEntry.class ); - when( reportEntry.getRunMode() ).thenReturn( NORMAL_RUN ); - when( reportEntry.getTestRunId() ).thenReturn( 1L ); - when( reportEntry.getElapsed() ).thenReturn( ELAPSED_TIME ); - when( reportEntry.getGroup() ).thenReturn( "this group" ); - when( reportEntry.getMessage() ).thenReturn( "skipped test" ); - when( reportEntry.getName() ).thenReturn( "my test" ); - when( reportEntry.getNameWithGroup() ).thenReturn( "name with group" ); - when( reportEntry.getSourceName() ).thenReturn( "pkg.MyTest" ); - when( reportEntry.getStackTraceWriter() ).thenReturn( stackTraceWriter ); + SafeThrowable safeThrowable = new SafeThrowable(new Exception(exceptionMessage)); + StackTraceWriter stackTraceWriter = mock(StackTraceWriter.class); + when(stackTraceWriter.getThrowable()).thenReturn(safeThrowable); + when(stackTraceWriter.smartTrimmedStackTrace()).thenReturn(smartStackTrace); + when(stackTraceWriter.writeTrimmedTraceToString()).thenReturn(trimmedStackTrace); + when(stackTraceWriter.writeTraceToString()).thenReturn(stackTrace); + + ReportEntry reportEntry = mock(ReportEntry.class); + when(reportEntry.getRunMode()).thenReturn(NORMAL_RUN); + when(reportEntry.getTestRunId()).thenReturn(1L); + when(reportEntry.getElapsed()).thenReturn(ELAPSED_TIME); + when(reportEntry.getGroup()).thenReturn("this group"); + when(reportEntry.getMessage()).thenReturn("skipped test"); + when(reportEntry.getName()).thenReturn("my test"); + when(reportEntry.getNameWithGroup()).thenReturn("name with group"); + when(reportEntry.getSourceName()).thenReturn("pkg.MyTest"); + when(reportEntry.getStackTraceWriter()).thenReturn(stackTraceWriter); Stream out = Stream.newStream(); - EventChannelEncoder encoder = new EventChannelEncoder( newBufferedChannel( out ) ); + EventChannelEncoder encoder = new EventChannelEncoder(newBufferedChannel(out)); - encoder.testFailed( reportEntry, false ); + encoder.testFailed(reportEntry, false); ByteArrayOutputStream expectedFrame = new ByteArrayOutputStream(); - expectedFrame.write( ":maven-surefire-event:".getBytes( UTF_8 ) ); - expectedFrame.write( (byte) 11 ); - expectedFrame.write( ":test-failed:".getBytes( UTF_8 ) ); - expectedFrame.write( (byte) 10 ); - expectedFrame.write( ":normal-run:".getBytes( UTF_8 ) ); - expectedFrame.write( "\u0001\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0001".getBytes() ); - expectedFrame.write( ':' ); - expectedFrame.write( (byte) 5 ); - expectedFrame.write( ":UTF-8:".getBytes( UTF_8 ) ); - expectedFrame.write( new byte[] {0, 0, 0, 10} ); - expectedFrame.write( ':' ); - expectedFrame.write( reportEntry.getSourceName().getBytes( UTF_8 ) ); - expectedFrame.write( ':' ); - expectedFrame.write( new byte[] {0, 0, 0, 1} ); - expectedFrame.write( ':' ); - expectedFrame.write( 0 ); - expectedFrame.write( ':' ); - expectedFrame.write( new byte[] {0, 0, 0, 7} ); - expectedFrame.write( ':' ); - expectedFrame.write( reportEntry.getName().getBytes( UTF_8 ) ); - expectedFrame.write( ':' ); - expectedFrame.write( new byte[] {0, 0, 0, 1} ); - expectedFrame.write( ':' ); - expectedFrame.write( 0 ); - expectedFrame.write( ':' ); - expectedFrame.write( new byte[] {0, 0, 0, 10} ); - expectedFrame.write( ':' ); - expectedFrame.write( reportEntry.getGroup().getBytes( UTF_8 ) ); - expectedFrame.write( ':' ); - expectedFrame.write( new byte[] {0, 0, 0, 12} ); - expectedFrame.write( ':' ); - expectedFrame.write( reportEntry.getMessage().getBytes( UTF_8 ) ); - expectedFrame.write( ':' ); - expectedFrame.write( 0xff ); - expectedFrame.write( ELAPSED_TIME_HEXA ); - expectedFrame.write( ':' ); - expectedFrame.write( new byte[] {0, 0, 0, 3} ); - expectedFrame.write( ':' ); - expectedFrame.write( exceptionMessage.getBytes( UTF_8 ) ); - expectedFrame.write( ':' ); - expectedFrame.write( new byte[] {0, 0, 0, 18} ); - expectedFrame.write( ':' ); - expectedFrame.write( reportEntry.getStackTraceWriter().smartTrimmedStackTrace().getBytes( UTF_8 ) ); - expectedFrame.write( ':' ); - expectedFrame.write( new byte[] {0, 0, 0, 25} ); - expectedFrame.write( ':' ); - expectedFrame.write( stackTrace.getBytes( UTF_8 ) ); - expectedFrame.write( ':' ); - assertThat( out.toByteArray() ) - .isEqualTo( expectedFrame.toByteArray() ); + expectedFrame.write(":maven-surefire-event:".getBytes(UTF_8)); + expectedFrame.write((byte) 11); + expectedFrame.write(":test-failed:".getBytes(UTF_8)); + expectedFrame.write((byte) 10); + expectedFrame.write(":normal-run:".getBytes(UTF_8)); + expectedFrame.write("\u0001\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0001".getBytes()); + expectedFrame.write(':'); + expectedFrame.write((byte) 5); + expectedFrame.write(":UTF-8:".getBytes(UTF_8)); + expectedFrame.write(new byte[] {0, 0, 0, 10}); + expectedFrame.write(':'); + expectedFrame.write(reportEntry.getSourceName().getBytes(UTF_8)); + expectedFrame.write(':'); + expectedFrame.write(new byte[] {0, 0, 0, 1}); + expectedFrame.write(':'); + expectedFrame.write(0); + expectedFrame.write(':'); + expectedFrame.write(new byte[] {0, 0, 0, 7}); + expectedFrame.write(':'); + expectedFrame.write(reportEntry.getName().getBytes(UTF_8)); + expectedFrame.write(':'); + expectedFrame.write(new byte[] {0, 0, 0, 1}); + expectedFrame.write(':'); + expectedFrame.write(0); + expectedFrame.write(':'); + expectedFrame.write(new byte[] {0, 0, 0, 10}); + expectedFrame.write(':'); + expectedFrame.write(reportEntry.getGroup().getBytes(UTF_8)); + expectedFrame.write(':'); + expectedFrame.write(new byte[] {0, 0, 0, 12}); + expectedFrame.write(':'); + expectedFrame.write(reportEntry.getMessage().getBytes(UTF_8)); + expectedFrame.write(':'); + expectedFrame.write(0xff); + expectedFrame.write(ELAPSED_TIME_HEXA); + expectedFrame.write(':'); + expectedFrame.write(new byte[] {0, 0, 0, 3}); + expectedFrame.write(':'); + expectedFrame.write(exceptionMessage.getBytes(UTF_8)); + expectedFrame.write(':'); + expectedFrame.write(new byte[] {0, 0, 0, 18}); + expectedFrame.write(':'); + expectedFrame.write( + reportEntry.getStackTraceWriter().smartTrimmedStackTrace().getBytes(UTF_8)); + expectedFrame.write(':'); + expectedFrame.write(new byte[] {0, 0, 0, 25}); + expectedFrame.write(':'); + expectedFrame.write(stackTrace.getBytes(UTF_8)); + expectedFrame.write(':'); + assertThat(out.toByteArray()).isEqualTo(expectedFrame.toByteArray()); } @Test - public void testSkipped() throws IOException - { + public void testSkipped() throws IOException { String smartStackTrace = "MyTest:86 >> Error"; String stackTrace = "trace line 1\ntrace line 2"; String trimmedStackTrace = "trace line 1\ntrace line 2"; - SafeThrowable safeThrowable = new SafeThrowable( new Exception() ); - StackTraceWriter stackTraceWriter = mock( StackTraceWriter.class ); - when( stackTraceWriter.getThrowable() ).thenReturn( safeThrowable ); - when( stackTraceWriter.smartTrimmedStackTrace() ).thenReturn( smartStackTrace ); - when( stackTraceWriter.writeTrimmedTraceToString() ).thenReturn( trimmedStackTrace ); - when( stackTraceWriter.writeTraceToString() ).thenReturn( stackTrace ); - - ReportEntry reportEntry = mock( ReportEntry.class ); - when( reportEntry.getRunMode() ).thenReturn( NORMAL_RUN ); - when( reportEntry.getTestRunId() ).thenReturn( 1L ); - when( reportEntry.getElapsed() ).thenReturn( ELAPSED_TIME ); - when( reportEntry.getGroup() ).thenReturn( "this group" ); - when( reportEntry.getMessage() ).thenReturn( "skipped test" ); - when( reportEntry.getName() ).thenReturn( "my test" ); - when( reportEntry.getNameWithGroup() ).thenReturn( "name with group" ); - when( reportEntry.getSourceName() ).thenReturn( "pkg.MyTest" ); - when( reportEntry.getStackTraceWriter() ).thenReturn( stackTraceWriter ); + SafeThrowable safeThrowable = new SafeThrowable(new Exception()); + StackTraceWriter stackTraceWriter = mock(StackTraceWriter.class); + when(stackTraceWriter.getThrowable()).thenReturn(safeThrowable); + when(stackTraceWriter.smartTrimmedStackTrace()).thenReturn(smartStackTrace); + when(stackTraceWriter.writeTrimmedTraceToString()).thenReturn(trimmedStackTrace); + when(stackTraceWriter.writeTraceToString()).thenReturn(stackTrace); + + ReportEntry reportEntry = mock(ReportEntry.class); + when(reportEntry.getRunMode()).thenReturn(NORMAL_RUN); + when(reportEntry.getTestRunId()).thenReturn(1L); + when(reportEntry.getElapsed()).thenReturn(ELAPSED_TIME); + when(reportEntry.getGroup()).thenReturn("this group"); + when(reportEntry.getMessage()).thenReturn("skipped test"); + when(reportEntry.getName()).thenReturn("my test"); + when(reportEntry.getNameWithGroup()).thenReturn("name with group"); + when(reportEntry.getSourceName()).thenReturn("pkg.MyTest"); + when(reportEntry.getStackTraceWriter()).thenReturn(stackTraceWriter); Stream out = Stream.newStream(); - EventChannelEncoder encoder = new EventChannelEncoder( newBufferedChannel( out ) ); + EventChannelEncoder encoder = new EventChannelEncoder(newBufferedChannel(out)); - encoder.testSkipped( reportEntry, false ); + encoder.testSkipped(reportEntry, false); ByteArrayOutputStream expectedFrame = new ByteArrayOutputStream(); - expectedFrame.write( ":maven-surefire-event:".getBytes( UTF_8 ) ); - expectedFrame.write( (byte) 12 ); - expectedFrame.write( ":test-skipped:".getBytes( UTF_8 ) ); - expectedFrame.write( (byte) 10 ); - expectedFrame.write( ":normal-run:".getBytes( UTF_8 ) ); - expectedFrame.write( "\u0001\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0001".getBytes() ); - expectedFrame.write( ':' ); - expectedFrame.write( (byte) 5 ); - expectedFrame.write( ":UTF-8:".getBytes( UTF_8 ) ); - expectedFrame.write( new byte[] {0, 0, 0, 10} ); - expectedFrame.write( ':' ); - expectedFrame.write( reportEntry.getSourceName().getBytes( UTF_8 ) ); - expectedFrame.write( ':' ); - expectedFrame.write( new byte[] {0, 0, 0, 1} ); - expectedFrame.write( ':' ); - expectedFrame.write( 0 ); - expectedFrame.write( ':' ); - expectedFrame.write( new byte[] {0, 0, 0, 7} ); - expectedFrame.write( ':' ); - expectedFrame.write( reportEntry.getName().getBytes( UTF_8 ) ); - expectedFrame.write( ':' ); - expectedFrame.write( new byte[] {0, 0, 0, 1} ); - expectedFrame.write( ':' ); - expectedFrame.write( 0 ); - expectedFrame.write( ':' ); - expectedFrame.write( new byte[] {0, 0, 0, 10} ); - expectedFrame.write( ':' ); - expectedFrame.write( reportEntry.getGroup().getBytes( UTF_8 ) ); - expectedFrame.write( ':' ); - expectedFrame.write( new byte[] {0, 0, 0, 12} ); - expectedFrame.write( ':' ); - expectedFrame.write( reportEntry.getMessage().getBytes( UTF_8 ) ); - expectedFrame.write( ':' ); - expectedFrame.write( 0xFF ); - expectedFrame.write( ELAPSED_TIME_HEXA ); - expectedFrame.write( ':' ); - expectedFrame.write( new byte[] {0, 0, 0, 1} ); - expectedFrame.write( ':' ); - expectedFrame.write( 0 ); - expectedFrame.write( ':' ); - expectedFrame.write( new byte[] {0, 0, 0, 18} ); - expectedFrame.write( ':' ); - expectedFrame.write( reportEntry.getStackTraceWriter().smartTrimmedStackTrace().getBytes( UTF_8 ) ); - expectedFrame.write( ':' ); - expectedFrame.write( new byte[] {0, 0, 0, 25} ); - expectedFrame.write( ':' ); - expectedFrame.write( stackTrace.getBytes( UTF_8 ) ); - expectedFrame.write( ':' ); - assertThat( out.toByteArray() ) - .isEqualTo( expectedFrame.toByteArray() ); + expectedFrame.write(":maven-surefire-event:".getBytes(UTF_8)); + expectedFrame.write((byte) 12); + expectedFrame.write(":test-skipped:".getBytes(UTF_8)); + expectedFrame.write((byte) 10); + expectedFrame.write(":normal-run:".getBytes(UTF_8)); + expectedFrame.write("\u0001\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0001".getBytes()); + expectedFrame.write(':'); + expectedFrame.write((byte) 5); + expectedFrame.write(":UTF-8:".getBytes(UTF_8)); + expectedFrame.write(new byte[] {0, 0, 0, 10}); + expectedFrame.write(':'); + expectedFrame.write(reportEntry.getSourceName().getBytes(UTF_8)); + expectedFrame.write(':'); + expectedFrame.write(new byte[] {0, 0, 0, 1}); + expectedFrame.write(':'); + expectedFrame.write(0); + expectedFrame.write(':'); + expectedFrame.write(new byte[] {0, 0, 0, 7}); + expectedFrame.write(':'); + expectedFrame.write(reportEntry.getName().getBytes(UTF_8)); + expectedFrame.write(':'); + expectedFrame.write(new byte[] {0, 0, 0, 1}); + expectedFrame.write(':'); + expectedFrame.write(0); + expectedFrame.write(':'); + expectedFrame.write(new byte[] {0, 0, 0, 10}); + expectedFrame.write(':'); + expectedFrame.write(reportEntry.getGroup().getBytes(UTF_8)); + expectedFrame.write(':'); + expectedFrame.write(new byte[] {0, 0, 0, 12}); + expectedFrame.write(':'); + expectedFrame.write(reportEntry.getMessage().getBytes(UTF_8)); + expectedFrame.write(':'); + expectedFrame.write(0xFF); + expectedFrame.write(ELAPSED_TIME_HEXA); + expectedFrame.write(':'); + expectedFrame.write(new byte[] {0, 0, 0, 1}); + expectedFrame.write(':'); + expectedFrame.write(0); + expectedFrame.write(':'); + expectedFrame.write(new byte[] {0, 0, 0, 18}); + expectedFrame.write(':'); + expectedFrame.write( + reportEntry.getStackTraceWriter().smartTrimmedStackTrace().getBytes(UTF_8)); + expectedFrame.write(':'); + expectedFrame.write(new byte[] {0, 0, 0, 25}); + expectedFrame.write(':'); + expectedFrame.write(stackTrace.getBytes(UTF_8)); + expectedFrame.write(':'); + assertThat(out.toByteArray()).isEqualTo(expectedFrame.toByteArray()); } @Test - public void testError() throws IOException - { + public void testError() throws IOException { String stackTrace = "trace line 1\ntrace line 2"; String trimmedStackTrace = "trace line 1"; - SafeThrowable safeThrowable = new SafeThrowable( new Exception() ); - StackTraceWriter stackTraceWriter = mock( StackTraceWriter.class ); - when( stackTraceWriter.getThrowable() ).thenReturn( safeThrowable ); - when( stackTraceWriter.smartTrimmedStackTrace() ).thenReturn( null ); - when( stackTraceWriter.writeTrimmedTraceToString() ).thenReturn( trimmedStackTrace ); - when( stackTraceWriter.writeTraceToString() ).thenReturn( stackTrace ); - - ReportEntry reportEntry = mock( ReportEntry.class ); - when( reportEntry.getRunMode() ).thenReturn( NORMAL_RUN ); - when( reportEntry.getTestRunId() ).thenReturn( 1L ); - when( reportEntry.getElapsed() ).thenReturn( ELAPSED_TIME ); - when( reportEntry.getGroup() ).thenReturn( "this group" ); - when( reportEntry.getMessage() ).thenReturn( "skipped test" ); - when( reportEntry.getName() ).thenReturn( "my test" ); - when( reportEntry.getNameWithGroup() ).thenReturn( "name with group" ); - when( reportEntry.getSourceName() ).thenReturn( "pkg.MyTest" ); - when( reportEntry.getStackTraceWriter() ).thenReturn( stackTraceWriter ); + SafeThrowable safeThrowable = new SafeThrowable(new Exception()); + StackTraceWriter stackTraceWriter = mock(StackTraceWriter.class); + when(stackTraceWriter.getThrowable()).thenReturn(safeThrowable); + when(stackTraceWriter.smartTrimmedStackTrace()).thenReturn(null); + when(stackTraceWriter.writeTrimmedTraceToString()).thenReturn(trimmedStackTrace); + when(stackTraceWriter.writeTraceToString()).thenReturn(stackTrace); + + ReportEntry reportEntry = mock(ReportEntry.class); + when(reportEntry.getRunMode()).thenReturn(NORMAL_RUN); + when(reportEntry.getTestRunId()).thenReturn(1L); + when(reportEntry.getElapsed()).thenReturn(ELAPSED_TIME); + when(reportEntry.getGroup()).thenReturn("this group"); + when(reportEntry.getMessage()).thenReturn("skipped test"); + when(reportEntry.getName()).thenReturn("my test"); + when(reportEntry.getNameWithGroup()).thenReturn("name with group"); + when(reportEntry.getSourceName()).thenReturn("pkg.MyTest"); + when(reportEntry.getStackTraceWriter()).thenReturn(stackTraceWriter); Stream out = Stream.newStream(); - EventChannelEncoder encoder = new EventChannelEncoder( newBufferedChannel( out ) ); - encoder.testError( reportEntry, false ); + EventChannelEncoder encoder = new EventChannelEncoder(newBufferedChannel(out)); + encoder.testError(reportEntry, false); ByteArrayOutputStream expectedFrame = new ByteArrayOutputStream(); - expectedFrame.write( ":maven-surefire-event:".getBytes( UTF_8 ) ); - expectedFrame.write( (byte) 10 ); - expectedFrame.write( ":test-error:".getBytes( UTF_8 ) ); - expectedFrame.write( (byte) 10 ); - expectedFrame.write( ":normal-run:".getBytes( UTF_8 ) ); - expectedFrame.write( "\u0001\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0001".getBytes() ); - expectedFrame.write( ':' ); - expectedFrame.write( (byte) 5 ); - expectedFrame.write( ":UTF-8:".getBytes( UTF_8 ) ); - expectedFrame.write( new byte[] {0, 0, 0, 10} ); - expectedFrame.write( ':' ); - expectedFrame.write( reportEntry.getSourceName().getBytes( UTF_8 ) ); - expectedFrame.write( ':' ); - expectedFrame.write( new byte[] {0, 0, 0, 1} ); - expectedFrame.write( ':' ); - expectedFrame.write( 0 ); - expectedFrame.write( ':' ); - expectedFrame.write( new byte[] {0, 0, 0, 7} ); - expectedFrame.write( ':' ); - expectedFrame.write( reportEntry.getName().getBytes( UTF_8 ) ); - expectedFrame.write( ':' ); - expectedFrame.write( new byte[] {0, 0, 0, 1} ); - expectedFrame.write( ':' ); - expectedFrame.write( 0 ); - expectedFrame.write( ':' ); - expectedFrame.write( new byte[] {0, 0, 0, 10} ); - expectedFrame.write( ':' ); - expectedFrame.write( reportEntry.getGroup().getBytes( UTF_8 ) ); - expectedFrame.write( ':' ); - expectedFrame.write( new byte[] {0, 0, 0, 12} ); - expectedFrame.write( ':' ); - expectedFrame.write( reportEntry.getMessage().getBytes( UTF_8 ) ); - expectedFrame.write( ':' ); - expectedFrame.write( 0xff ); - expectedFrame.write( ELAPSED_TIME_HEXA ); - expectedFrame.write( ':' ); - expectedFrame.write( new byte[] {0, 0, 0, 1} ); - expectedFrame.write( ':' ); - expectedFrame.write( 0 ); - expectedFrame.write( ':' ); - expectedFrame.write( new byte[] {0, 0, 0, 1} ); - expectedFrame.write( ':' ); - expectedFrame.write( 0 ); - expectedFrame.write( ':' ); - expectedFrame.write( new byte[] {0, 0, 0, 25} ); - expectedFrame.write( ':' ); - expectedFrame.write( stackTrace.getBytes( UTF_8 ) ); - expectedFrame.write( ':' ); - assertThat( out.toByteArray() ) - .isEqualTo( expectedFrame.toByteArray() ); + expectedFrame.write(":maven-surefire-event:".getBytes(UTF_8)); + expectedFrame.write((byte) 10); + expectedFrame.write(":test-error:".getBytes(UTF_8)); + expectedFrame.write((byte) 10); + expectedFrame.write(":normal-run:".getBytes(UTF_8)); + expectedFrame.write("\u0001\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0001".getBytes()); + expectedFrame.write(':'); + expectedFrame.write((byte) 5); + expectedFrame.write(":UTF-8:".getBytes(UTF_8)); + expectedFrame.write(new byte[] {0, 0, 0, 10}); + expectedFrame.write(':'); + expectedFrame.write(reportEntry.getSourceName().getBytes(UTF_8)); + expectedFrame.write(':'); + expectedFrame.write(new byte[] {0, 0, 0, 1}); + expectedFrame.write(':'); + expectedFrame.write(0); + expectedFrame.write(':'); + expectedFrame.write(new byte[] {0, 0, 0, 7}); + expectedFrame.write(':'); + expectedFrame.write(reportEntry.getName().getBytes(UTF_8)); + expectedFrame.write(':'); + expectedFrame.write(new byte[] {0, 0, 0, 1}); + expectedFrame.write(':'); + expectedFrame.write(0); + expectedFrame.write(':'); + expectedFrame.write(new byte[] {0, 0, 0, 10}); + expectedFrame.write(':'); + expectedFrame.write(reportEntry.getGroup().getBytes(UTF_8)); + expectedFrame.write(':'); + expectedFrame.write(new byte[] {0, 0, 0, 12}); + expectedFrame.write(':'); + expectedFrame.write(reportEntry.getMessage().getBytes(UTF_8)); + expectedFrame.write(':'); + expectedFrame.write(0xff); + expectedFrame.write(ELAPSED_TIME_HEXA); + expectedFrame.write(':'); + expectedFrame.write(new byte[] {0, 0, 0, 1}); + expectedFrame.write(':'); + expectedFrame.write(0); + expectedFrame.write(':'); + expectedFrame.write(new byte[] {0, 0, 0, 1}); + expectedFrame.write(':'); + expectedFrame.write(0); + expectedFrame.write(':'); + expectedFrame.write(new byte[] {0, 0, 0, 25}); + expectedFrame.write(':'); + expectedFrame.write(stackTrace.getBytes(UTF_8)); + expectedFrame.write(':'); + assertThat(out.toByteArray()).isEqualTo(expectedFrame.toByteArray()); } @Test - public void testAssumptionFailure() throws IOException - { + public void testAssumptionFailure() throws IOException { String exceptionMessage = "msg"; String smartStackTrace = "MyTest:86 >> Error"; - SafeThrowable safeThrowable = new SafeThrowable( new Exception( exceptionMessage ) ); - StackTraceWriter stackTraceWriter = mock( StackTraceWriter.class ); - when( stackTraceWriter.getThrowable() ).thenReturn( safeThrowable ); - when( stackTraceWriter.smartTrimmedStackTrace() ).thenReturn( smartStackTrace ); - when( stackTraceWriter.writeTrimmedTraceToString() ).thenReturn( null ); - when( stackTraceWriter.writeTraceToString() ).thenReturn( null ); - - ReportEntry reportEntry = mock( ReportEntry.class ); - when( reportEntry.getRunMode() ).thenReturn( NORMAL_RUN ); - when( reportEntry.getTestRunId() ).thenReturn( 1L ); - when( reportEntry.getElapsed() ).thenReturn( null ); - when( reportEntry.getGroup() ).thenReturn( "this group" ); - when( reportEntry.getMessage() ).thenReturn( "skipped test" ); - when( reportEntry.getName() ).thenReturn( "my test" ); - when( reportEntry.getNameWithGroup() ).thenReturn( "name with group" ); - when( reportEntry.getSourceName() ).thenReturn( "pkg.MyTest" ); - when( reportEntry.getStackTraceWriter() ).thenReturn( stackTraceWriter ); + SafeThrowable safeThrowable = new SafeThrowable(new Exception(exceptionMessage)); + StackTraceWriter stackTraceWriter = mock(StackTraceWriter.class); + when(stackTraceWriter.getThrowable()).thenReturn(safeThrowable); + when(stackTraceWriter.smartTrimmedStackTrace()).thenReturn(smartStackTrace); + when(stackTraceWriter.writeTrimmedTraceToString()).thenReturn(null); + when(stackTraceWriter.writeTraceToString()).thenReturn(null); + + ReportEntry reportEntry = mock(ReportEntry.class); + when(reportEntry.getRunMode()).thenReturn(NORMAL_RUN); + when(reportEntry.getTestRunId()).thenReturn(1L); + when(reportEntry.getElapsed()).thenReturn(null); + when(reportEntry.getGroup()).thenReturn("this group"); + when(reportEntry.getMessage()).thenReturn("skipped test"); + when(reportEntry.getName()).thenReturn("my test"); + when(reportEntry.getNameWithGroup()).thenReturn("name with group"); + when(reportEntry.getSourceName()).thenReturn("pkg.MyTest"); + when(reportEntry.getStackTraceWriter()).thenReturn(stackTraceWriter); Stream out = Stream.newStream(); - EventChannelEncoder encoder = new EventChannelEncoder( newBufferedChannel( out ) ); + EventChannelEncoder encoder = new EventChannelEncoder(newBufferedChannel(out)); - encoder.testAssumptionFailure( reportEntry, false ); + encoder.testAssumptionFailure(reportEntry, false); ByteArrayOutputStream expectedFrame = new ByteArrayOutputStream(); - expectedFrame.write( ":maven-surefire-event:".getBytes( UTF_8 ) ); - expectedFrame.write( (byte) 23 ); - expectedFrame.write( ":test-assumption-failure:".getBytes( UTF_8 ) ); - expectedFrame.write( (byte) 10 ); - expectedFrame.write( ":normal-run:".getBytes( UTF_8 ) ); - expectedFrame.write( "\u0001\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0001".getBytes() ); - expectedFrame.write( ':' ); - expectedFrame.write( (byte) 5 ); - expectedFrame.write( ":UTF-8:".getBytes( UTF_8 ) ); - expectedFrame.write( new byte[] {0, 0, 0, 10} ); - expectedFrame.write( ':' ); - expectedFrame.write( reportEntry.getSourceName().getBytes( UTF_8 ) ); - expectedFrame.write( ':' ); - expectedFrame.write( new byte[] {0, 0, 0, 1} ); - expectedFrame.write( ':' ); - expectedFrame.write( 0 ); - expectedFrame.write( ':' ); - expectedFrame.write( new byte[] {0, 0, 0, 7} ); - expectedFrame.write( ':' ); - expectedFrame.write( reportEntry.getName().getBytes( UTF_8 ) ); - expectedFrame.write( ':' ); - expectedFrame.write( new byte[] {0, 0, 0, 1} ); - expectedFrame.write( ':' ); - expectedFrame.write( 0 ); - expectedFrame.write( ':' ); - expectedFrame.write( new byte[] {0, 0, 0, 10} ); - expectedFrame.write( ':' ); - expectedFrame.write( reportEntry.getGroup().getBytes( UTF_8 ) ); - expectedFrame.write( ':' ); - expectedFrame.write( new byte[] {0, 0, 0, 12} ); - expectedFrame.write( ':' ); - expectedFrame.write( reportEntry.getMessage().getBytes( UTF_8 ) ); - expectedFrame.write( ':' ); - expectedFrame.write( 0 ); - expectedFrame.write( ':' ); - expectedFrame.write( new byte[] {0, 0, 0, 3} ); - expectedFrame.write( ':' ); - expectedFrame.write( exceptionMessage.getBytes( UTF_8 ) ); - expectedFrame.write( ':' ); - expectedFrame.write( new byte[] {0, 0, 0, 18} ); - expectedFrame.write( ':' ); - expectedFrame.write( smartStackTrace.getBytes( UTF_8 ) ); - expectedFrame.write( ':' ); - expectedFrame.write( new byte[] {0, 0, 0, 1} ); - expectedFrame.write( ':' ); - expectedFrame.write( 0 ); - expectedFrame.write( ':' ); - assertThat( out.toByteArray() ) - .isEqualTo( expectedFrame.toByteArray() ); + expectedFrame.write(":maven-surefire-event:".getBytes(UTF_8)); + expectedFrame.write((byte) 23); + expectedFrame.write(":test-assumption-failure:".getBytes(UTF_8)); + expectedFrame.write((byte) 10); + expectedFrame.write(":normal-run:".getBytes(UTF_8)); + expectedFrame.write("\u0001\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0001".getBytes()); + expectedFrame.write(':'); + expectedFrame.write((byte) 5); + expectedFrame.write(":UTF-8:".getBytes(UTF_8)); + expectedFrame.write(new byte[] {0, 0, 0, 10}); + expectedFrame.write(':'); + expectedFrame.write(reportEntry.getSourceName().getBytes(UTF_8)); + expectedFrame.write(':'); + expectedFrame.write(new byte[] {0, 0, 0, 1}); + expectedFrame.write(':'); + expectedFrame.write(0); + expectedFrame.write(':'); + expectedFrame.write(new byte[] {0, 0, 0, 7}); + expectedFrame.write(':'); + expectedFrame.write(reportEntry.getName().getBytes(UTF_8)); + expectedFrame.write(':'); + expectedFrame.write(new byte[] {0, 0, 0, 1}); + expectedFrame.write(':'); + expectedFrame.write(0); + expectedFrame.write(':'); + expectedFrame.write(new byte[] {0, 0, 0, 10}); + expectedFrame.write(':'); + expectedFrame.write(reportEntry.getGroup().getBytes(UTF_8)); + expectedFrame.write(':'); + expectedFrame.write(new byte[] {0, 0, 0, 12}); + expectedFrame.write(':'); + expectedFrame.write(reportEntry.getMessage().getBytes(UTF_8)); + expectedFrame.write(':'); + expectedFrame.write(0); + expectedFrame.write(':'); + expectedFrame.write(new byte[] {0, 0, 0, 3}); + expectedFrame.write(':'); + expectedFrame.write(exceptionMessage.getBytes(UTF_8)); + expectedFrame.write(':'); + expectedFrame.write(new byte[] {0, 0, 0, 18}); + expectedFrame.write(':'); + expectedFrame.write(smartStackTrace.getBytes(UTF_8)); + expectedFrame.write(':'); + expectedFrame.write(new byte[] {0, 0, 0, 1}); + expectedFrame.write(':'); + expectedFrame.write(0); + expectedFrame.write(':'); + assertThat(out.toByteArray()).isEqualTo(expectedFrame.toByteArray()); } @Test - public void testBye() - { + public void testBye() { Stream out = Stream.newStream(); - EventChannelEncoder encoder = new EventChannelEncoder( newBufferedChannel( out ) ); + EventChannelEncoder encoder = new EventChannelEncoder(newBufferedChannel(out)); encoder.bye(); - String encoded = new String( out.toByteArray(), UTF_8 ); + String encoded = new String(out.toByteArray(), UTF_8); - assertThat( encoded ) - .isEqualTo( ":maven-surefire-event:\u0003:bye:" ); + assertThat(encoded).isEqualTo(":maven-surefire-event:\u0003:bye:"); } @Test - public void testStopOnNextTest() - { + public void testStopOnNextTest() { Stream out = Stream.newStream(); - EventChannelEncoder encoder = new EventChannelEncoder( newBufferedChannel( out ) ); + EventChannelEncoder encoder = new EventChannelEncoder(newBufferedChannel(out)); encoder.stopOnNextTest(); - String encoded = new String( out.toByteArray(), UTF_8 ); - assertThat( encoded ) - .isEqualTo( ":maven-surefire-event:\u0011:stop-on-next-test:" ); + String encoded = new String(out.toByteArray(), UTF_8); + assertThat(encoded).isEqualTo(":maven-surefire-event:\u0011:stop-on-next-test:"); } @Test - public void testAcquireNextTest() - { + public void testAcquireNextTest() { Stream out = Stream.newStream(); - EventChannelEncoder encoder = new EventChannelEncoder( newBufferedChannel( out ) ); + EventChannelEncoder encoder = new EventChannelEncoder(newBufferedChannel(out)); encoder.acquireNextTest(); - String encoded = new String( out.toByteArray(), UTF_8 ); - assertThat( encoded ) - .isEqualTo( ":maven-surefire-event:\u0009:next-test:" ); + String encoded = new String(out.toByteArray(), UTF_8); + assertThat(encoded).isEqualTo(":maven-surefire-event:\u0009:next-test:"); } @Test - public void testSendOpcode() - { + public void testSendOpcode() { Channel channel = new Channel(); - new EventChannelEncoder( channel ) - .testOutput( new TestOutputReportEntry( stdOut( "msg" ), NORMAL_RUN, 1L ) ); - assertThat( toString( channel.src ) ) - .isEqualTo( ":maven-surefire-event:" + (char) 14 + ":std-out-stream:" + (char) 10 + ":normal-run:" - + "\u0001\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0001:" - + (char) 5 + ":UTF-8:\u0000\u0000\u0000\u0003:msg:" ); + new EventChannelEncoder(channel).testOutput(new TestOutputReportEntry(stdOut("msg"), NORMAL_RUN, 1L)); + assertThat(toString(channel.src)) + .isEqualTo(":maven-surefire-event:" + (char) 14 + ":std-out-stream:" + (char) 10 + ":normal-run:" + + "\u0001\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0001:" + + (char) 5 + ":UTF-8:\u0000\u0000\u0000\u0003:msg:"); channel = new Channel(); - new EventChannelEncoder( channel ) - .testOutput( new TestOutputReportEntry( stdErr( null ), NORMAL_RUN, 1L ) ); - assertThat( toString( channel.src ) ) - .isEqualTo( ":maven-surefire-event:" + (char) 14 + ":std-err-stream:" + (char) 10 + ":normal-run:" - + "\u0001\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0001:" - + (char) 5 + ":UTF-8:\u0000\u0000\u0000\u0001:\u0000:" ); - - ByteBuffer result = new EventChannelEncoder( new Channel() ) - .encodeMessage( BOOTERCODE_TEST_ERROR, NORMAL_RUN, 1L, "msg" ); - assertThat( toString( result ) ) - .isEqualTo( ":maven-surefire-event:" + (char) 10 + ":test-error:" + (char) 10 + ":normal-run:" - + "\u0001\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0001:" - + (char) 5 + ":UTF-8:\u0000\u0000\u0000\u0003:msg:" ); + new EventChannelEncoder(channel).testOutput(new TestOutputReportEntry(stdErr(null), NORMAL_RUN, 1L)); + assertThat(toString(channel.src)) + .isEqualTo(":maven-surefire-event:" + (char) 14 + ":std-err-stream:" + (char) 10 + ":normal-run:" + + "\u0001\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0001:" + + (char) 5 + ":UTF-8:\u0000\u0000\u0000\u0001:\u0000:"); + + ByteBuffer result = + new EventChannelEncoder(new Channel()).encodeMessage(BOOTERCODE_TEST_ERROR, NORMAL_RUN, 1L, "msg"); + assertThat(toString(result)) + .isEqualTo(":maven-surefire-event:" + (char) 10 + ":test-error:" + (char) 10 + ":normal-run:" + + "\u0001\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0001:" + + (char) 5 + ":UTF-8:\u0000\u0000\u0000\u0003:msg:"); } @Test - public void testConsoleInfo() - { + public void testConsoleInfo() { Stream out = Stream.newStream(); - EventChannelEncoder encoder = new EventChannelEncoder( newBufferedChannel( out ) ); + EventChannelEncoder encoder = new EventChannelEncoder(newBufferedChannel(out)); - encoder.consoleInfoLog( "msg" ); + encoder.consoleInfoLog("msg"); - String encoded = new String( out.toByteArray(), UTF_8 ); + String encoded = new String(out.toByteArray(), UTF_8); String expected = ":maven-surefire-event:\u0010:console-info-log:\u0005:UTF-8:\u0000\u0000\u0000\u0003:msg:"; - assertThat( encoded ) - .isEqualTo( expected ); + assertThat(encoded).isEqualTo(expected); } @Test - public void testConsoleError() - { + public void testConsoleError() { Stream out = Stream.newStream(); - EventChannelEncoder encoder = new EventChannelEncoder( newBufferedChannel( out ) ); + EventChannelEncoder encoder = new EventChannelEncoder(newBufferedChannel(out)); - encoder.consoleErrorLog( "msg" ); + encoder.consoleErrorLog("msg"); - String encoded = new String( out.toByteArray(), UTF_8 ); + String encoded = new String(out.toByteArray(), UTF_8); String expected = ":maven-surefire-event:\u0011:console-error-log:\u0005:UTF-8:" - + "\u0000\u0000\u0000\u0003:msg:" - + "\u0000\u0000\u0000\u0001:\u0000:" - + "\u0000\u0000\u0000\u0001:\u0000:"; + + "\u0000\u0000\u0000\u0003:msg:" + + "\u0000\u0000\u0000\u0001:\u0000:" + + "\u0000\u0000\u0000\u0001:\u0000:"; - assertThat( encoded ) - .isEqualTo( expected ); + assertThat(encoded).isEqualTo(expected); } @Test - public void testConsoleErrorLog1() throws IOException - { + public void testConsoleErrorLog1() throws IOException { Stream out = Stream.newStream(); - EventChannelEncoder encoder = new EventChannelEncoder( newBufferedChannel( out ) ); + EventChannelEncoder encoder = new EventChannelEncoder(newBufferedChannel(out)); - Exception e = new Exception( "msg" ); - encoder.consoleErrorLog( e ); - String stackTrace = ConsoleLoggerUtils.toString( e ); + Exception e = new Exception("msg"); + encoder.consoleErrorLog(e); + String stackTrace = ConsoleLoggerUtils.toString(e); ByteArrayOutputStream expectedFrame = new ByteArrayOutputStream(); - expectedFrame.write( ":maven-surefire-event:\u0011:console-error-log:\u0005:UTF-8:".getBytes( UTF_8 ) ); - expectedFrame.write( 0 ); - expectedFrame.write( 0 ); - expectedFrame.write( 0 ); - expectedFrame.write( 3 ); - expectedFrame.write( ':' ); - expectedFrame.write( "msg".getBytes( UTF_8 ) ); - expectedFrame.write( ':' ); - expectedFrame.write( 0 ); - expectedFrame.write( 0 ); - expectedFrame.write( 0 ); - expectedFrame.write( 1 ); - expectedFrame.write( ':' ); - expectedFrame.write( 0 ); - expectedFrame.write( ':' ); - byte[] stackTraceBytes = stackTrace.getBytes( UTF_8 ); - int[] stackTraceLength = toBytes( stackTraceBytes.length ); - expectedFrame.write( stackTraceLength[0] ); - expectedFrame.write( stackTraceLength[1] ); - expectedFrame.write( stackTraceLength[2] ); - expectedFrame.write( stackTraceLength[3] ); - expectedFrame.write( ':' ); - expectedFrame.write( stackTraceBytes ); - expectedFrame.write( ':' ); - assertThat( out.toByteArray() ) - .isEqualTo( expectedFrame.toByteArray() ); + expectedFrame.write(":maven-surefire-event:\u0011:console-error-log:\u0005:UTF-8:".getBytes(UTF_8)); + expectedFrame.write(0); + expectedFrame.write(0); + expectedFrame.write(0); + expectedFrame.write(3); + expectedFrame.write(':'); + expectedFrame.write("msg".getBytes(UTF_8)); + expectedFrame.write(':'); + expectedFrame.write(0); + expectedFrame.write(0); + expectedFrame.write(0); + expectedFrame.write(1); + expectedFrame.write(':'); + expectedFrame.write(0); + expectedFrame.write(':'); + byte[] stackTraceBytes = stackTrace.getBytes(UTF_8); + int[] stackTraceLength = toBytes(stackTraceBytes.length); + expectedFrame.write(stackTraceLength[0]); + expectedFrame.write(stackTraceLength[1]); + expectedFrame.write(stackTraceLength[2]); + expectedFrame.write(stackTraceLength[3]); + expectedFrame.write(':'); + expectedFrame.write(stackTraceBytes); + expectedFrame.write(':'); + assertThat(out.toByteArray()).isEqualTo(expectedFrame.toByteArray()); } @Test - public void testConsoleErrorLog2() throws IOException - { + public void testConsoleErrorLog2() throws IOException { Stream out = Stream.newStream(); - EventChannelEncoder encoder = new EventChannelEncoder( newBufferedChannel( out ) ); + EventChannelEncoder encoder = new EventChannelEncoder(newBufferedChannel(out)); - Exception e = new Exception( "msg" ); - encoder.consoleErrorLog( "msg2", e ); - String stackTrace = ConsoleLoggerUtils.toString( e ); + Exception e = new Exception("msg"); + encoder.consoleErrorLog("msg2", e); + String stackTrace = ConsoleLoggerUtils.toString(e); ByteArrayOutputStream expectedFrame = new ByteArrayOutputStream(); - expectedFrame.write( ":maven-surefire-event:\u0011:console-error-log:\u0005:UTF-8:".getBytes( UTF_8 ) ); - expectedFrame.write( 0 ); - expectedFrame.write( 0 ); - expectedFrame.write( 0 ); - expectedFrame.write( 4 ); - expectedFrame.write( ':' ); - expectedFrame.write( "msg2".getBytes( UTF_8 ) ); - expectedFrame.write( ':' ); - expectedFrame.write( 0 ); - expectedFrame.write( 0 ); - expectedFrame.write( 0 ); - expectedFrame.write( 1 ); - expectedFrame.write( ':' ); - expectedFrame.write( 0 ); - expectedFrame.write( ':' ); - byte[] stackTraceBytes = stackTrace.getBytes( UTF_8 ); - int[] stackTraceLength = toBytes( stackTraceBytes.length ); - expectedFrame.write( stackTraceLength[0] ); - expectedFrame.write( stackTraceLength[1] ); - expectedFrame.write( stackTraceLength[2] ); - expectedFrame.write( stackTraceLength[3] ); - expectedFrame.write( ':' ); - expectedFrame.write( stackTraceBytes ); - expectedFrame.write( ':' ); - assertThat( out.toByteArray() ) - .isEqualTo( expectedFrame.toByteArray() ); + expectedFrame.write(":maven-surefire-event:\u0011:console-error-log:\u0005:UTF-8:".getBytes(UTF_8)); + expectedFrame.write(0); + expectedFrame.write(0); + expectedFrame.write(0); + expectedFrame.write(4); + expectedFrame.write(':'); + expectedFrame.write("msg2".getBytes(UTF_8)); + expectedFrame.write(':'); + expectedFrame.write(0); + expectedFrame.write(0); + expectedFrame.write(0); + expectedFrame.write(1); + expectedFrame.write(':'); + expectedFrame.write(0); + expectedFrame.write(':'); + byte[] stackTraceBytes = stackTrace.getBytes(UTF_8); + int[] stackTraceLength = toBytes(stackTraceBytes.length); + expectedFrame.write(stackTraceLength[0]); + expectedFrame.write(stackTraceLength[1]); + expectedFrame.write(stackTraceLength[2]); + expectedFrame.write(stackTraceLength[3]); + expectedFrame.write(':'); + expectedFrame.write(stackTraceBytes); + expectedFrame.write(':'); + assertThat(out.toByteArray()).isEqualTo(expectedFrame.toByteArray()); } @Test - public void testConsoleErrorLog3() - { + public void testConsoleErrorLog3() { Stream out = Stream.newStream(); - EventChannelEncoder encoder = new EventChannelEncoder( newBufferedChannel( out ) ); - - StackTraceWriter stackTraceWriter = mock( StackTraceWriter.class ); - when( stackTraceWriter.getThrowable() ).thenReturn( new SafeThrowable( "1" ) ); - when( stackTraceWriter.smartTrimmedStackTrace() ).thenReturn( "2" ); - when( stackTraceWriter.writeTraceToString() ).thenReturn( "3" ); - when( stackTraceWriter.writeTrimmedTraceToString() ).thenReturn( "4" ); - - encoder.consoleErrorLog( stackTraceWriter, true ); - String encoded = new String( out.toByteArray(), UTF_8 ); - assertThat( encoded ) - .startsWith( ":maven-surefire-event:\u0011:console-error-log:\u0005:UTF-8:\u0000\u0000\u0000\u0001:1:\u0000\u0000\u0000\u0001:2:\u0000\u0000\u0000\u0001:4:" ); + EventChannelEncoder encoder = new EventChannelEncoder(newBufferedChannel(out)); + + StackTraceWriter stackTraceWriter = mock(StackTraceWriter.class); + when(stackTraceWriter.getThrowable()).thenReturn(new SafeThrowable("1")); + when(stackTraceWriter.smartTrimmedStackTrace()).thenReturn("2"); + when(stackTraceWriter.writeTraceToString()).thenReturn("3"); + when(stackTraceWriter.writeTrimmedTraceToString()).thenReturn("4"); + + encoder.consoleErrorLog(stackTraceWriter, true); + String encoded = new String(out.toByteArray(), UTF_8); + assertThat(encoded) + .startsWith( + ":maven-surefire-event:\u0011:console-error-log:\u0005:UTF-8:\u0000\u0000\u0000\u0001:1:\u0000\u0000\u0000\u0001:2:\u0000\u0000\u0000\u0001:4:"); } @Test - public void testConsoleDebug() - { + public void testConsoleDebug() { Stream out = Stream.newStream(); - EventChannelEncoder encoder = new EventChannelEncoder( newBufferedChannel( out ) ); + EventChannelEncoder encoder = new EventChannelEncoder(newBufferedChannel(out)); - encoder.consoleDebugLog( "msg" ); + encoder.consoleDebugLog("msg"); - String encoded = new String( out.toByteArray(), UTF_8 ); + String encoded = new String(out.toByteArray(), UTF_8); String expected = ":maven-surefire-event:\u0011:console-debug-log:\u0005:UTF-8:\u0000\u0000\u0000\u0003:msg:"; - assertThat( encoded ) - .isEqualTo( expected ); + assertThat(encoded).isEqualTo(expected); } @Test - public void testConsoleWarning() - { + public void testConsoleWarning() { Stream out = Stream.newStream(); - EventChannelEncoder encoder = new EventChannelEncoder( newBufferedChannel( out ) ); + EventChannelEncoder encoder = new EventChannelEncoder(newBufferedChannel(out)); - encoder.consoleWarningLog( "msg" ); + encoder.consoleWarningLog("msg"); - String encoded = new String( out.toByteArray(), UTF_8 ); + String encoded = new String(out.toByteArray(), UTF_8); String expected = ":maven-surefire-event:\u0013:console-warning-log:\u0005:UTF-8:\u0000\u0000\u0000\u0003:msg:"; - assertThat( encoded ) - .isEqualTo( expected ); + assertThat(encoded).isEqualTo(expected); } @Test - public void testStdOutStream() throws IOException - { + public void testStdOutStream() throws IOException { Stream out = Stream.newStream(); - WritableBufferedByteChannel channel = newBufferedChannel( out ); - EventChannelEncoder encoder = new EventChannelEncoder( channel ); + WritableBufferedByteChannel channel = newBufferedChannel(out); + EventChannelEncoder encoder = new EventChannelEncoder(channel); - encoder.testOutput( new TestOutputReportEntry( stdOut( "msg" ), NORMAL_RUN, 1L ) ); + encoder.testOutput(new TestOutputReportEntry(stdOut("msg"), NORMAL_RUN, 1L)); channel.close(); String expected = ":maven-surefire-event:\u000e:std-out-stream:" - + (char) 10 + ":normal-run:\u0001\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0001:" - + "\u0005:UTF-8:\u0000\u0000\u0000\u0003:msg:"; + + (char) 10 + ":normal-run:\u0001\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0001:" + + "\u0005:UTF-8:\u0000\u0000\u0000\u0003:msg:"; - assertThat( new String( out.toByteArray(), UTF_8 ) ) - .isEqualTo( expected ); + assertThat(new String(out.toByteArray(), UTF_8)).isEqualTo(expected); } @Test - public void testStdOutStreamLn() throws IOException - { + public void testStdOutStreamLn() throws IOException { Stream out = Stream.newStream(); - WritableBufferedByteChannel channel = newBufferedChannel( out ); - EventChannelEncoder encoder = new EventChannelEncoder( channel ); + WritableBufferedByteChannel channel = newBufferedChannel(out); + EventChannelEncoder encoder = new EventChannelEncoder(channel); - encoder.testOutput( new TestOutputReportEntry( stdOutln( "msg" ), NORMAL_RUN, 1L ) ); + encoder.testOutput(new TestOutputReportEntry(stdOutln("msg"), NORMAL_RUN, 1L)); channel.close(); String expected = ":maven-surefire-event:\u0017:std-out-stream-new-line:" - + (char) 10 + ":normal-run:\u0001\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0001:" - + "\u0005:UTF-8:\u0000\u0000\u0000\u0003:msg:"; + + (char) 10 + ":normal-run:\u0001\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0001:" + + "\u0005:UTF-8:\u0000\u0000\u0000\u0003:msg:"; - assertThat( new String( out.toByteArray(), UTF_8 ) ) - .isEqualTo( expected ); + assertThat(new String(out.toByteArray(), UTF_8)).isEqualTo(expected); } @Test - public void testStdErrStream() throws IOException - { + public void testStdErrStream() throws IOException { Stream out = Stream.newStream(); - WritableBufferedByteChannel channel = newBufferedChannel( out ); - EventChannelEncoder encoder = new EventChannelEncoder( channel ); + WritableBufferedByteChannel channel = newBufferedChannel(out); + EventChannelEncoder encoder = new EventChannelEncoder(channel); - encoder.testOutput( new TestOutputReportEntry( stdErr( "msg" ), NORMAL_RUN, 1L ) ); + encoder.testOutput(new TestOutputReportEntry(stdErr("msg"), NORMAL_RUN, 1L)); channel.close(); String expected = ":maven-surefire-event:\u000e:std-err-stream:" - + (char) 10 + ":normal-run:\u0001\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0001:" - + "\u0005:UTF-8:\u0000\u0000\u0000\u0003:msg:"; + + (char) 10 + ":normal-run:\u0001\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0001:" + + "\u0005:UTF-8:\u0000\u0000\u0000\u0003:msg:"; - assertThat( new String( out.toByteArray(), UTF_8 ) ) - .isEqualTo( expected ); + assertThat(new String(out.toByteArray(), UTF_8)).isEqualTo(expected); } @Test - public void testStdErrStreamLn() throws IOException - { + public void testStdErrStreamLn() throws IOException { Stream out = Stream.newStream(); - WritableBufferedByteChannel channel = newBufferedChannel( out ); - EventChannelEncoder encoder = new EventChannelEncoder( channel ); + WritableBufferedByteChannel channel = newBufferedChannel(out); + EventChannelEncoder encoder = new EventChannelEncoder(channel); - encoder.testOutput( new TestOutputReportEntry( stdErrln( "msg" ), NORMAL_RUN, 1L ) ); + encoder.testOutput(new TestOutputReportEntry(stdErrln("msg"), NORMAL_RUN, 1L)); channel.close(); String expected = ":maven-surefire-event:\u0017:std-err-stream-new-line:" - + (char) 10 + ":normal-run:\u0001\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0001:" - + "\u0005:UTF-8:\u0000\u0000\u0000\u0003:msg:"; + + (char) 10 + ":normal-run:\u0001\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0001:" + + "\u0005:UTF-8:\u0000\u0000\u0000\u0003:msg:"; - assertThat( new String( out.toByteArray(), UTF_8 ) ) - .isEqualTo( expected ); + assertThat(new String(out.toByteArray(), UTF_8)).isEqualTo(expected); } @Test - public void testStdErrStreamEmptyMessageNullTestId() throws IOException - { + public void testStdErrStreamEmptyMessageNullTestId() throws IOException { Stream out = Stream.newStream(); - WritableBufferedByteChannel channel = newBufferedChannel( out ); - EventChannelEncoder encoder = new EventChannelEncoder( channel ); + WritableBufferedByteChannel channel = newBufferedChannel(out); + EventChannelEncoder encoder = new EventChannelEncoder(channel); // This used to produce a BufferOverflowException; see SUREFIRE-2056. // In essence, we used to under-allocate for the encoding of a null test ID @@ -1240,208 +1197,183 @@ public void testStdErrStreamEmptyMessageNullTestId() throws IOException // otherwise we over-allocate for the test message // (for safety, due to unpredictability of the size of encoded text) // and this over-allocation ends up compensating the under-allocation for the null test id. - encoder.testOutput( new TestOutputReportEntry( stdErr( "" ), NORMAL_RUN, null ) ); + encoder.testOutput(new TestOutputReportEntry(stdErr(""), NORMAL_RUN, null)); channel.close(); String expected = ":maven-surefire-event:\u000e:std-err-stream:" - + (char) 10 + ":normal-run:\u0000:" - + "\u0005:UTF-8:\u0000\u0000\u0000\u0000::"; + + (char) 10 + ":normal-run:\u0000:" + + "\u0005:UTF-8:\u0000\u0000\u0000\u0000::"; - assertThat( new String( out.toByteArray(), UTF_8 ) ) - .isEqualTo( expected ); + assertThat(new String(out.toByteArray(), UTF_8)).isEqualTo(expected); } @Test - public void testStdErrStreamEmptyMessageNullRunMode() throws IOException - { + public void testStdErrStreamEmptyMessageNullRunMode() throws IOException { Stream out = Stream.newStream(); - WritableBufferedByteChannel channel = newBufferedChannel( out ); - EventChannelEncoder encoder = new EventChannelEncoder( channel ); + WritableBufferedByteChannel channel = newBufferedChannel(out); + EventChannelEncoder encoder = new EventChannelEncoder(channel); // This used to produce a BufferOverflowException; see SUREFIRE-2076. - encoder.testOutput( new TestOutputReportEntry( stdErr( "" ), null, 1L ) ); + encoder.testOutput(new TestOutputReportEntry(stdErr(""), null, 1L)); channel.close(); String expected = ":maven-surefire-event:\u000e:std-err-stream:" - + (char) 0 + "::" // One byte for length and 1+1 bytes for the 2 delimiters (0 bytes for null runMode) - + "\u0001\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0001:" - + "\u0005:UTF-8:\u0000\u0000\u0000\u0000::"; + + (char) 0 + "::" // One byte for length and 1+1 bytes for the 2 delimiters (0 bytes for null runMode) + + "\u0001\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0001:" + + "\u0005:UTF-8:\u0000\u0000\u0000\u0000::"; - assertThat( new String( out.toByteArray(), UTF_8 ) ) - .isEqualTo( expected ); + assertThat(new String(out.toByteArray(), UTF_8)).isEqualTo(expected); } @Test - @SuppressWarnings( "checkstyle:innerassignment" ) - public void shouldCountSameNumberOfSystemProperties() throws IOException - { + @SuppressWarnings("checkstyle:innerassignment") + public void shouldCountSameNumberOfSystemProperties() throws IOException { Stream stream = Stream.newStream(); - WritableBufferedByteChannel channel = newBufferedChannel( stream ); - EventChannelEncoder encoder = new EventChannelEncoder( channel ); + WritableBufferedByteChannel channel = newBufferedChannel(stream); + EventChannelEncoder encoder = new EventChannelEncoder(channel); Map sysProps = ObjectUtils.systemProps(); - encoder.encodeSystemProperties( sysProps, NORMAL_RUN, 1L ); + encoder.encodeSystemProperties(sysProps, NORMAL_RUN, 1L); channel.close(); - for ( Entry entry : sysProps.entrySet() ) - { - int[] k = toBytes( entry.getKey().length() ); - int[] v = toBytes( entry.getValue() == null ? 1 : entry.getValue().getBytes( UTF_8 ).length ); + for (Entry entry : sysProps.entrySet()) { + int[] k = toBytes(entry.getKey().length()); + int[] v = toBytes(entry.getValue() == null ? 1 : entry.getValue().getBytes(UTF_8).length); ByteArrayOutputStream expectedFrame = new ByteArrayOutputStream(); - expectedFrame.write( ":maven-surefire-event:sys-prop:normal-run:UTF-8:".getBytes( UTF_8 ) ); - expectedFrame.write( k[0] ); - expectedFrame.write( k[1] ); - expectedFrame.write( k[2] ); - expectedFrame.write( k[3] ); - expectedFrame.write( ':' ); - expectedFrame.write( v[0] ); - expectedFrame.write( v[1] ); - expectedFrame.write( v[2] ); - expectedFrame.write( v[3] ); - expectedFrame.write( ':' ); - expectedFrame.write( ( entry.getValue() == null ? "\u0000" : entry.getValue() ).getBytes( UTF_8 ) ); - expectedFrame.write( ':' ); - assertThat( stream.toByteArray() ) - .contains( expectedFrame.toByteArray() ); + expectedFrame.write(":maven-surefire-event:sys-prop:normal-run:UTF-8:".getBytes(UTF_8)); + expectedFrame.write(k[0]); + expectedFrame.write(k[1]); + expectedFrame.write(k[2]); + expectedFrame.write(k[3]); + expectedFrame.write(':'); + expectedFrame.write(v[0]); + expectedFrame.write(v[1]); + expectedFrame.write(v[2]); + expectedFrame.write(v[3]); + expectedFrame.write(':'); + expectedFrame.write((entry.getValue() == null ? "\u0000" : entry.getValue()).getBytes(UTF_8)); + expectedFrame.write(':'); + assertThat(stream.toByteArray()).contains(expectedFrame.toByteArray()); } } @Test - public void shouldHandleExit() - { + public void shouldHandleExit() { Stream out = Stream.newStream(); - EventChannelEncoder encoder = new EventChannelEncoder( newBufferedChannel( out ) ); - StackTraceWriter stackTraceWriter = mock( StackTraceWriter.class ); - when( stackTraceWriter.getThrowable() ).thenReturn( new SafeThrowable( "1" ) ); - when( stackTraceWriter.smartTrimmedStackTrace() ).thenReturn( "2" ); - when( stackTraceWriter.writeTraceToString() ).thenReturn( "3" ); - when( stackTraceWriter.writeTrimmedTraceToString() ).thenReturn( "4" ); - encoder.sendExitError( stackTraceWriter, false ); - - assertThat( new String( out.toByteArray(), UTF_8 ) ) - .startsWith( ":maven-surefire-event:\u000e:jvm-exit-error:\u0005:UTF-8:\u0000\u0000\u0000\u0001:1:\u0000\u0000\u0000\u0001:2:\u0000\u0000\u0000\u0001:3:" ); + EventChannelEncoder encoder = new EventChannelEncoder(newBufferedChannel(out)); + StackTraceWriter stackTraceWriter = mock(StackTraceWriter.class); + when(stackTraceWriter.getThrowable()).thenReturn(new SafeThrowable("1")); + when(stackTraceWriter.smartTrimmedStackTrace()).thenReturn("2"); + when(stackTraceWriter.writeTraceToString()).thenReturn("3"); + when(stackTraceWriter.writeTrimmedTraceToString()).thenReturn("4"); + encoder.sendExitError(stackTraceWriter, false); + + assertThat(new String(out.toByteArray(), UTF_8)) + .startsWith( + ":maven-surefire-event:\u000e:jvm-exit-error:\u0005:UTF-8:\u0000\u0000\u0000\u0001:1:\u0000\u0000\u0000\u0001:2:\u0000\u0000\u0000\u0001:3:"); } @Test - public void shouldHandleExitWithTrimmedTrace() - { + public void shouldHandleExitWithTrimmedTrace() { Stream out = Stream.newStream(); - EventChannelEncoder encoder = new EventChannelEncoder( newBufferedChannel( out ) ); - StackTraceWriter stackTraceWriter = mock( StackTraceWriter.class ); - when( stackTraceWriter.getThrowable() ).thenReturn( new SafeThrowable( "1" ) ); - when( stackTraceWriter.smartTrimmedStackTrace() ).thenReturn( "2" ); - when( stackTraceWriter.writeTraceToString() ).thenReturn( "3" ); - when( stackTraceWriter.writeTrimmedTraceToString() ).thenReturn( "4" ); - encoder.sendExitError( stackTraceWriter, true ); - - assertThat( new String( out.toByteArray(), UTF_8 ) ) - .startsWith( ":maven-surefire-event:\u000e:jvm-exit-error:\u0005:UTF-8:\u0000\u0000\u0000\u0001:1:\u0000\u0000\u0000\u0001:2:\u0000\u0000\u0000\u0001:4:" ); + EventChannelEncoder encoder = new EventChannelEncoder(newBufferedChannel(out)); + StackTraceWriter stackTraceWriter = mock(StackTraceWriter.class); + when(stackTraceWriter.getThrowable()).thenReturn(new SafeThrowable("1")); + when(stackTraceWriter.smartTrimmedStackTrace()).thenReturn("2"); + when(stackTraceWriter.writeTraceToString()).thenReturn("3"); + when(stackTraceWriter.writeTrimmedTraceToString()).thenReturn("4"); + encoder.sendExitError(stackTraceWriter, true); + + assertThat(new String(out.toByteArray(), UTF_8)) + .startsWith( + ":maven-surefire-event:\u000e:jvm-exit-error:\u0005:UTF-8:\u0000\u0000\u0000\u0001:1:\u0000\u0000\u0000\u0001:2:\u0000\u0000\u0000\u0001:4:"); } @Test - public void testInterruptHandling() throws IOException - { + public void testInterruptHandling() throws IOException { Stream out = Stream.newStream(); - WritableBufferedByteChannel channel = newBufferedChannel( out ); - EventChannelEncoder encoder = new EventChannelEncoder( channel ); + WritableBufferedByteChannel channel = newBufferedChannel(out); + EventChannelEncoder encoder = new EventChannelEncoder(channel); Thread.currentThread().interrupt(); - try - { - encoder.testOutput( new TestOutputReportEntry( stdOut( "msg" ), NORMAL_RUN, 2L ) ); + try { + encoder.testOutput(new TestOutputReportEntry(stdOut("msg"), NORMAL_RUN, 2L)); channel.close(); - } - finally - { + } finally { // Clear the interrupt and make sure it survived the invocation - assertThat( Thread.interrupted() ) - .isTrue(); + assertThat(Thread.interrupted()).isTrue(); } - assertThat( new String( out.toByteArray(), UTF_8 ) ) - .isEqualTo( ":maven-surefire-event:\u000e:std-out-stream:" - + (char) 10 + ":normal-run:\u0001\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0002" - + ":\u0005:UTF-8:\u0000\u0000\u0000\u0003:msg:" ); + assertThat(new String(out.toByteArray(), UTF_8)) + .isEqualTo(":maven-surefire-event:\u000e:std-out-stream:" + + (char) 10 + ":normal-run:\u0001\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0002" + + ":\u0005:UTF-8:\u0000\u0000\u0000\u0003:msg:"); } - private static class Stream extends PrintStream - { + private static class Stream extends PrintStream { private final ByteArrayOutputStream out; - Stream( ByteArrayOutputStream out ) - { - super( out, true ); + Stream(ByteArrayOutputStream out) { + super(out, true); this.out = out; } - byte[] toByteArray() - { + byte[] toByteArray() { return out.toByteArray(); } - static Stream newStream() - { - return new Stream( new ByteArrayOutputStream() ); + static Stream newStream() { + return new Stream(new ByteArrayOutputStream()); } } - private static byte[] toArray( ByteBuffer buffer ) - { - return copyOfRange( buffer.array(), buffer.arrayOffset(), buffer.arrayOffset() + buffer.remaining() ); + private static byte[] toArray(ByteBuffer buffer) { + return copyOfRange(buffer.array(), buffer.arrayOffset(), buffer.arrayOffset() + buffer.remaining()); } - private static String toString( ByteBuffer frame ) - { + private static String toString(ByteBuffer frame) { ByteArrayOutputStream os = new ByteArrayOutputStream(); - ( (Buffer) frame ).flip(); - os.write( frame.array(), frame.arrayOffset() + ( (Buffer) frame ).position(), frame.remaining() ); - return new String( os.toByteArray(), UTF_8 ); + ((Buffer) frame).flip(); + os.write(frame.array(), frame.arrayOffset() + ((Buffer) frame).position(), frame.remaining()); + return new String(os.toByteArray(), UTF_8); } - private static int[] toBytes( int i ) - { + private static int[] toBytes(int i) { int[] result = new int[4]; - result[0] = 0xff & ( i >> 24 ); - result[1] = 0xff & ( i >> 16 ); - result[2] = 0xff & ( i >> 8 ); + result[0] = 0xff & (i >> 24); + result[1] = 0xff & (i >> 16); + result[2] = 0xff & (i >> 8); result[3] = 0xff & i; return result; } - private static final class Channel implements WritableBufferedByteChannel - { + private static final class Channel implements WritableBufferedByteChannel { ByteBuffer src; @Override - public void writeBuffered( ByteBuffer src ) - { + public void writeBuffered(ByteBuffer src) { this.src = src; } @Override - public long countBufferOverflows() - { + public long countBufferOverflows() { return 0; } @Override - public int write( ByteBuffer src ) - { + public int write(ByteBuffer src) { this.src = src; return 0; } @Override - public boolean isOpen() - { + public boolean isOpen() { return false; } @Override - public void close() - { - } + public void close() {} } } diff --git a/surefire-extensions-api/pom.xml b/surefire-extensions-api/pom.xml index 787cd25468..d3b5bdef14 100644 --- a/surefire-extensions-api/pom.xml +++ b/surefire-extensions-api/pom.xml @@ -17,76 +17,76 @@ ~ specific language governing permissions and limitations ~ under the License. --> - - 4.0.0 + 4.0.0 - - org.apache.maven.surefire - surefire - 3.0.0-M10-SNAPSHOT - + + org.apache.maven.surefire + surefire + 3.0.0-M10-SNAPSHOT + - surefire-extensions-api - Surefire Extensions API + surefire-extensions-api + Surefire Extensions API - - - org.apache.maven.surefire - surefire-api - ${project.version} - provided - - - com.google.code.findbugs - jsr305 - provided - - - org.apache.maven.surefire - surefire-shared-utils - ${surefire-shared-utils.version} - - - org.mockito - mockito-core - test - - + + + org.apache.maven.surefire + surefire-api + ${project.version} + provided + + + com.google.code.findbugs + jsr305 + provided + + + org.apache.maven.surefire + surefire-shared-utils + ${surefire-shared-utils.version} + + + org.mockito + mockito-core + test + + - - - - org.jacoco - jacoco-maven-plugin - - - jacoco-agent - - prepare-agent - - - - - jacoco.agent - - - - maven-surefire-plugin - - ${jvm.args.tests} ${jacoco.agent} - - **/JUnit4SuiteTest.java - - - - - org.apache.maven.surefire - surefire-shadefire - 3.0.0-M7 - - - - - + + + + org.jacoco + jacoco-maven-plugin + + jacoco.agent + + + + jacoco-agent + + prepare-agent + + + + + + maven-surefire-plugin + + ${jvm.args.tests} ${jacoco.agent} + + **/JUnit4SuiteTest.java + + + + + org.apache.maven.surefire + surefire-shadefire + 3.0.0-M7 + + + + + + diff --git a/surefire-extensions-api/src/main/java/org/apache/maven/surefire/extensions/CloseableDaemonThread.java b/surefire-extensions-api/src/main/java/org/apache/maven/surefire/extensions/CloseableDaemonThread.java index f0f32d3229..6136ee692f 100644 --- a/surefire-extensions-api/src/main/java/org/apache/maven/surefire/extensions/CloseableDaemonThread.java +++ b/surefire-extensions-api/src/main/java/org/apache/maven/surefire/extensions/CloseableDaemonThread.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.extensions; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,17 +16,16 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.extensions; import javax.annotation.Nonnull; /** * The base thread class used to handle a stream, transforms the stream to an object. */ -public abstract class CloseableDaemonThread extends Thread implements Stoppable -{ - protected CloseableDaemonThread( @Nonnull String threadName ) - { - setName( threadName ); - setDaemon( true ); +public abstract class CloseableDaemonThread extends Thread implements Stoppable { + protected CloseableDaemonThread(@Nonnull String threadName) { + setName(threadName); + setDaemon(true); } } diff --git a/surefire-extensions-api/src/main/java/org/apache/maven/surefire/extensions/CommandReader.java b/surefire-extensions-api/src/main/java/org/apache/maven/surefire/extensions/CommandReader.java index ecc7282249..8794f07736 100644 --- a/surefire-extensions-api/src/main/java/org/apache/maven/surefire/extensions/CommandReader.java +++ b/surefire-extensions-api/src/main/java/org/apache/maven/surefire/extensions/CommandReader.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.extensions; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,20 +16,20 @@ * specific language governing permissions and limitations * under the License. */ - -import org.apache.maven.surefire.api.booter.Command; +package org.apache.maven.surefire.extensions; import java.io.Closeable; import java.io.IOException; +import org.apache.maven.surefire.api.booter.Command; + /** * Stream reader returns bytes which ar finally sent to the forked jvm. * * @author Tibor Digana (tibor17) * @since 3.0.0-M4 */ -public interface CommandReader extends Closeable -{ +public interface CommandReader extends Closeable { /** * Waits for the next command and returns it. @@ -39,7 +37,9 @@ public interface CommandReader extends Closeable * @return the command, or null if closed */ Command readNextCommand() throws IOException; + @Override void close(); + boolean isClosed(); } diff --git a/surefire-extensions-api/src/main/java/org/apache/maven/surefire/extensions/Completable.java b/surefire-extensions-api/src/main/java/org/apache/maven/surefire/extensions/Completable.java index 30506b2fa0..b9b7ef550a 100644 --- a/surefire-extensions-api/src/main/java/org/apache/maven/surefire/extensions/Completable.java +++ b/surefire-extensions-api/src/main/java/org/apache/maven/surefire/extensions/Completable.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.extensions; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.extensions; import java.io.IOException; @@ -28,14 +27,10 @@ * @author Tibor Digana (tibor17) * @since 3.0.0-M5 */ -public interface Completable -{ - Completable EMPTY_COMPLETABLE = new Completable() - { +public interface Completable { + Completable EMPTY_COMPLETABLE = new Completable() { @Override - public void complete() - { - } + public void complete() {} }; void complete() throws IOException, InterruptedException; diff --git a/surefire-extensions-api/src/main/java/org/apache/maven/surefire/extensions/ConsoleOutputReportEventListener.java b/surefire-extensions-api/src/main/java/org/apache/maven/surefire/extensions/ConsoleOutputReportEventListener.java index ea4a1ed082..9c1c1ea7ec 100644 --- a/surefire-extensions-api/src/main/java/org/apache/maven/surefire/extensions/ConsoleOutputReportEventListener.java +++ b/surefire-extensions-api/src/main/java/org/apache/maven/surefire/extensions/ConsoleOutputReportEventListener.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.extensions; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.extensions; import org.apache.maven.surefire.api.report.TestOutputReportEntry; import org.apache.maven.surefire.api.report.TestSetReportEntry; @@ -29,10 +28,12 @@ * @author Tibor Digana (tibor17) * @since 3.0.0-M4 */ -public interface ConsoleOutputReportEventListener -{ - void testSetStarting( TestSetReportEntry report ); - void testSetCompleted( TestSetReportEntry report ); +public interface ConsoleOutputReportEventListener { + void testSetStarting(TestSetReportEntry report); + + void testSetCompleted(TestSetReportEntry report); + void close(); - void writeTestOutput( TestOutputReportEntry reportEntry ); + + void writeTestOutput(TestOutputReportEntry reportEntry); } diff --git a/surefire-extensions-api/src/main/java/org/apache/maven/surefire/extensions/ConsoleOutputReporter.java b/surefire-extensions-api/src/main/java/org/apache/maven/surefire/extensions/ConsoleOutputReporter.java index ae9d927990..5f32f9b782 100644 --- a/surefire-extensions-api/src/main/java/org/apache/maven/surefire/extensions/ConsoleOutputReporter.java +++ b/surefire-extensions-api/src/main/java/org/apache/maven/surefire/extensions/ConsoleOutputReporter.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.extensions; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.extensions; import java.io.File; import java.io.PrintStream; @@ -31,8 +30,7 @@ * @author Tibor Digana (tibor17) * @since 3.0.0-M4 */ -public abstract class ConsoleOutputReporter -{ +public abstract class ConsoleOutputReporter { /** * {@code false} by default */ @@ -43,30 +41,26 @@ public abstract class ConsoleOutputReporter */ private String encoding; - public abstract ConsoleOutputReportEventListener createListener( File reportsDirectory, String reportNameSuffix, - Integer forkNumber ); + public abstract ConsoleOutputReportEventListener createListener( + File reportsDirectory, String reportNameSuffix, Integer forkNumber); - public abstract ConsoleOutputReportEventListener createListener( PrintStream out, PrintStream err ); + public abstract ConsoleOutputReportEventListener createListener(PrintStream out, PrintStream err); - public abstract Object clone( ClassLoader target ); + public abstract Object clone(ClassLoader target); - public boolean isDisable() - { + public boolean isDisable() { return disable; } - public void setDisable( boolean disable ) - { + public void setDisable(boolean disable) { this.disable = disable; } - public String getEncoding() - { - return isBlank( encoding ) ? "UTF-8" : encoding; + public String getEncoding() { + return isBlank(encoding) ? "UTF-8" : encoding; } - public void setEncoding( String encoding ) - { + public void setEncoding(String encoding) { this.encoding = encoding; } } diff --git a/surefire-extensions-api/src/main/java/org/apache/maven/surefire/extensions/EventHandler.java b/surefire-extensions-api/src/main/java/org/apache/maven/surefire/extensions/EventHandler.java index 7ded309719..a70ef0b9e8 100644 --- a/surefire-extensions-api/src/main/java/org/apache/maven/surefire/extensions/EventHandler.java +++ b/surefire-extensions-api/src/main/java/org/apache/maven/surefire/extensions/EventHandler.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.extensions; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.extensions; import javax.annotation.Nonnull; @@ -26,7 +25,6 @@ * * @param generic type of the event object */ -public interface EventHandler -{ - void handleEvent( @Nonnull T event ); +public interface EventHandler { + void handleEvent(@Nonnull T event); } diff --git a/surefire-extensions-api/src/main/java/org/apache/maven/surefire/extensions/ForkChannel.java b/surefire-extensions-api/src/main/java/org/apache/maven/surefire/extensions/ForkChannel.java index 38d3648244..e9424830f1 100644 --- a/surefire-extensions-api/src/main/java/org/apache/maven/surefire/extensions/ForkChannel.java +++ b/surefire-extensions-api/src/main/java/org/apache/maven/surefire/extensions/ForkChannel.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.extensions; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,17 +16,19 @@ * specific language governing permissions and limitations * under the License. */ - -import org.apache.maven.surefire.api.event.Event; -import org.apache.maven.surefire.api.fork.ForkNodeArguments; -import org.apache.maven.surefire.extensions.util.CountdownCloseable; +package org.apache.maven.surefire.extensions; import javax.annotation.Nonnull; + import java.io.Closeable; import java.io.IOException; import java.nio.channels.ReadableByteChannel; import java.nio.channels.WritableByteChannel; +import org.apache.maven.surefire.api.event.Event; +import org.apache.maven.surefire.api.fork.ForkNodeArguments; +import org.apache.maven.surefire.extensions.util.CountdownCloseable; + /** * It's a session object used only by a particular Thread in ForkStarter * and communicates with a dedicated forked JVM. It represents a server. @@ -41,16 +41,14 @@ * @author Tibor Digana (tibor17) * @since 3.0.0-M5 */ -public abstract class ForkChannel implements Closeable -{ +public abstract class ForkChannel implements Closeable { @Nonnull private final ForkNodeArguments arguments; /** * @param arguments data necessary for command reader and event handler. */ - protected ForkChannel( @Nonnull ForkNodeArguments arguments ) - { + protected ForkChannel(@Nonnull ForkNodeArguments arguments) { this.arguments = arguments; } @@ -82,8 +80,8 @@ protected ForkChannel( @Nonnull ForkNodeArguments arguments ) * @throws IOException if an error in the fork channel * @throws InterruptedException channel interrupted */ - public abstract void bindCommandReader( @Nonnull CommandReader commands, WritableByteChannel stdIn ) - throws IOException, InterruptedException; + public abstract void bindCommandReader(@Nonnull CommandReader commands, WritableByteChannel stdIn) + throws IOException, InterruptedException; /** * Starts a Thread reading the events. @@ -94,14 +92,14 @@ public abstract void bindCommandReader( @Nonnull CommandReader commands, Writabl * @throws IOException if an error in the fork channel * @throws InterruptedException channel interrupted */ - public abstract void bindEventHandler( @Nonnull EventHandler eventHandler, - @Nonnull CountdownCloseable countdownCloseable, - ReadableByteChannel stdOut ) - throws IOException, InterruptedException; + public abstract void bindEventHandler( + @Nonnull EventHandler eventHandler, + @Nonnull CountdownCloseable countdownCloseable, + ReadableByteChannel stdOut) + throws IOException, InterruptedException; @Nonnull - protected ForkNodeArguments getArguments() - { + protected ForkNodeArguments getArguments() { return arguments; } diff --git a/surefire-extensions-api/src/main/java/org/apache/maven/surefire/extensions/ForkNodeFactory.java b/surefire-extensions-api/src/main/java/org/apache/maven/surefire/extensions/ForkNodeFactory.java index 7a529ba091..4207858ce1 100644 --- a/surefire-extensions-api/src/main/java/org/apache/maven/surefire/extensions/ForkNodeFactory.java +++ b/surefire-extensions-api/src/main/java/org/apache/maven/surefire/extensions/ForkNodeFactory.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.extensions; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,20 +16,21 @@ * specific language governing permissions and limitations * under the License. */ - -import org.apache.maven.surefire.api.fork.ForkNodeArguments; +package org.apache.maven.surefire.extensions; import javax.annotation.Nonnull; + import java.io.IOException; +import org.apache.maven.surefire.api.fork.ForkNodeArguments; + /** * This is the plugin extension as a factory of {@link ForkChannel}. * * @author Tibor Digana (tibor17) * @since 3.0.0-M5 */ -public interface ForkNodeFactory -{ +public interface ForkNodeFactory { /** * Opens and closes the channel. * @@ -40,5 +39,5 @@ public interface ForkNodeFactory * @throws IOException if cannot open the channel */ @Nonnull - ForkChannel createForkChannel( @Nonnull ForkNodeArguments arguments ) throws IOException; + ForkChannel createForkChannel(@Nonnull ForkNodeArguments arguments) throws IOException; } diff --git a/surefire-extensions-api/src/main/java/org/apache/maven/surefire/extensions/StatelessReportEventListener.java b/surefire-extensions-api/src/main/java/org/apache/maven/surefire/extensions/StatelessReportEventListener.java index 20eda3bdb8..948c27893e 100644 --- a/surefire-extensions-api/src/main/java/org/apache/maven/surefire/extensions/StatelessReportEventListener.java +++ b/surefire-extensions-api/src/main/java/org/apache/maven/surefire/extensions/StatelessReportEventListener.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.extensions; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.extensions; import org.apache.maven.surefire.api.report.TestSetReportEntry; @@ -31,13 +30,12 @@ * @param report entry type, see WrappedReportEntry from module the maven-surefire-common * @param test-set statistics, see TestSetStats from module the maven-surefire-common */ -public interface StatelessReportEventListener -{ +public interface StatelessReportEventListener { /** * The callback is called after the test class has been completed and the state of report is final. * * @param report WrappedReportEntry * @param testSetStats TestSetStats */ - void testSetCompleted( R report, S testSetStats ); + void testSetCompleted(R report, S testSetStats); } diff --git a/surefire-extensions-api/src/main/java/org/apache/maven/surefire/extensions/StatelessReportMojoConfiguration.java b/surefire-extensions-api/src/main/java/org/apache/maven/surefire/extensions/StatelessReportMojoConfiguration.java index f176fce23b..f0424207a7 100644 --- a/surefire-extensions-api/src/main/java/org/apache/maven/surefire/extensions/StatelessReportMojoConfiguration.java +++ b/surefire-extensions-api/src/main/java/org/apache/maven/surefire/extensions/StatelessReportMojoConfiguration.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.extensions; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.extensions; import java.io.File; @@ -26,8 +25,7 @@ * org.apache.maven.plugin.surefire.report.StatelessXmlReporter. * Signatures can be changed between major, minor versions or milestones. */ -public class StatelessReportMojoConfiguration -{ +public class StatelessReportMojoConfiguration { private final File reportsDirectory; private final String reportNameSuffix; @@ -38,9 +36,12 @@ public class StatelessReportMojoConfiguration private final String xsdSchemaLocation; - public StatelessReportMojoConfiguration( File reportsDirectory, String reportNameSuffix, boolean trimStackTrace, - int rerunFailingTestsCount, String xsdSchemaLocation ) - { + public StatelessReportMojoConfiguration( + File reportsDirectory, + String reportNameSuffix, + boolean trimStackTrace, + int rerunFailingTestsCount, + String xsdSchemaLocation) { this.reportsDirectory = reportsDirectory; this.reportNameSuffix = reportNameSuffix; this.trimStackTrace = trimStackTrace; @@ -48,28 +49,23 @@ public StatelessReportMojoConfiguration( File reportsDirectory, String reportNam this.xsdSchemaLocation = xsdSchemaLocation; } - public File getReportsDirectory() - { + public File getReportsDirectory() { return reportsDirectory; } - public String getReportNameSuffix() - { + public String getReportNameSuffix() { return reportNameSuffix; } - public boolean isTrimStackTrace() - { + public boolean isTrimStackTrace() { return trimStackTrace; } - public int getRerunFailingTestsCount() - { + public int getRerunFailingTestsCount() { return rerunFailingTestsCount; } - public String getXsdSchemaLocation() - { + public String getXsdSchemaLocation() { return xsdSchemaLocation; } } diff --git a/surefire-extensions-api/src/main/java/org/apache/maven/surefire/extensions/StatelessReporter.java b/surefire-extensions-api/src/main/java/org/apache/maven/surefire/extensions/StatelessReporter.java index effb7de733..5d91fca168 100644 --- a/surefire-extensions-api/src/main/java/org/apache/maven/surefire/extensions/StatelessReporter.java +++ b/surefire-extensions-api/src/main/java/org/apache/maven/surefire/extensions/StatelessReporter.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.extensions; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.extensions; import org.apache.maven.surefire.api.report.TestSetReportEntry; @@ -33,12 +32,11 @@ * @param test-set statistics, see TestSetStats from module the maven-surefire-common * @param mojo config, see DefaultStatelessReportMojoConfiguration from maven-surefire-common */ -public abstract class StatelessReporter -{ +public abstract class StatelessReporter { /** * {@code false} by default */ - //todo remove isDisableXmlReport() in AbstractSurefireMojo and use this param instead + // todo remove isDisableXmlReport() in AbstractSurefireMojo and use this param instead private boolean disable; /** @@ -51,37 +49,28 @@ public abstract class StatelessReporter createListener( C configuration ); + public abstract StatelessReportEventListener createListener(C configuration); - public abstract Object clone( ClassLoader target ); + public abstract Object clone(ClassLoader target); - public boolean isDisable() - { + public boolean isDisable() { return disable; } - public void setDisable( boolean disable ) - { + public void setDisable(boolean disable) { this.disable = disable; } - public String getVersion() - { - return isBlank( version ) ? "3.0" : version; + public String getVersion() { + return isBlank(version) ? "3.0" : version; } - public void setVersion( String version ) - { + public void setVersion(String version) { this.version = version; } @Override - public String toString() - { - return getClass().getSimpleName() - + "{" - + "version=" + getVersion() - + ", disable=" + isDisable() - + '}'; + public String toString() { + return getClass().getSimpleName() + "{" + "version=" + getVersion() + ", disable=" + isDisable() + '}'; } } diff --git a/surefire-extensions-api/src/main/java/org/apache/maven/surefire/extensions/StatelessTestsetInfoConsoleReportEventListener.java b/surefire-extensions-api/src/main/java/org/apache/maven/surefire/extensions/StatelessTestsetInfoConsoleReportEventListener.java index e894a416e5..8ca3956a13 100644 --- a/surefire-extensions-api/src/main/java/org/apache/maven/surefire/extensions/StatelessTestsetInfoConsoleReportEventListener.java +++ b/surefire-extensions-api/src/main/java/org/apache/maven/surefire/extensions/StatelessTestsetInfoConsoleReportEventListener.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.extensions; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,12 +16,13 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.extensions; + +import java.util.List; import org.apache.maven.plugin.surefire.log.api.ConsoleLogger; import org.apache.maven.surefire.api.report.TestSetReportEntry; -import java.util.List; - /** * Extension listener for stateless console reporter of test-set. * Signatures can be changed between major, minor versions or milestones. @@ -33,21 +32,20 @@ * @param report entry type, see WrappedReportEntry from module the maven-surefire-common * @param test-set statistics, see TestSetStats from module the maven-surefire-common */ -public abstract class StatelessTestsetInfoConsoleReportEventListener -{ +public abstract class StatelessTestsetInfoConsoleReportEventListener { private final ConsoleLogger logger; - public StatelessTestsetInfoConsoleReportEventListener( ConsoleLogger logger ) - { + public StatelessTestsetInfoConsoleReportEventListener(ConsoleLogger logger) { this.logger = logger; } - public abstract void testSetStarting( TestSetReportEntry report ); - public abstract void testSetCompleted( R report, S testSetStats, List testResults ); + public abstract void testSetStarting(TestSetReportEntry report); + + public abstract void testSetCompleted(R report, S testSetStats, List testResults); + public abstract void reset(); - public ConsoleLogger getConsoleLogger() - { + public ConsoleLogger getConsoleLogger() { return logger; } } diff --git a/surefire-extensions-api/src/main/java/org/apache/maven/surefire/extensions/StatelessTestsetInfoFileReportEventListener.java b/surefire-extensions-api/src/main/java/org/apache/maven/surefire/extensions/StatelessTestsetInfoFileReportEventListener.java index 1eeb672d70..57139030e4 100644 --- a/surefire-extensions-api/src/main/java/org/apache/maven/surefire/extensions/StatelessTestsetInfoFileReportEventListener.java +++ b/surefire-extensions-api/src/main/java/org/apache/maven/surefire/extensions/StatelessTestsetInfoFileReportEventListener.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.extensions; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,13 +16,14 @@ * specific language governing permissions and limitations * under the License. */ - -import org.apache.maven.surefire.api.report.TestSetReportEntry; +package org.apache.maven.surefire.extensions; import java.io.File; import java.nio.charset.Charset; import java.util.List; +import org.apache.maven.surefire.api.report.TestSetReportEntry; + /** * Extension listener for stateless file reporter of test-set. * Signatures can be changed between major, minor versions or milestones. @@ -34,34 +33,29 @@ * @param report entry type, see WrappedReportEntry from module the maven-surefire-common * @param test-set statistics, see TestSetStats from module the maven-surefire-common */ -public abstract class StatelessTestsetInfoFileReportEventListener -{ +public abstract class StatelessTestsetInfoFileReportEventListener { private final File reportsDirectory; private final String reportNameSuffix; private final Charset encoding; - public StatelessTestsetInfoFileReportEventListener( File reportsDirectory, String reportNameSuffix, - Charset encoding ) - { + public StatelessTestsetInfoFileReportEventListener( + File reportsDirectory, String reportNameSuffix, Charset encoding) { this.reportsDirectory = reportsDirectory; this.reportNameSuffix = reportNameSuffix; this.encoding = encoding; } - public abstract void testSetCompleted( R report, S testSetStats, List testResults ); + public abstract void testSetCompleted(R report, S testSetStats, List testResults); - protected File getReportsDirectory() - { + protected File getReportsDirectory() { return reportsDirectory; } - protected String getReportNameSuffix() - { + protected String getReportNameSuffix() { return reportNameSuffix; } - protected Charset getEncoding() - { + protected Charset getEncoding() { return encoding; } } diff --git a/surefire-extensions-api/src/main/java/org/apache/maven/surefire/extensions/StatelessTestsetInfoReporter.java b/surefire-extensions-api/src/main/java/org/apache/maven/surefire/extensions/StatelessTestsetInfoReporter.java index 3bd899ca59..f33cb5335c 100644 --- a/surefire-extensions-api/src/main/java/org/apache/maven/surefire/extensions/StatelessTestsetInfoReporter.java +++ b/surefire-extensions-api/src/main/java/org/apache/maven/surefire/extensions/StatelessTestsetInfoReporter.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.extensions; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,13 +16,14 @@ * specific language governing permissions and limitations * under the License. */ - -import org.apache.maven.plugin.surefire.log.api.ConsoleLogger; -import org.apache.maven.surefire.api.report.TestSetReportEntry; +package org.apache.maven.surefire.extensions; import java.io.File; import java.nio.charset.Charset; +import org.apache.maven.plugin.surefire.log.api.ConsoleLogger; +import org.apache.maven.surefire.api.report.TestSetReportEntry; + /** * Extension listener for stateless file and console reporter of test-set. * Signatures can be changed between major, minor versions or milestones. @@ -34,25 +33,21 @@ * @param report entry type, see WrappedReportEntry from module the maven-surefire-common * @param test-set statistics, see TestSetStats from module the maven-surefire-common */ -public abstract class StatelessTestsetInfoReporter -{ +public abstract class StatelessTestsetInfoReporter { private boolean disable; - public abstract StatelessTestsetInfoConsoleReportEventListener createListener( ConsoleLogger logger ); + public abstract StatelessTestsetInfoConsoleReportEventListener createListener(ConsoleLogger logger); - public abstract StatelessTestsetInfoFileReportEventListener createListener( File reportsDirectory, - String reportNameSuffix, - Charset encoding ); + public abstract StatelessTestsetInfoFileReportEventListener createListener( + File reportsDirectory, String reportNameSuffix, Charset encoding); - public abstract Object clone( ClassLoader target ); + public abstract Object clone(ClassLoader target); - public boolean isDisable() - { + public boolean isDisable() { return disable; } - public void setDisable( boolean disable ) - { + public void setDisable(boolean disable) { this.disable = disable; } } diff --git a/surefire-extensions-api/src/main/java/org/apache/maven/surefire/extensions/Stoppable.java b/surefire-extensions-api/src/main/java/org/apache/maven/surefire/extensions/Stoppable.java index e637b3ecc3..44e3767d3a 100644 --- a/surefire-extensions-api/src/main/java/org/apache/maven/surefire/extensions/Stoppable.java +++ b/surefire-extensions-api/src/main/java/org/apache/maven/surefire/extensions/Stoppable.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.extensions; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,13 +16,13 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.extensions; import java.io.Closeable; /** * Used in {@link CloseableDaemonThread}. */ -public interface Stoppable extends Closeable -{ +public interface Stoppable extends Closeable { void disable(); } diff --git a/surefire-extensions-api/src/main/java/org/apache/maven/surefire/extensions/util/CommandlineExecutor.java b/surefire-extensions-api/src/main/java/org/apache/maven/surefire/extensions/util/CommandlineExecutor.java index 14a055d942..737fd5af14 100644 --- a/surefire-extensions-api/src/main/java/org/apache/maven/surefire/extensions/util/CommandlineExecutor.java +++ b/surefire-extensions-api/src/main/java/org/apache/maven/surefire/extensions/util/CommandlineExecutor.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.extensions.util; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,12 +16,13 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.extensions.util; + +import java.io.Closeable; import org.apache.maven.surefire.shared.utils.cli.CommandLineException; import org.apache.maven.surefire.shared.utils.cli.Commandline; -import java.io.Closeable; - import static org.apache.maven.surefire.shared.utils.cli.ShutdownHookUtils.addShutDownHook; import static org.apache.maven.surefire.shared.utils.cli.ShutdownHookUtils.removeShutdownHook; @@ -58,15 +57,13 @@ * } * } */ -public class CommandlineExecutor implements Closeable -{ +public class CommandlineExecutor implements Closeable { private final Commandline cli; private final CountdownCloseable endOfStreamsCountdown; private Process process; private Thread shutdownHook; - public CommandlineExecutor( Commandline cli, CountdownCloseable endOfStreamsCountdown ) - { + public CommandlineExecutor(Commandline cli, CountdownCloseable endOfStreamsCountdown) { // now the surefire-extension-api is dependent on CLI without casting generic type T to unrelated object // and the user would not use maven-surefire-common nothing but the only surefire-extension-api // because maven-surefire-common is used for MOJO plugin and not the user's extensions. The user does not need @@ -75,54 +72,43 @@ public CommandlineExecutor( Commandline cli, CountdownCloseable endOfStreamsCoun this.endOfStreamsCountdown = endOfStreamsCountdown; } - public CommandlineStreams execute() throws CommandLineException - { + public CommandlineStreams execute() throws CommandLineException { process = cli.execute(); - shutdownHook = new ProcessHook( process ); - addShutDownHook( shutdownHook ); - return new CommandlineStreams( process ); + shutdownHook = new ProcessHook(process); + addShutDownHook(shutdownHook); + return new CommandlineStreams(process); } - public int awaitExit() throws InterruptedException - { - try - { + public int awaitExit() throws InterruptedException { + try { return process.waitFor(); - } - finally - { + } finally { endOfStreamsCountdown.awaitClosed(); } } @Override - public void close() - { - if ( shutdownHook != null ) - { + public void close() { + if (shutdownHook != null) { shutdownHook.run(); - removeShutdownHook( shutdownHook ); + removeShutdownHook(shutdownHook); shutdownHook = null; } } - private static class ProcessHook extends Thread - { + private static class ProcessHook extends Thread { private final Process process; - private ProcessHook( Process process ) - { - super( "cli-shutdown-hook" ); + private ProcessHook(Process process) { + super("cli-shutdown-hook"); this.process = process; - setContextClassLoader( null ); - setDaemon( true ); + setContextClassLoader(null); + setDaemon(true); } /** {@inheritDoc} */ - public void run() - { + public void run() { process.destroy(); } } - } diff --git a/surefire-extensions-api/src/main/java/org/apache/maven/surefire/extensions/util/CommandlineStreams.java b/surefire-extensions-api/src/main/java/org/apache/maven/surefire/extensions/util/CommandlineStreams.java index 634ed64ede..489d106c18 100644 --- a/surefire-extensions-api/src/main/java/org/apache/maven/surefire/extensions/util/CommandlineStreams.java +++ b/surefire-extensions-api/src/main/java/org/apache/maven/surefire/extensions/util/CommandlineStreams.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.extensions.util; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,8 +16,10 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.extensions.util; import javax.annotation.Nonnull; + import java.io.Closeable; import java.io.IOException; import java.io.InputStream; @@ -34,55 +34,45 @@ /** * */ -public final class CommandlineStreams implements Closeable -{ +public final class CommandlineStreams implements Closeable { private final ReadableByteChannel stdOutChannel; private final ReadableByteChannel stdErrChannel; private final WritableByteChannel stdInChannel; private volatile boolean closed; - public CommandlineStreams( @Nonnull Process process ) - { + public CommandlineStreams(@Nonnull Process process) { InputStream stdOutStream = process.getInputStream(); - stdOutChannel = newBufferedChannel( stdOutStream ); + stdOutChannel = newBufferedChannel(stdOutStream); InputStream stdErrStream = process.getErrorStream(); - stdErrChannel = newBufferedChannel( stdErrStream ); + stdErrChannel = newBufferedChannel(stdErrStream); - stdInChannel = newChannel( process.getOutputStream() ); + stdInChannel = newChannel(process.getOutputStream()); } - public ReadableByteChannel getStdOutChannel() - { + public ReadableByteChannel getStdOutChannel() { return stdOutChannel; } - public ReadableByteChannel getStdErrChannel() - { + public ReadableByteChannel getStdErrChannel() { return stdErrChannel; } - public WritableByteChannel getStdInChannel() - { + public WritableByteChannel getStdInChannel() { return stdInChannel; } @Override - public void close() throws IOException - { - if ( closed ) - { + public void close() throws IOException { + if (closed) { return; } - try ( Channel c1 = stdOutChannel; - Channel c2 = stdErrChannel; - Channel c3 = stdInChannel ) - { + try (Channel c1 = stdOutChannel; + Channel c2 = stdErrChannel; + Channel c3 = stdInChannel) { closed = true; - } - catch ( ClosedChannelException e ) - { + } catch (ClosedChannelException e) { // already closed externally } } diff --git a/surefire-extensions-api/src/main/java/org/apache/maven/surefire/extensions/util/CountDownLauncher.java b/surefire-extensions-api/src/main/java/org/apache/maven/surefire/extensions/util/CountDownLauncher.java index 6d0e443b61..6b7ae1430c 100644 --- a/surefire-extensions-api/src/main/java/org/apache/maven/surefire/extensions/util/CountDownLauncher.java +++ b/surefire-extensions-api/src/main/java/org/apache/maven/surefire/extensions/util/CountDownLauncher.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.extensions.util; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.extensions.util; import java.io.IOException; import java.util.concurrent.atomic.AtomicInteger; @@ -28,26 +27,21 @@ * @author Tibor Digana (tibor17) * @since 3.0.0-M5 */ -public abstract class CountDownLauncher -{ +public abstract class CountDownLauncher { private final AtomicInteger countDown; - public CountDownLauncher( int count ) - { - if ( count <= 0 ) - { - throw new IllegalStateException( "count=" + count + " should be greater than zero" ); + public CountDownLauncher(int count) { + if (count <= 0) { + throw new IllegalStateException("count=" + count + " should be greater than zero"); } - countDown = new AtomicInteger( count ); + countDown = new AtomicInteger(count); } protected abstract void job() throws IOException, InterruptedException; - public void countDown() throws IOException, InterruptedException - { - if ( countDown.decrementAndGet() == 0 ) - { + public void countDown() throws IOException, InterruptedException { + if (countDown.decrementAndGet() == 0) { job(); } } diff --git a/surefire-extensions-api/src/main/java/org/apache/maven/surefire/extensions/util/CountdownCloseable.java b/surefire-extensions-api/src/main/java/org/apache/maven/surefire/extensions/util/CountdownCloseable.java index 9818ec9f97..02f7846dfd 100644 --- a/surefire-extensions-api/src/main/java/org/apache/maven/surefire/extensions/util/CountdownCloseable.java +++ b/surefire-extensions-api/src/main/java/org/apache/maven/surefire/extensions/util/CountdownCloseable.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.extensions.util; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,38 +16,32 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.extensions.util; import javax.annotation.Nonnegative; import javax.annotation.Nonnull; + import java.io.Closeable; import java.io.IOException; /** * Decrements {@code countdown} and calls {@code closeable} if reached zero. */ -public final class CountdownCloseable - implements Closeable -{ +public final class CountdownCloseable implements Closeable { private final Closeable closeable; private volatile int countdown; - public CountdownCloseable( @Nonnull Closeable closeable, @Nonnegative int countdown ) - { + public CountdownCloseable(@Nonnull Closeable closeable, @Nonnegative int countdown) { this.closeable = closeable; this.countdown = countdown; } @Override - public synchronized void close() throws IOException - { - if ( --countdown == 0 ) - { - try - { + public synchronized void close() throws IOException { + if (--countdown == 0) { + try { closeable.close(); - } - finally - { + } finally { notifyAll(); } } @@ -60,10 +52,8 @@ public synchronized void close() throws IOException * * @throws InterruptedException see {@link Object#wait()} */ - public synchronized void awaitClosed() throws InterruptedException - { - if ( countdown > 0 ) - { + public synchronized void awaitClosed() throws InterruptedException { + if (countdown > 0) { wait(); } } diff --git a/surefire-extensions-api/src/main/java/org/apache/maven/surefire/extensions/util/LineConsumerThread.java b/surefire-extensions-api/src/main/java/org/apache/maven/surefire/extensions/util/LineConsumerThread.java index 41558f0524..c24d16e0a5 100644 --- a/surefire-extensions-api/src/main/java/org/apache/maven/surefire/extensions/util/LineConsumerThread.java +++ b/surefire-extensions-api/src/main/java/org/apache/maven/surefire/extensions/util/LineConsumerThread.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.extensions.util; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,40 +16,44 @@ * specific language governing permissions and limitations * under the License. */ - -import org.apache.maven.surefire.extensions.CloseableDaemonThread; -import org.apache.maven.surefire.extensions.EventHandler; +package org.apache.maven.surefire.extensions.util; import javax.annotation.Nonnull; + import java.io.IOException; import java.io.InterruptedIOException; import java.nio.channels.ReadableByteChannel; import java.nio.charset.Charset; import java.util.Scanner; +import org.apache.maven.surefire.extensions.CloseableDaemonThread; +import org.apache.maven.surefire.extensions.EventHandler; + /** * */ -public final class LineConsumerThread extends CloseableDaemonThread -{ +public final class LineConsumerThread extends CloseableDaemonThread { private final Charset encoding; private final ReadableByteChannel channel; private final EventHandler eventHandler; private final CountdownCloseable countdownCloseable; private volatile boolean disabled; - public LineConsumerThread( @Nonnull String threadName, - @Nonnull ReadableByteChannel channel, @Nonnull EventHandler eventHandler, - @Nonnull CountdownCloseable countdownCloseable ) - { - this( threadName, channel, eventHandler, countdownCloseable, Charset.defaultCharset() ); + public LineConsumerThread( + @Nonnull String threadName, + @Nonnull ReadableByteChannel channel, + @Nonnull EventHandler eventHandler, + @Nonnull CountdownCloseable countdownCloseable) { + this(threadName, channel, eventHandler, countdownCloseable, Charset.defaultCharset()); } - public LineConsumerThread( @Nonnull String threadName, - @Nonnull ReadableByteChannel channel, @Nonnull EventHandler eventHandler, - @Nonnull CountdownCloseable countdownCloseable, @Nonnull Charset encoding ) - { - super( threadName ); + public LineConsumerThread( + @Nonnull String threadName, + @Nonnull ReadableByteChannel channel, + @Nonnull EventHandler eventHandler, + @Nonnull CountdownCloseable countdownCloseable, + @Nonnull Charset encoding) { + super(threadName); this.channel = channel; this.eventHandler = eventHandler; this.countdownCloseable = countdownCloseable; @@ -59,50 +61,36 @@ public LineConsumerThread( @Nonnull String threadName, } @Override - public void run() - { - try ( Scanner stream = new Scanner( channel, encoding.name() ); - CountdownCloseable c = countdownCloseable; ) - { + public void run() { + try (Scanner stream = new Scanner(channel, encoding.name()); + CountdownCloseable c = countdownCloseable; ) { boolean isError = false; - while ( stream.hasNextLine() ) - { - try - { + while (stream.hasNextLine()) { + try { String line = stream.nextLine(); isError |= stream.ioException() != null; - if ( !isError && !disabled ) - { - eventHandler.handleEvent( line ); + if (!isError && !disabled) { + eventHandler.handleEvent(line); } - } - catch ( IllegalStateException e ) - { + } catch (IllegalStateException e) { isError = true; } } - } - catch ( IOException e ) - { - if ( e instanceof InterruptedIOException || e.getCause() instanceof InterruptedException ) - { + } catch (IOException e) { + if (e instanceof InterruptedIOException || e.getCause() instanceof InterruptedException) { Thread.currentThread().interrupt(); } - } - catch ( IllegalStateException e ) - { + } catch (IllegalStateException e) { // not needed } } - public void disable() - { + public void disable() { disabled = true; } @Override - public void close() throws IOException - { + public void close() throws IOException { channel.close(); } } diff --git a/surefire-extensions-api/src/test/java/org/apache/maven/plugin/surefire/extensions/CommandlineExecutorTest.java b/surefire-extensions-api/src/test/java/org/apache/maven/plugin/surefire/extensions/CommandlineExecutorTest.java index e3197befea..1443947dfc 100644 --- a/surefire-extensions-api/src/test/java/org/apache/maven/plugin/surefire/extensions/CommandlineExecutorTest.java +++ b/surefire-extensions-api/src/test/java/org/apache/maven/plugin/surefire/extensions/CommandlineExecutorTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire.extensions; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,10 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.surefire.extensions; + +import java.io.Closeable; +import java.nio.file.Paths; import org.apache.maven.surefire.extensions.EventHandler; import org.apache.maven.surefire.extensions.util.CommandlineExecutor; @@ -29,9 +31,6 @@ import org.junit.Before; import org.junit.Test; -import java.io.Closeable; -import java.nio.file.Paths; - import static org.apache.maven.surefire.shared.lang3.SystemUtils.IS_OS_WINDOWS; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.util.Files.delete; @@ -42,63 +41,55 @@ /** * */ -public class CommandlineExecutorTest -{ +public class CommandlineExecutorTest { private CommandlineExecutor exec; private CommandlineStreams streams; private String baseDir; private LineConsumerThread out; @Before - public void setUp() throws Exception - { - baseDir = System.getProperty( "user.dir" ); + public void setUp() throws Exception { + baseDir = System.getProperty("user.dir"); - delete( Paths.get( baseDir, "target", "CommandlineExecutorTest" ).toFile() ); + delete(Paths.get(baseDir, "target", "CommandlineExecutorTest").toFile()); - boolean createdDir = Paths.get( baseDir, "target", "CommandlineExecutorTest" ) - .toFile() - .mkdirs(); + boolean createdDir = + Paths.get(baseDir, "target", "CommandlineExecutorTest").toFile().mkdirs(); - assertThat( createdDir ) - .isTrue(); + assertThat(createdDir).isTrue(); - boolean createdFile = Paths.get( baseDir, "target", "CommandlineExecutorTest", "a.txt" ) - .toFile() - .createNewFile(); + boolean createdFile = Paths.get(baseDir, "target", "CommandlineExecutorTest", "a.txt") + .toFile() + .createNewFile(); - assertThat( createdFile ) - .isTrue(); + assertThat(createdFile).isTrue(); } @After - public void tearDown() throws Exception - { - if ( out != null ) - { + public void tearDown() throws Exception { + if (out != null) { out.close(); } exec.close(); streams.close(); - delete( Paths.get( baseDir, "target", "CommandlineExecutorTest" ).toFile() ); + delete(Paths.get(baseDir, "target", "CommandlineExecutorTest").toFile()); } @Test - public void shouldExecuteNativeCommand() throws Exception - { - Closeable closer = mock( Closeable.class ); - Commandline cli = new Commandline( IS_OS_WINDOWS ? "dir" : "ls -la" ); - cli.setWorkingDirectory( Paths.get( baseDir, "target", "CommandlineExecutorTest" ).toFile() ); - CountdownCloseable countdownCloseable = new CountdownCloseable( closer, 1 ); - exec = new CommandlineExecutor( cli, countdownCloseable ); + public void shouldExecuteNativeCommand() throws Exception { + Closeable closer = mock(Closeable.class); + Commandline cli = new Commandline(IS_OS_WINDOWS ? "dir" : "ls -la"); + cli.setWorkingDirectory( + Paths.get(baseDir, "target", "CommandlineExecutorTest").toFile()); + CountdownCloseable countdownCloseable = new CountdownCloseable(closer, 1); + exec = new CommandlineExecutor(cli, countdownCloseable); streams = exec.execute(); - @SuppressWarnings( "unchecked" ) - EventHandler consumer = mock( EventHandler.class ); + @SuppressWarnings("unchecked") + EventHandler consumer = mock(EventHandler.class); - out = new LineConsumerThread( "std-out-fork-1", streams.getStdOutChannel(), consumer, countdownCloseable ); + out = new LineConsumerThread("std-out-fork-1", streams.getStdOutChannel(), consumer, countdownCloseable); out.start(); exec.awaitExit(); - verify( consumer ) - .handleEvent( contains( "a.txt" ) ); + verify(consumer).handleEvent(contains("a.txt")); } } diff --git a/surefire-extensions-api/src/test/java/org/apache/maven/plugin/surefire/extensions/JUnit4SuiteTest.java b/surefire-extensions-api/src/test/java/org/apache/maven/plugin/surefire/extensions/JUnit4SuiteTest.java index a8464a4083..d17e9a6643 100644 --- a/surefire-extensions-api/src/test/java/org/apache/maven/plugin/surefire/extensions/JUnit4SuiteTest.java +++ b/surefire-extensions-api/src/test/java/org/apache/maven/plugin/surefire/extensions/JUnit4SuiteTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire.extensions; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.surefire.extensions; import junit.framework.JUnit4TestAdapter; import junit.framework.Test; @@ -27,12 +26,10 @@ /** * */ -public class JUnit4SuiteTest extends TestCase -{ - public static Test suite() - { +public class JUnit4SuiteTest extends TestCase { + public static Test suite() { TestSuite suite = new TestSuite(); - suite.addTest( new JUnit4TestAdapter( CommandlineExecutorTest.class ) ); + suite.addTest(new JUnit4TestAdapter(CommandlineExecutorTest.class)); return suite; } } diff --git a/surefire-extensions-spi/pom.xml b/surefire-extensions-spi/pom.xml index 5f610cb3bd..ddcfffa665 100644 --- a/surefire-extensions-spi/pom.xml +++ b/surefire-extensions-spi/pom.xml @@ -18,28 +18,28 @@ ~ under the License. --> - 4.0.0 + 4.0.0 - - org.apache.maven.surefire - surefire - 3.0.0-M10-SNAPSHOT - + + org.apache.maven.surefire + surefire + 3.0.0-M10-SNAPSHOT + - surefire-extensions-spi - Surefire Extensions SPI + surefire-extensions-spi + Surefire Extensions SPI - - - org.apache.maven.surefire - surefire-api - ${project.version} - - - com.google.code.findbugs - jsr305 - provided - - + + + org.apache.maven.surefire + surefire-api + ${project.version} + + + com.google.code.findbugs + jsr305 + provided + + diff --git a/surefire-extensions-spi/src/main/java/org/apache/maven/surefire/spi/MasterProcessChannelProcessorFactory.java b/surefire-extensions-spi/src/main/java/org/apache/maven/surefire/spi/MasterProcessChannelProcessorFactory.java index 486349b333..fd77010c80 100644 --- a/surefire-extensions-spi/src/main/java/org/apache/maven/surefire/spi/MasterProcessChannelProcessorFactory.java +++ b/surefire-extensions-spi/src/main/java/org/apache/maven/surefire/spi/MasterProcessChannelProcessorFactory.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.spi; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,27 +16,28 @@ * specific language governing permissions and limitations * under the License. */ - -import org.apache.maven.surefire.api.booter.MasterProcessChannelDecoder; -import org.apache.maven.surefire.api.booter.MasterProcessChannelEncoder; -import org.apache.maven.surefire.api.fork.ForkNodeArguments; +package org.apache.maven.surefire.spi; import javax.annotation.Nonnull; + import java.io.Closeable; import java.io.IOException; +import org.apache.maven.surefire.api.booter.MasterProcessChannelDecoder; +import org.apache.maven.surefire.api.booter.MasterProcessChannelEncoder; +import org.apache.maven.surefire.api.fork.ForkNodeArguments; + /** * The SPI interface, a factory of an encoder and a decoder. */ -public interface MasterProcessChannelProcessorFactory extends Closeable -{ +public interface MasterProcessChannelProcessorFactory extends Closeable { /** * Evaluates the {@code channelConfig}. * * @param channelConfig a connection string used by the fork JVM * @return {@code true} if {@code channelConfig} is applicable and thus this SPI is eligible in the fork */ - boolean canUse( String channelConfig ); + boolean canUse(String channelConfig); /** * Open a new connection. @@ -46,19 +45,19 @@ public interface MasterProcessChannelProcessorFactory extends Closeable * @param channelConfig e.g. "pipe://3" or "tcp://localhost:65035" * @throws IOException if cannot connect */ - void connect( String channelConfig ) throws IOException; + void connect(String channelConfig) throws IOException; /** * Decoder factory method. * @param forkingArguments forking arguments * @return a new instance of decoder */ - MasterProcessChannelDecoder createDecoder( @Nonnull ForkNodeArguments forkingArguments ) throws IOException; + MasterProcessChannelDecoder createDecoder(@Nonnull ForkNodeArguments forkingArguments) throws IOException; /** * Encoder factory method. * @param forkingArguments forking arguments * @return a new instance of encoder */ - MasterProcessChannelEncoder createEncoder( @Nonnull ForkNodeArguments forkingArguments ) throws IOException; + MasterProcessChannelEncoder createEncoder(@Nonnull ForkNodeArguments forkingArguments) throws IOException; } diff --git a/surefire-grouper/pom.xml b/surefire-grouper/pom.xml index 9b4d1af301..2d3b5cb132 100644 --- a/surefire-grouper/pom.xml +++ b/surefire-grouper/pom.xml @@ -17,7 +17,6 @@ ~ specific language governing permissions and limitations ~ under the License. --> - 4.0.0 @@ -38,6 +37,13 @@ org.javacc.plugin javacc-maven-plugin 3.0.3 + + + net.java.dev.javacc + javacc + 7.0.12 + + javacc @@ -46,17 +52,13 @@ - - - net.java.dev.javacc - javacc - 7.0.12 - - org.jacoco jacoco-maven-plugin + + jacoco.agent + jacoco-agent @@ -65,9 +67,6 @@ - - jacoco.agent - maven-surefire-plugin @@ -78,7 +77,8 @@ org.apache.maven.surefire surefire-shadefire - 3.0.0-M7 + 3.0.0-M7 + diff --git a/surefire-grouper/src/main/java/org/apache/maven/surefire/group/match/AndGroupMatcher.java b/surefire-grouper/src/main/java/org/apache/maven/surefire/group/match/AndGroupMatcher.java index e9adb22b5f..e50a328c60 100644 --- a/surefire-grouper/src/main/java/org/apache/maven/surefire/group/match/AndGroupMatcher.java +++ b/surefire-grouper/src/main/java/org/apache/maven/surefire/group/match/AndGroupMatcher.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.group.match; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.group.match; import java.util.Collection; @@ -25,34 +24,25 @@ * AND group matcher * */ -public class AndGroupMatcher - extends JoinGroupMatcher -{ +public class AndGroupMatcher extends JoinGroupMatcher { - public AndGroupMatcher( GroupMatcher... matchers ) - { - for ( GroupMatcher matcher : matchers ) - { - addMatcher( matcher ); + public AndGroupMatcher(GroupMatcher... matchers) { + for (GroupMatcher matcher : matchers) { + addMatcher(matcher); } } - public AndGroupMatcher( Collection matchers ) - { - for ( GroupMatcher matcher : matchers ) - { - addMatcher( matcher ); + public AndGroupMatcher(Collection matchers) { + for (GroupMatcher matcher : matchers) { + addMatcher(matcher); } } @Override - public boolean enabled( Class... cats ) - { - for ( GroupMatcher matcher : getMatchers() ) - { - boolean result = matcher.enabled( cats ); - if ( !result ) - { + public boolean enabled(Class... cats) { + for (GroupMatcher matcher : getMatchers()) { + boolean result = matcher.enabled(cats); + if (!result) { return false; } } @@ -61,13 +51,10 @@ public boolean enabled( Class... cats ) } @Override - public boolean enabled( String... cats ) - { - for ( GroupMatcher matcher : getMatchers() ) - { - boolean result = matcher.enabled( cats ); - if ( !result ) - { + public boolean enabled(String... cats) { + for (GroupMatcher matcher : getMatchers()) { + boolean result = matcher.enabled(cats); + if (!result) { return false; } } @@ -76,51 +63,41 @@ public boolean enabled( String... cats ) } @Override - public String toString() - { + public String toString() { StringBuilder sb = new StringBuilder(); - for ( GroupMatcher matcher : getMatchers() ) - { - if ( sb.length() > 0 ) - { - sb.append( " AND " ); + for (GroupMatcher matcher : getMatchers()) { + if (sb.length() > 0) { + sb.append(" AND "); } - sb.append( matcher ); + sb.append(matcher); } return sb.toString(); } @Override - public int hashCode() - { + public int hashCode() { final int prime = 31; int result = 1; result = prime * result; - for ( GroupMatcher matcher : getMatchers() ) - { + for (GroupMatcher matcher : getMatchers()) { result += matcher.hashCode(); } return result; } @Override - public boolean equals( Object obj ) - { - if ( this == obj ) - { + public boolean equals(Object obj) { + if (this == obj) { return true; } - if ( obj == null ) - { + if (obj == null) { return false; } - if ( getClass() != obj.getClass() ) - { + if (getClass() != obj.getClass()) { return false; } AndGroupMatcher other = (AndGroupMatcher) obj; - return getMatchers().equals( other.getMatchers() ); + return getMatchers().equals(other.getMatchers()); } - } diff --git a/surefire-grouper/src/main/java/org/apache/maven/surefire/group/match/GroupMatcher.java b/surefire-grouper/src/main/java/org/apache/maven/surefire/group/match/GroupMatcher.java index 5a75b3f3e9..7165addf2b 100644 --- a/surefire-grouper/src/main/java/org/apache/maven/surefire/group/match/GroupMatcher.java +++ b/surefire-grouper/src/main/java/org/apache/maven/surefire/group/match/GroupMatcher.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.group.match; /* @@ -23,13 +41,11 @@ * Group Matcher * */ -public interface GroupMatcher -{ - - void loadGroupClasses( ClassLoader cloader ); +public interface GroupMatcher { - boolean enabled( Class... cats ); + void loadGroupClasses(ClassLoader cloader); - boolean enabled( String... cats ); + boolean enabled(Class... cats); + boolean enabled(String... cats); } diff --git a/surefire-grouper/src/main/java/org/apache/maven/surefire/group/match/InverseGroupMatcher.java b/surefire-grouper/src/main/java/org/apache/maven/surefire/group/match/InverseGroupMatcher.java index 2028b1bca1..a349790ea7 100644 --- a/surefire-grouper/src/main/java/org/apache/maven/surefire/group/match/InverseGroupMatcher.java +++ b/surefire-grouper/src/main/java/org/apache/maven/surefire/group/match/InverseGroupMatcher.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.group.match; /* @@ -19,80 +37,63 @@ * under the License. */ - /** * Inverse group matcher * */ -public class InverseGroupMatcher - implements GroupMatcher -{ +public class InverseGroupMatcher implements GroupMatcher { private final GroupMatcher matcher; - public InverseGroupMatcher( GroupMatcher matcher ) - { + public InverseGroupMatcher(GroupMatcher matcher) { this.matcher = matcher; } @Override - public boolean enabled( Class... cats ) - { - return cats == null || !matcher.enabled( cats ); + public boolean enabled(Class... cats) { + return cats == null || !matcher.enabled(cats); } @Override - public boolean enabled( String... cats ) - { - return cats == null || !matcher.enabled( cats ); + public boolean enabled(String... cats) { + return cats == null || !matcher.enabled(cats); } @Override - public String toString() - { + public String toString() { return "NOT " + matcher; } @Override - public int hashCode() - { + public int hashCode() { final int prime = 31; int result = 1; - result = prime * result + ( matcher == null ? 0 : matcher.hashCode() ); + result = prime * result + (matcher == null ? 0 : matcher.hashCode()); return result; } @Override - public boolean equals( Object obj ) - { - if ( this == obj ) - { + public boolean equals(Object obj) { + if (this == obj) { return true; } - if ( obj == null || getClass() != obj.getClass() ) - { + if (obj == null || getClass() != obj.getClass()) { return false; } InverseGroupMatcher other = (InverseGroupMatcher) obj; - if ( matcher == null ) - { - if ( other.matcher != null ) - { + if (matcher == null) { + if (other.matcher != null) { return false; } - } - else if ( !matcher.equals( other.matcher ) ) - { + } else if (!matcher.equals(other.matcher)) { return false; } return true; } @Override - public void loadGroupClasses( ClassLoader cloader ) - { - matcher.loadGroupClasses( cloader ); + public void loadGroupClasses(ClassLoader cloader) { + matcher.loadGroupClasses(cloader); } - } diff --git a/surefire-grouper/src/main/java/org/apache/maven/surefire/group/match/JoinGroupMatcher.java b/surefire-grouper/src/main/java/org/apache/maven/surefire/group/match/JoinGroupMatcher.java index 478b3c0038..4180e0e166 100644 --- a/surefire-grouper/src/main/java/org/apache/maven/surefire/group/match/JoinGroupMatcher.java +++ b/surefire-grouper/src/main/java/org/apache/maven/surefire/group/match/JoinGroupMatcher.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.group.match; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.group.match; import java.util.HashSet; import java.util.Set; @@ -26,29 +25,22 @@ * Joins several group matchers * */ -public abstract class JoinGroupMatcher - implements GroupMatcher -{ +public abstract class JoinGroupMatcher implements GroupMatcher { Set matchers = new HashSet<>(); - public final boolean addMatcher( GroupMatcher matcher ) - { - return matchers.add( matcher ); + public final boolean addMatcher(GroupMatcher matcher) { + return matchers.add(matcher); } - protected final Set getMatchers() - { + protected final Set getMatchers() { return matchers; } @Override - public void loadGroupClasses( ClassLoader cloader ) - { - for ( GroupMatcher matcher : matchers ) - { - matcher.loadGroupClasses( cloader ); + public void loadGroupClasses(ClassLoader cloader) { + for (GroupMatcher matcher : matchers) { + matcher.loadGroupClasses(cloader); } } - } diff --git a/surefire-grouper/src/main/java/org/apache/maven/surefire/group/match/OrGroupMatcher.java b/surefire-grouper/src/main/java/org/apache/maven/surefire/group/match/OrGroupMatcher.java index 631086e913..92dddbadc3 100644 --- a/surefire-grouper/src/main/java/org/apache/maven/surefire/group/match/OrGroupMatcher.java +++ b/surefire-grouper/src/main/java/org/apache/maven/surefire/group/match/OrGroupMatcher.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.group.match; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.group.match; import java.util.Collection; @@ -25,34 +24,25 @@ * OR group matcher * */ -public class OrGroupMatcher - extends JoinGroupMatcher -{ +public class OrGroupMatcher extends JoinGroupMatcher { - public OrGroupMatcher( GroupMatcher... matchers ) - { - for ( GroupMatcher matcher : matchers ) - { - addMatcher( matcher ); + public OrGroupMatcher(GroupMatcher... matchers) { + for (GroupMatcher matcher : matchers) { + addMatcher(matcher); } } - public OrGroupMatcher( Collection matchers ) - { - for ( GroupMatcher matcher : matchers ) - { - addMatcher( matcher ); + public OrGroupMatcher(Collection matchers) { + for (GroupMatcher matcher : matchers) { + addMatcher(matcher); } } @Override - public boolean enabled( Class... cats ) - { - for ( GroupMatcher matcher : getMatchers() ) - { - boolean result = matcher.enabled( cats ); - if ( result ) - { + public boolean enabled(Class... cats) { + for (GroupMatcher matcher : getMatchers()) { + boolean result = matcher.enabled(cats); + if (result) { return true; } } @@ -61,13 +51,10 @@ public boolean enabled( Class... cats ) } @Override - public boolean enabled( String... cats ) - { - for ( GroupMatcher matcher : getMatchers() ) - { - boolean result = matcher.enabled( cats ); - if ( result ) - { + public boolean enabled(String... cats) { + for (GroupMatcher matcher : getMatchers()) { + boolean result = matcher.enabled(cats); + if (result) { return true; } } @@ -76,50 +63,41 @@ public boolean enabled( String... cats ) } @Override - public String toString() - { + public String toString() { StringBuilder sb = new StringBuilder(); - for ( GroupMatcher matcher : getMatchers() ) - { - if ( sb.length() > 0 ) - { - sb.append( " OR " ); + for (GroupMatcher matcher : getMatchers()) { + if (sb.length() > 0) { + sb.append(" OR "); } - sb.append( matcher ); + sb.append(matcher); } return sb.toString(); } @Override - public int hashCode() - { + public int hashCode() { final int prime = 37; int result = 1; result = prime * result; - for ( GroupMatcher matcher : getMatchers() ) - { + for (GroupMatcher matcher : getMatchers()) { result += matcher.hashCode(); } return result; } @Override - public boolean equals( Object obj ) - { - if ( this == obj ) - { + public boolean equals(Object obj) { + if (this == obj) { return true; } - if ( obj == null ) - { + if (obj == null) { return false; } - if ( getClass() != obj.getClass() ) - { + if (getClass() != obj.getClass()) { return false; } AndGroupMatcher other = (AndGroupMatcher) obj; - return getMatchers().equals( other.getMatchers() ); + return getMatchers().equals(other.getMatchers()); } } diff --git a/surefire-grouper/src/main/java/org/apache/maven/surefire/group/match/SingleGroupMatcher.java b/surefire-grouper/src/main/java/org/apache/maven/surefire/group/match/SingleGroupMatcher.java index 7f5f2472fe..750cbd0662 100644 --- a/surefire-grouper/src/main/java/org/apache/maven/surefire/group/match/SingleGroupMatcher.java +++ b/surefire-grouper/src/main/java/org/apache/maven/surefire/group/match/SingleGroupMatcher.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.group.match; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.group.match; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; @@ -26,32 +25,25 @@ * Single group matcher * */ -public class SingleGroupMatcher - implements GroupMatcher -{ +public class SingleGroupMatcher implements GroupMatcher { private final String enabled; private final Pattern pattern; private Class enabledClass; - public SingleGroupMatcher( String enabled ) - { - this.enabled = enabled.endsWith( ".class" ) ? enabled.substring( 0, enabled.length() - 6 ) : enabled; + public SingleGroupMatcher(String enabled) { + this.enabled = enabled.endsWith(".class") ? enabled.substring(0, enabled.length() - 6) : enabled; Pattern p; - try - { - p = Pattern.compile( enabled ); - } - catch ( PatternSyntaxException e ) - { + try { + p = Pattern.compile(enabled); + } catch (PatternSyntaxException e) { p = null; } pattern = p; } @Override - public int hashCode() - { + public int hashCode() { final int prime = 31; int result = 1; result = prime * result + enabled.hashCode(); @@ -59,45 +51,35 @@ public int hashCode() } @Override - public boolean equals( Object obj ) - { - if ( this == obj ) - { + public boolean equals(Object obj) { + if (this == obj) { return true; } - if ( obj == null ) - { + if (obj == null) { return false; } - if ( getClass() != obj.getClass() ) - { + if (getClass() != obj.getClass()) { return false; } SingleGroupMatcher other = (SingleGroupMatcher) obj; - return enabled.equals( other.enabled ); + return enabled.equals(other.enabled); } @Override - public String toString() - { + public String toString() { return "*" + enabled; } @Override - public boolean enabled( Class... cats ) - { - if ( cats != null ) - { - for ( Class cls : cats ) - { - if ( enabledClass != null && enabledClass.isAssignableFrom( cls ) ) - { + public boolean enabled(Class... cats) { + if (cats != null) { + for (Class cls : cats) { + if (enabledClass != null && enabledClass.isAssignableFrom(cls)) { return true; } String name = cls.getName(); - if ( name.endsWith( enabled ) ) - { + if (name.endsWith(enabled)) { return true; } } @@ -107,22 +89,17 @@ public boolean enabled( Class... cats ) } @Override - public boolean enabled( String... cats ) - { - for ( String cat : cats ) - { - if ( cat == null || cat.trim().isEmpty() ) - { + public boolean enabled(String... cats) { + for (String cat : cats) { + if (cat == null || cat.trim().isEmpty()) { continue; } - if ( cat.equals( enabled ) ) - { + if (cat.equals(enabled)) { return true; } - if ( pattern != null && pattern.matcher( cat ).matches() ) - { + if (pattern != null && pattern.matcher(cat).matches()) { return true; } } @@ -131,18 +108,14 @@ public boolean enabled( String... cats ) } @Override - public void loadGroupClasses( ClassLoader classLoader ) - { - try - { - enabledClass = classLoader.loadClass( enabled ); - } - catch ( ClassNotFoundException e ) - { + public void loadGroupClasses(ClassLoader classLoader) { + try { + enabledClass = classLoader.loadClass(enabled); + } catch (ClassNotFoundException e) { // class is not available at runtime, for instance this would happen in reactor projects // in which not all modules have the required class on the classpath/module path - System.out.println( "[WARNING] Couldn't load group class '" + enabled + "' in Surefire|Failsafe plugin. " - + "The group class is ignored!" ); + System.out.println("[WARNING] Couldn't load group class '" + enabled + "' in Surefire|Failsafe plugin. " + + "The group class is ignored!"); } } } diff --git a/surefire-grouper/src/test/java/org/apache/maven/surefire/group/match/AndGroupMatcherTest.java b/surefire-grouper/src/test/java/org/apache/maven/surefire/group/match/AndGroupMatcherTest.java index d9c8baf8bd..1ff75d3453 100644 --- a/surefire-grouper/src/test/java/org/apache/maven/surefire/group/match/AndGroupMatcherTest.java +++ b/surefire-grouper/src/test/java/org/apache/maven/surefire/group/match/AndGroupMatcherTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.group.match; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,38 +16,36 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.group.match; import junit.framework.TestCase; /** * */ -public class AndGroupMatcherTest - extends TestCase -{ +public class AndGroupMatcherTest extends TestCase { - public void testDontMatchOneInGroup() - { - AndGroupMatcher matcher = new AndGroupMatcher( new SingleGroupMatcher( SingleGroupMatcher.class.getName() ), - new SingleGroupMatcher( InverseGroupMatcher.class.getName() ) ); + public void testDontMatchOneInGroup() { + AndGroupMatcher matcher = new AndGroupMatcher( + new SingleGroupMatcher(SingleGroupMatcher.class.getName()), + new SingleGroupMatcher(InverseGroupMatcher.class.getName())); - assertFalse( matcher.enabled( InverseGroupMatcher.class, AndGroupMatcher.class ) ); + assertFalse(matcher.enabled(InverseGroupMatcher.class, AndGroupMatcher.class)); } - public void testMatchBothInGroup() - { - AndGroupMatcher matcher = new AndGroupMatcher( new SingleGroupMatcher( SingleGroupMatcher.class.getName() ), - new SingleGroupMatcher( InverseGroupMatcher.class.getName() ) ); + public void testMatchBothInGroup() { + AndGroupMatcher matcher = new AndGroupMatcher( + new SingleGroupMatcher(SingleGroupMatcher.class.getName()), + new SingleGroupMatcher(InverseGroupMatcher.class.getName())); - assertTrue( matcher.enabled( InverseGroupMatcher.class, SingleGroupMatcher.class ) ); + assertTrue(matcher.enabled(InverseGroupMatcher.class, SingleGroupMatcher.class)); } - public void testDontMatchAnyInGroup() - { - AndGroupMatcher matcher = new AndGroupMatcher( new SingleGroupMatcher( SingleGroupMatcher.class.getName() ), - new SingleGroupMatcher( InverseGroupMatcher.class.getName() ) ); + public void testDontMatchAnyInGroup() { + AndGroupMatcher matcher = new AndGroupMatcher( + new SingleGroupMatcher(SingleGroupMatcher.class.getName()), + new SingleGroupMatcher(InverseGroupMatcher.class.getName())); - assertFalse( matcher.enabled( OrGroupMatcher.class, AndGroupMatcher.class ) ); + assertFalse(matcher.enabled(OrGroupMatcher.class, AndGroupMatcher.class)); } - } diff --git a/surefire-grouper/src/test/java/org/apache/maven/surefire/group/match/InverseGroupMatcherTest.java b/surefire-grouper/src/test/java/org/apache/maven/surefire/group/match/InverseGroupMatcherTest.java index 23ecc3591e..c60bb2ea81 100644 --- a/surefire-grouper/src/test/java/org/apache/maven/surefire/group/match/InverseGroupMatcherTest.java +++ b/surefire-grouper/src/test/java/org/apache/maven/surefire/group/match/InverseGroupMatcherTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.group.match; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,21 +16,18 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.group.match; import junit.framework.TestCase; /** * */ -public class InverseGroupMatcherTest - extends TestCase -{ +public class InverseGroupMatcherTest extends TestCase { - public void testInvertSingleMatcher() - { + public void testInvertSingleMatcher() { InverseGroupMatcher matcher = - new InverseGroupMatcher( new SingleGroupMatcher( InverseGroupMatcher.class.getName() ) ); - assertFalse( matcher.enabled( InverseGroupMatcher.class ) ); + new InverseGroupMatcher(new SingleGroupMatcher(InverseGroupMatcher.class.getName())); + assertFalse(matcher.enabled(InverseGroupMatcher.class)); } - } diff --git a/surefire-grouper/src/test/java/org/apache/maven/surefire/group/match/OrGroupMatcherTest.java b/surefire-grouper/src/test/java/org/apache/maven/surefire/group/match/OrGroupMatcherTest.java index 48feb36292..2e8183a468 100644 --- a/surefire-grouper/src/test/java/org/apache/maven/surefire/group/match/OrGroupMatcherTest.java +++ b/surefire-grouper/src/test/java/org/apache/maven/surefire/group/match/OrGroupMatcherTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.group.match; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,38 +16,36 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.group.match; import junit.framework.TestCase; /** * */ -public class OrGroupMatcherTest - extends TestCase -{ +public class OrGroupMatcherTest extends TestCase { - public void testMatchOneInOredGroup() - { - OrGroupMatcher matcher = new OrGroupMatcher( new SingleGroupMatcher( SingleGroupMatcher.class.getName() ), - new SingleGroupMatcher( InverseGroupMatcher.class.getName() ) ); + public void testMatchOneInOredGroup() { + OrGroupMatcher matcher = new OrGroupMatcher( + new SingleGroupMatcher(SingleGroupMatcher.class.getName()), + new SingleGroupMatcher(InverseGroupMatcher.class.getName())); - assertTrue( matcher.enabled( InverseGroupMatcher.class, AndGroupMatcher.class ) ); + assertTrue(matcher.enabled(InverseGroupMatcher.class, AndGroupMatcher.class)); } - public void testMatchBothInOredGroup() - { - OrGroupMatcher matcher = new OrGroupMatcher( new SingleGroupMatcher( SingleGroupMatcher.class.getName() ), - new SingleGroupMatcher( InverseGroupMatcher.class.getName() ) ); + public void testMatchBothInOredGroup() { + OrGroupMatcher matcher = new OrGroupMatcher( + new SingleGroupMatcher(SingleGroupMatcher.class.getName()), + new SingleGroupMatcher(InverseGroupMatcher.class.getName())); - assertTrue( matcher.enabled( InverseGroupMatcher.class, SingleGroupMatcher.class ) ); + assertTrue(matcher.enabled(InverseGroupMatcher.class, SingleGroupMatcher.class)); } - public void testMatchNoneInOredGroup() - { - OrGroupMatcher matcher = new OrGroupMatcher( new SingleGroupMatcher( SingleGroupMatcher.class.getName() ), - new SingleGroupMatcher( InverseGroupMatcher.class.getName() ) ); + public void testMatchNoneInOredGroup() { + OrGroupMatcher matcher = new OrGroupMatcher( + new SingleGroupMatcher(SingleGroupMatcher.class.getName()), + new SingleGroupMatcher(InverseGroupMatcher.class.getName())); - assertFalse( matcher.enabled( OrGroupMatcher.class, AndGroupMatcher.class ) ); + assertFalse(matcher.enabled(OrGroupMatcher.class, AndGroupMatcher.class)); } - } diff --git a/surefire-grouper/src/test/java/org/apache/maven/surefire/group/match/SingleGroupMatcherTest.java b/surefire-grouper/src/test/java/org/apache/maven/surefire/group/match/SingleGroupMatcherTest.java index b75011f920..34dcbac9c4 100644 --- a/surefire-grouper/src/test/java/org/apache/maven/surefire/group/match/SingleGroupMatcherTest.java +++ b/surefire-grouper/src/test/java/org/apache/maven/surefire/group/match/SingleGroupMatcherTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.group.match; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,40 +16,34 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.group.match; import junit.framework.TestCase; /** * */ -public class SingleGroupMatcherTest - extends TestCase -{ +public class SingleGroupMatcherTest extends TestCase { - public void testMatchExactClassName() - { - SingleGroupMatcher matcher = new SingleGroupMatcher( SingleGroupMatcher.class.getName() ); - assertTrue( matcher.enabled( SingleGroupMatcher.class ) ); + public void testMatchExactClassName() { + SingleGroupMatcher matcher = new SingleGroupMatcher(SingleGroupMatcher.class.getName()); + assertTrue(matcher.enabled(SingleGroupMatcher.class)); } - public void testMatchLoadedClass() - { - SingleGroupMatcher matcher = new SingleGroupMatcher( SingleGroupMatcher.class.getName() ); - matcher.loadGroupClasses( Thread.currentThread().getContextClassLoader() ); - assertTrue( matcher.enabled( SingleGroupMatcher.class ) ); + public void testMatchLoadedClass() { + SingleGroupMatcher matcher = new SingleGroupMatcher(SingleGroupMatcher.class.getName()); + matcher.loadGroupClasses(Thread.currentThread().getContextClassLoader()); + assertTrue(matcher.enabled(SingleGroupMatcher.class)); } - public void testMatchUnknownClass() - { - SingleGroupMatcher matcher = new SingleGroupMatcher( "BadClass" ); - matcher.loadGroupClasses( Thread.currentThread().getContextClassLoader() ); - assertTrue( matcher.enabled( "BadClass" ) ); + public void testMatchUnknownClass() { + SingleGroupMatcher matcher = new SingleGroupMatcher("BadClass"); + matcher.loadGroupClasses(Thread.currentThread().getContextClassLoader()); + assertTrue(matcher.enabled("BadClass")); } - public void testMatchClassNameWithoutPackage() - { - SingleGroupMatcher matcher = new SingleGroupMatcher( SingleGroupMatcher.class.getSimpleName() ); - assertTrue( matcher.enabled( SingleGroupMatcher.class ) ); + public void testMatchClassNameWithoutPackage() { + SingleGroupMatcher matcher = new SingleGroupMatcher(SingleGroupMatcher.class.getSimpleName()); + assertTrue(matcher.enabled(SingleGroupMatcher.class)); } - } diff --git a/surefire-grouper/src/test/java/org/apache/maven/surefire/group/parse/GroupMatcherParserTest.java b/surefire-grouper/src/test/java/org/apache/maven/surefire/group/parse/GroupMatcherParserTest.java index 070caa73c3..248d061a5a 100644 --- a/surefire-grouper/src/test/java/org/apache/maven/surefire/group/parse/GroupMatcherParserTest.java +++ b/surefire-grouper/src/test/java/org/apache/maven/surefire/group/parse/GroupMatcherParserTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.group.parse; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,129 +16,111 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.group.parse; +import junit.framework.TestCase; import org.apache.maven.surefire.group.match.AndGroupMatcher; import org.apache.maven.surefire.group.match.GroupMatcher; import org.apache.maven.surefire.group.match.InverseGroupMatcher; import org.apache.maven.surefire.group.match.OrGroupMatcher; import org.apache.maven.surefire.group.match.SingleGroupMatcher; -import junit.framework.TestCase; - /** * */ -public class GroupMatcherParserTest - extends TestCase -{ - - public void testParseSingleClass() - throws ParseException - { - GroupMatcher matcher = new GroupMatcherParser( GroupMatcherParser.class.getName() ).parse(); - assertTrue( "Wrong matcher type: " + matcher.getClass().getName(), matcher instanceof SingleGroupMatcher ); - assertTrue( matcher.enabled( GroupMatcherParser.class ) ); +public class GroupMatcherParserTest extends TestCase { + + public void testParseSingleClass() throws ParseException { + GroupMatcher matcher = new GroupMatcherParser(GroupMatcherParser.class.getName()).parse(); + assertTrue("Wrong matcher type: " + matcher.getClass().getName(), matcher instanceof SingleGroupMatcher); + assertTrue(matcher.enabled(GroupMatcherParser.class)); } - public void testParseInvertedSingleClass() - throws ParseException - { - GroupMatcher matcher = new GroupMatcherParser( "NOT " + GroupMatcherParser.class.getName() ).parse(); - assertTrue( "Wrong matcher type: " + matcher.getClass().getName(), matcher instanceof InverseGroupMatcher ); - assertFalse( matcher.enabled( GroupMatcherParser.class ) ); + public void testParseInvertedSingleClass() throws ParseException { + GroupMatcher matcher = new GroupMatcherParser("NOT " + GroupMatcherParser.class.getName()).parse(); + assertTrue("Wrong matcher type: " + matcher.getClass().getName(), matcher instanceof InverseGroupMatcher); + assertFalse(matcher.enabled(GroupMatcherParser.class)); } - public void testParseBareANDedPair() - throws ParseException - { + public void testParseBareANDedPair() throws ParseException { GroupMatcher matcher = new GroupMatcherParser( - GroupMatcherParser.class.getName() + " AND " + SingleGroupMatcher.class.getName() ).parse(); + GroupMatcherParser.class.getName() + " AND " + SingleGroupMatcher.class.getName()) + .parse(); - assertTrue( "Wrong matcher type: " + matcher.getClass().getName(), matcher instanceof AndGroupMatcher ); - assertFalse( matcher.enabled( GroupMatcherParser.class ) ); - assertTrue( matcher.enabled( GroupMatcherParser.class, SingleGroupMatcher.class ) ); + assertTrue("Wrong matcher type: " + matcher.getClass().getName(), matcher instanceof AndGroupMatcher); + assertFalse(matcher.enabled(GroupMatcherParser.class)); + assertTrue(matcher.enabled(GroupMatcherParser.class, SingleGroupMatcher.class)); } - public void testParseBareORedPair() - throws ParseException - { + public void testParseBareORedPair() throws ParseException { GroupMatcher matcher = new GroupMatcherParser( - GroupMatcherParser.class.getName() + " OR " + SingleGroupMatcher.class.getName() ).parse(); + GroupMatcherParser.class.getName() + " OR " + SingleGroupMatcher.class.getName()) + .parse(); - assertTrue( "Wrong matcher type: " + matcher.getClass().getName(), matcher instanceof OrGroupMatcher ); - assertTrue( matcher.enabled( GroupMatcherParser.class ) ); - assertTrue( matcher.enabled( GroupMatcherParser.class, SingleGroupMatcher.class ) ); + assertTrue("Wrong matcher type: " + matcher.getClass().getName(), matcher instanceof OrGroupMatcher); + assertTrue(matcher.enabled(GroupMatcherParser.class)); + assertTrue(matcher.enabled(GroupMatcherParser.class, SingleGroupMatcher.class)); } - public void testBareCommaSeparatedORedPair() - throws ParseException - { + public void testBareCommaSeparatedORedPair() throws ParseException { GroupMatcher matcher = new GroupMatcherParser( - GroupMatcherParser.class.getName() + ", " + SingleGroupMatcher.class.getName() ).parse(); + GroupMatcherParser.class.getName() + ", " + SingleGroupMatcher.class.getName()) + .parse(); - assertTrue( "Wrong matcher type: " + matcher.getClass().getName(), matcher instanceof OrGroupMatcher ); - assertTrue( matcher.enabled( GroupMatcherParser.class ) ); - assertTrue( matcher.enabled( GroupMatcherParser.class, SingleGroupMatcher.class ) ); + assertTrue("Wrong matcher type: " + matcher.getClass().getName(), matcher instanceof OrGroupMatcher); + assertTrue(matcher.enabled(GroupMatcherParser.class)); + assertTrue(matcher.enabled(GroupMatcherParser.class, SingleGroupMatcher.class)); } - public void testParseGroupedANDedPair() - throws ParseException - { + public void testParseGroupedANDedPair() throws ParseException { GroupMatcher matcher = new GroupMatcherParser( - "(" + GroupMatcherParser.class.getName() + " AND " + SingleGroupMatcher.class.getName() + ")" ).parse(); + "(" + GroupMatcherParser.class.getName() + " AND " + SingleGroupMatcher.class.getName() + ")") + .parse(); - assertTrue( "Wrong matcher type: " + matcher.getClass().getName(), matcher instanceof AndGroupMatcher ); - assertFalse( matcher.enabled( GroupMatcherParser.class ) ); - assertTrue( matcher.enabled( GroupMatcherParser.class, SingleGroupMatcher.class ) ); + assertTrue("Wrong matcher type: " + matcher.getClass().getName(), matcher instanceof AndGroupMatcher); + assertFalse(matcher.enabled(GroupMatcherParser.class)); + assertTrue(matcher.enabled(GroupMatcherParser.class, SingleGroupMatcher.class)); } - public void testParseGroupedORedPair() - throws ParseException - { + public void testParseGroupedORedPair() throws ParseException { GroupMatcher matcher = new GroupMatcherParser( - "(" + GroupMatcherParser.class.getName() + " OR " + SingleGroupMatcher.class.getName() + ")" ).parse(); + "(" + GroupMatcherParser.class.getName() + " OR " + SingleGroupMatcher.class.getName() + ")") + .parse(); - assertTrue( "Wrong matcher type: " + matcher.getClass().getName(), matcher instanceof OrGroupMatcher ); - assertTrue( matcher.enabled( GroupMatcherParser.class ) ); - assertTrue( matcher.enabled( GroupMatcherParser.class, SingleGroupMatcher.class ) ); + assertTrue("Wrong matcher type: " + matcher.getClass().getName(), matcher instanceof OrGroupMatcher); + assertTrue(matcher.enabled(GroupMatcherParser.class)); + assertTrue(matcher.enabled(GroupMatcherParser.class, SingleGroupMatcher.class)); } - public void testParseInvertedGroupedANDedPair() - throws ParseException - { - GroupMatcher matcher = new GroupMatcherParser( - "NOT (" + GroupMatcherParser.class.getName() + " AND " + SingleGroupMatcher.class.getName() + ")" ).parse(); + public void testParseInvertedGroupedANDedPair() throws ParseException { + GroupMatcher matcher = new GroupMatcherParser("NOT (" + GroupMatcherParser.class.getName() + " AND " + + SingleGroupMatcher.class.getName() + ")") + .parse(); - assertTrue( "Wrong matcher type: " + matcher.getClass().getName(), matcher instanceof InverseGroupMatcher ); - assertTrue( matcher.enabled( GroupMatcherParser.class ) ); - assertFalse( matcher.enabled( GroupMatcherParser.class, SingleGroupMatcher.class ) ); + assertTrue("Wrong matcher type: " + matcher.getClass().getName(), matcher instanceof InverseGroupMatcher); + assertTrue(matcher.enabled(GroupMatcherParser.class)); + assertFalse(matcher.enabled(GroupMatcherParser.class, SingleGroupMatcher.class)); } - public void testParseInvertedGroupedORedPair() - throws ParseException - { - GroupMatcher matcher = new GroupMatcherParser( - "NOT (" + GroupMatcherParser.class.getName() + " OR " + SingleGroupMatcher.class.getName() + ")" ).parse(); + public void testParseInvertedGroupedORedPair() throws ParseException { + GroupMatcher matcher = new GroupMatcherParser("NOT (" + GroupMatcherParser.class.getName() + " OR " + + SingleGroupMatcher.class.getName() + ")") + .parse(); - assertTrue( "Wrong matcher type: " + matcher.getClass().getName(), matcher instanceof InverseGroupMatcher ); - assertFalse( matcher.enabled( GroupMatcherParser.class ) ); - assertFalse( matcher.enabled( GroupMatcherParser.class, SingleGroupMatcher.class ) ); + assertTrue("Wrong matcher type: " + matcher.getClass().getName(), matcher instanceof InverseGroupMatcher); + assertFalse(matcher.enabled(GroupMatcherParser.class)); + assertFalse(matcher.enabled(GroupMatcherParser.class, SingleGroupMatcher.class)); } - public void testSingleMatchWhenDotClassAppended() - throws ParseException - { - GroupMatcher matcher = new GroupMatcherParser( SingleGroupMatcher.class.getName() + ".class" ).parse(); - assertTrue( "Wrong matcher type: " + matcher.getClass().getName(), matcher instanceof SingleGroupMatcher ); - assertTrue( matcher.enabled( SingleGroupMatcher.class ) ); + public void testSingleMatchWhenDotClassAppended() throws ParseException { + GroupMatcher matcher = new GroupMatcherParser(SingleGroupMatcher.class.getName() + ".class").parse(); + assertTrue("Wrong matcher type: " + matcher.getClass().getName(), matcher instanceof SingleGroupMatcher); + assertTrue(matcher.enabled(SingleGroupMatcher.class)); } - public void testSingleMatchWithOnlyClassSimpleName() - throws ParseException - { - GroupMatcher matcher = new GroupMatcherParser( SingleGroupMatcher.class.getSimpleName() ).parse(); - assertTrue( "Wrong matcher type: " + matcher.getClass().getName(), matcher instanceof SingleGroupMatcher ); - assertTrue( matcher.enabled( SingleGroupMatcher.class ) ); + public void testSingleMatchWithOnlyClassSimpleName() throws ParseException { + GroupMatcher matcher = new GroupMatcherParser(SingleGroupMatcher.class.getSimpleName()).parse(); + assertTrue("Wrong matcher type: " + matcher.getClass().getName(), matcher instanceof SingleGroupMatcher); + assertTrue(matcher.enabled(SingleGroupMatcher.class)); } - } diff --git a/surefire-its/pom.xml b/surefire-its/pom.xml index 5994f5db24..e7b1c38813 100644 --- a/surefire-its/pom.xml +++ b/surefire-its/pom.xml @@ -17,207 +17,209 @@ ~ specific language governing permissions and limitations ~ under the License. --> - - 4.0.0 + 4.0.0 + + + org.apache.maven.surefire + surefire + 3.0.0-M10-SNAPSHOT + - - org.apache.maven.surefire - surefire - 3.0.0-M10-SNAPSHOT - + surefire-its - surefire-its + Maven Surefire Integration Tests + Used internally testing MOJOs. The project is not deployed. - Maven Surefire Integration Tests - Used internally testing MOJOs. The project is not deployed. + + UTF-8 + - - UTF-8 - + + + org.apache.maven.surefire + surefire-report-parser + 3.0.0-M7 + test + + + org.apache.maven.shared + maven-verifier + test + + + org.apache.maven + maven-settings + test + + + net.sourceforge.htmlunit + htmlunit + test + + + org.apache.maven + maven-artifact + test + + + org.apache.maven.shared + maven-shared-utils + test + + + commons-io + commons-io + test + + + org.apache.commons + commons-lang3 + test + + - - + + + + ${project.build.outputDirectory} + src/test/resources + + toolchains.xml + + + + ${project.build.directory}/private + true + src/test/resources + + toolchains.xml + + + + + + maven-help-plugin + + + settings.xml + + effective-settings + + generate-test-resources + + ${project.build.directory}/private/settings.xml + false + + + + + + maven-surefire-plugin + + + org/apache/maven/surefire/its/fixture/JUnit4SuiteTest.java + + + ${project.build.directory}/private/settings.xml + + + + org.apache.maven.surefire - surefire-report-parser + surefire-shadefire 3.0.0-M7 - test - - - org.apache.maven.shared - maven-verifier - test - - - org.apache.maven - maven-settings - test - - - net.sourceforge.htmlunit - htmlunit - test - - - org.apache.maven - maven-artifact - test - - - org.apache.maven.shared - maven-shared-utils - test - - - commons-io - commons-io - test - - - org.apache.commons - commons-lang3 - test - - - - - - - src/test/resources - ${project.build.outputDirectory} - - toolchains.xml - - - - src/test/resources - true - ${project.build.directory}/private - - toolchains.xml - - - + + + + + + org.jacoco + jacoco-maven-plugin + + + jacoco-agent + + prepare-agent + + + + jacoco-agent-it + + prepare-agent-integration + + + jacoco-it.agent + ${project.build.directory}/jacoco.exec + + + + + + maven-install-plugin + + true + + + + maven-deploy-plugin + + true + + + + + + + run-its + - - maven-help-plugin - - - settings.xml - generate-test-resources - - effective-settings - - - ${project.build.directory}/private/settings.xml - false - - - - - - maven-surefire-plugin - - - org.apache.maven.surefire - surefire-shadefire - 3.0.0-M7 - - - - - org/apache/maven/surefire/its/fixture/JUnit4SuiteTest.java - - - ${project.build.directory}/private/settings.xml - - - - - org.jacoco - jacoco-maven-plugin - - - jacoco-agent - - prepare-agent - - - - jacoco-agent-it - - prepare-agent-integration - - - jacoco-it.agent - ${project.build.directory}/jacoco.exec - - - - - - maven-install-plugin - - true - - - - maven-deploy-plugin - - true - - + + maven-failsafe-plugin + 3.0.0-M7 + + + ${skipTests} + alphabetical + 1 + false + -server -Xmx64m -XX:+UseG1GC -XX:+TieredCompilation -XX:TieredStopAtLevel=1 -Djava.awt.headless=true -Djdk.net.URLClassPath.disableClassPathURLCheck=true + + org/apache/**/*IT*.java + + + + + ${project.version} + ${maven.home} + ${project.build.directory}/private/settings.xml + ${project.build.directory}/private/toolchains.xml + ${project.build.directory} + forked + ${jacoco-it.agent} + + true + kill + + + + org.apache.maven.surefire + surefire-junit47 + 3.0.0-M7 + + + + + + + integration-test + verify + + + + - - - - run-its - - - - maven-failsafe-plugin - 3.0.0-M7 - - ${skipTests} - alphabetical - 1 - false - -server -Xmx64m -XX:+UseG1GC -XX:+TieredCompilation -XX:TieredStopAtLevel=1 -Djava.awt.headless=true -Djdk.net.URLClassPath.disableClassPathURLCheck=true - - org/apache/**/*IT*.java - - - - - ${project.version} - ${maven.home} - ${project.build.directory}/private/settings.xml - ${project.build.directory}/private/toolchains.xml - ${project.build.directory} - forked - ${jacoco-it.agent} - - true - kill - - - - org.apache.maven.surefire - surefire-junit47 - 3.0.0-M7 - - - - - - integration-test - verify - - - - - - - - + + + diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/AbstractFailFastIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/AbstractFailFastIT.java index 975f18bdfc..f1b59bb3ce 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/AbstractFailFastIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/AbstractFailFastIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its; /* @@ -39,89 +57,80 @@ * @author Tibor Digana (tibor17) * @since 2.19 */ -@RunWith( Parameterized.class ) -public abstract class AbstractFailFastIT - extends SurefireJUnit4IntegrationTestCase -{ - private static final String LEGACY_FORK_NODE = - "org.apache.maven.plugin.surefire.extensions.LegacyForkNodeFactory"; +@RunWith(Parameterized.class) +public abstract class AbstractFailFastIT extends SurefireJUnit4IntegrationTestCase { + private static final String LEGACY_FORK_NODE = "org.apache.maven.plugin.surefire.extensions.LegacyForkNodeFactory"; private static final String SUREFIRE_FORK_NODE = - "org.apache.maven.plugin.surefire.extensions.SurefireForkNodeFactory"; + "org.apache.maven.plugin.surefire.extensions.SurefireForkNodeFactory"; - @Parameter( 0 ) - @SuppressWarnings( "checkstyle:visibilitymodifier" ) + @Parameter(0) + @SuppressWarnings("checkstyle:visibilitymodifier") public String description; - @Parameter( 1 ) - @SuppressWarnings( "checkstyle:visibilitymodifier" ) + @Parameter(1) + @SuppressWarnings("checkstyle:visibilitymodifier") public String profile; - @Parameter( 2 ) - @SuppressWarnings( "checkstyle:visibilitymodifier" ) + @Parameter(2) + @SuppressWarnings("checkstyle:visibilitymodifier") public Map properties; - @Parameter( 3 ) - @SuppressWarnings( "checkstyle:visibilitymodifier" ) + @Parameter(3) + @SuppressWarnings("checkstyle:visibilitymodifier") public int total; - @Parameter( 4 ) - @SuppressWarnings( "checkstyle:visibilitymodifier" ) + @Parameter(4) + @SuppressWarnings("checkstyle:visibilitymodifier") public int failures; - @Parameter( 5 ) - @SuppressWarnings( "checkstyle:visibilitymodifier" ) + @Parameter(5) + @SuppressWarnings("checkstyle:visibilitymodifier") public int errors; - @Parameter( 6 ) - @SuppressWarnings( "checkstyle:visibilitymodifier" ) + @Parameter(6) + @SuppressWarnings("checkstyle:visibilitymodifier") public int skipped; - @Parameter( 7 ) - @SuppressWarnings( "checkstyle:visibilitymodifier" ) + @Parameter(7) + @SuppressWarnings("checkstyle:visibilitymodifier") public boolean useProcessPipes; protected abstract String withProvider(); - private OutputValidator prepare( String description, String profile, Map properties ) - { - MavenLauncher launcher = unpack( "/fail-fast-" + withProvider(), "_" + description ) - .maven() - .debugLogging(); + private OutputValidator prepare(String description, String profile, Map properties) { + MavenLauncher launcher = unpack("/fail-fast-" + withProvider(), "_" + description) + .maven() + .debugLogging(); - if ( profile != null ) - { - launcher.activateProfile( profile ); + if (profile != null) { + launcher.activateProfile(profile); } - if ( !useProcessPipes ) - { - launcher.activateProfile( "tcp" ); + if (!useProcessPipes) { + launcher.activateProfile("tcp"); } - if ( failures != 0 || errors != 0 ) - { + if (failures != 0 || errors != 0) { launcher.withFailure(); } - return launcher.sysProp( properties ).executeTest(); + return launcher.sysProp(properties).executeTest(); } - static Map props( int forkCount, int skipAfterFailureCount, boolean reuseForks ) - { - Map props = new HashMap<>( 3 ); - props.put( "surefire.skipAfterFailureCount", "" + skipAfterFailureCount ); - props.put( "forkCount", "" + forkCount ); - props.put( "reuseForks", "" + reuseForks ); + static Map props(int forkCount, int skipAfterFailureCount, boolean reuseForks) { + Map props = new HashMap<>(3); + props.put("surefire.skipAfterFailureCount", "" + skipAfterFailureCount); + props.put("forkCount", "" + forkCount); + props.put("reuseForks", "" + reuseForks); return props; } @Test - public void test() throws Exception - { + public void test() throws Exception { String cls = useProcessPipes ? LEGACY_FORK_NODE : SUREFIRE_FORK_NODE; - prepare( description, profile, properties ) - .assertTestSuiteResults( total, errors, failures, skipped ) - .assertThatLogLine( containsString( "Found implementation of fork node factory: " + cls ), equalTo( 1 ) ); + prepare(description, profile, properties) + .assertTestSuiteResults(total, errors, failures, skipped) + .assertThatLogLine(containsString("Found implementation of fork node factory: " + cls), equalTo(1)); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/AbstractTestCaseIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/AbstractTestCaseIT.java index 0260ba0a2f..ddd7247317 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/AbstractTestCaseIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/AbstractTestCaseIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its; /* @@ -29,13 +47,9 @@ * @author Dan Fabulich * @author Kristian Rosenvold */ -public class AbstractTestCaseIT - extends SurefireJUnit4IntegrationTestCase -{ +public class AbstractTestCaseIT extends SurefireJUnit4IntegrationTestCase { @Test - public void abstractTestCase() - { - unpack( "/default-configuration-abstract" ).executeTest().verifyErrorFree( 1 ); + public void abstractTestCase() { + unpack("/default-configuration-abstract").executeTest().verifyErrorFree(1); } - } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/AbstractTestMultipleMethodPatterns.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/AbstractTestMultipleMethodPatterns.java index f1a643e29a..36f7147395 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/AbstractTestMultipleMethodPatterns.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/AbstractTestMultipleMethodPatterns.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its; /* @@ -24,13 +42,13 @@ import org.apache.maven.surefire.its.fixture.SurefireLauncher; import org.junit.Test; -import static org.apache.maven.surefire.its.fixture.TestFramework.JUNIT47; -import static org.apache.maven.surefire.its.fixture.TestFramework.TestNG; import static org.apache.maven.surefire.its.fixture.Configuration.INCLUDES; import static org.apache.maven.surefire.its.fixture.Configuration.INCLUDES_EXCLUDES; import static org.apache.maven.surefire.its.fixture.Configuration.INCLUDES_EXCLUDES_FILE; import static org.apache.maven.surefire.its.fixture.Configuration.INCLUDES_FILE; import static org.apache.maven.surefire.its.fixture.Configuration.TEST; +import static org.apache.maven.surefire.its.fixture.TestFramework.JUNIT47; +import static org.apache.maven.surefire.its.fixture.TestFramework.TestNG; import static org.hamcrest.core.AnyOf.anyOf; import static org.hamcrest.core.Is.is; import static org.junit.Assume.assumeThat; @@ -38,9 +56,7 @@ /** * Test project using multiple method patterns, including wildcards in class and method names. */ -public abstract class AbstractTestMultipleMethodPatterns - extends SurefireJUnit4IntegrationTestCase -{ +public abstract class AbstractTestMultipleMethodPatterns extends SurefireJUnit4IntegrationTestCase { private static final String CSV_DELIMITER_SHORT = ","; private static final String CSV_DELIMITER_LONG = ", "; private static final String NOT_DELIMITER = "!"; @@ -49,418 +65,377 @@ public abstract class AbstractTestMultipleMethodPatterns protected abstract SurefireLauncher unpack(); - protected SurefireLauncher prepare( String tests ) - { - SurefireLauncher launcher = unpack().addGoal( "-P " + getSettings().profile() ); - String[] includedExcluded = splitIncludesExcludes( tests ); - switch ( getSettings().getConfiguration() ) - { + protected SurefireLauncher prepare(String tests) { + SurefireLauncher launcher = unpack().addGoal("-P " + getSettings().profile()); + String[] includedExcluded = splitIncludesExcludes(tests); + switch (getSettings().getConfiguration()) { case TEST: - launcher.setTestToRun( tests ); + launcher.setTestToRun(tests); break; case INCLUDES: - launcher.sysProp( "included", tests ); + launcher.sysProp("included", tests); break; case INCLUDES_EXCLUDES: - launcher.sysProp( "included", includedExcluded[0] ); - launcher.sysProp( "excluded", includedExcluded[1] ); + launcher.sysProp("included", includedExcluded[0]); + launcher.sysProp("excluded", includedExcluded[1]); break; default: - throw new IllegalArgumentException( "Unsupported configuration " + getSettings().getConfiguration() ); + throw new IllegalArgumentException( + "Unsupported configuration " + getSettings().getConfiguration()); } return launcher; } - private static String[] splitIncludesExcludes( String patterns ) - { + private static String[] splitIncludesExcludes(String patterns) { String included = ""; String excluded = ""; - for ( String pattern : patterns.split( CSV_DELIMITER_SHORT ) ) - { + for (String pattern : patterns.split(CSV_DELIMITER_SHORT)) { pattern = pattern.trim(); - if ( pattern.startsWith( NOT_DELIMITER ) ) - { - excluded += pattern.substring( NOT_DELIMITER.length() ).trim(); + if (pattern.startsWith(NOT_DELIMITER)) { + excluded += pattern.substring(NOT_DELIMITER.length()).trim(); excluded += CSV_DELIMITER_LONG; - } - else - { + } else { included += pattern; included += CSV_DELIMITER_LONG; } } - return new String[]{ trimEndComma( included ), trimEndComma( excluded ) }; + return new String[] {trimEndComma(included), trimEndComma(excluded)}; } - private static String trimEndComma( String pattern ) - { + private static String trimEndComma(String pattern) { pattern = pattern.trim(); - return pattern.endsWith( CSV_DELIMITER_LONG ) - ? pattern.substring( 0, pattern.length() - CSV_DELIMITER_LONG.length() ) : pattern; + return pattern.endsWith(CSV_DELIMITER_LONG) + ? pattern.substring(0, pattern.length() - CSV_DELIMITER_LONG.length()) + : pattern; } @Test - public void simpleNameTest() - { - prepare( "TestTwo" ) - .executeTest() - .verifyErrorFree( 2 ) - .verifyErrorFreeLog() - .verifyTextInLog( "jiras.surefire745.TestTwo#testSuccessOne" ) - .verifyTextInLog( "jiras.surefire745.TestTwo#testSuccessTwo" ); + public void simpleNameTest() { + prepare("TestTwo") + .executeTest() + .verifyErrorFree(2) + .verifyErrorFreeLog() + .verifyTextInLog("jiras.surefire745.TestTwo#testSuccessOne") + .verifyTextInLog("jiras.surefire745.TestTwo#testSuccessTwo"); } @Test - public void simpleNameTestAsParallel() - { - assumeThat( getSettings().getFramework(), anyOf( is( JUNIT47 ), is( TestNG ) ) ); - prepare( "TestTwo" ) - .parallel( "classes" ) - .useUnlimitedThreads() - .executeTest() - .verifyErrorFree( 2 ) - .verifyErrorFreeLog() - .verifyTextInLog( "jiras.surefire745.TestTwo#testSuccessOne" ) - .verifyTextInLog( "jiras.surefire745.TestTwo#testSuccessTwo" ); + public void simpleNameTestAsParallel() { + assumeThat(getSettings().getFramework(), anyOf(is(JUNIT47), is(TestNG))); + prepare("TestTwo") + .parallel("classes") + .useUnlimitedThreads() + .executeTest() + .verifyErrorFree(2) + .verifyErrorFreeLog() + .verifyTextInLog("jiras.surefire745.TestTwo#testSuccessOne") + .verifyTextInLog("jiras.surefire745.TestTwo#testSuccessTwo"); } @Test - public void simpleNameTestWithJavaExt() - { - prepare( "TestTwo.java" ) - .executeTest() - .verifyErrorFree( 2 ) - .verifyErrorFreeLog() - .verifyTextInLog( "jiras.surefire745.TestTwo#testSuccessOne" ) - .verifyTextInLog( "jiras.surefire745.TestTwo#testSuccessTwo" ); + public void simpleNameTestWithJavaExt() { + prepare("TestTwo.java") + .executeTest() + .verifyErrorFree(2) + .verifyErrorFreeLog() + .verifyTextInLog("jiras.surefire745.TestTwo#testSuccessOne") + .verifyTextInLog("jiras.surefire745.TestTwo#testSuccessTwo"); } @Test - public void simpleNameTestWithWildcardPkg() - { - prepare( "**/TestTwo" ) - .executeTest() - .verifyErrorFree( 2 ) - .verifyErrorFreeLog() - .verifyTextInLog( "jiras.surefire745.TestTwo#testSuccessOne" ) - .verifyTextInLog( "jiras.surefire745.TestTwo#testSuccessTwo" ); + public void simpleNameTestWithWildcardPkg() { + prepare("**/TestTwo") + .executeTest() + .verifyErrorFree(2) + .verifyErrorFreeLog() + .verifyTextInLog("jiras.surefire745.TestTwo#testSuccessOne") + .verifyTextInLog("jiras.surefire745.TestTwo#testSuccessTwo"); } @Test - public void simpleNameTestWithJavaExtWildcardPkg() - { - prepare( "**/TestTwo.java" ) - .executeTest() - .verifyErrorFree( 2 ) - .verifyErrorFreeLog() - .verifyTextInLog( "jiras.surefire745.TestTwo#testSuccessOne" ) - .verifyTextInLog( "jiras.surefire745.TestTwo#testSuccessTwo" ); + public void simpleNameTestWithJavaExtWildcardPkg() { + prepare("**/TestTwo.java") + .executeTest() + .verifyErrorFree(2) + .verifyErrorFreeLog() + .verifyTextInLog("jiras.surefire745.TestTwo#testSuccessOne") + .verifyTextInLog("jiras.surefire745.TestTwo#testSuccessTwo"); } @Test - public void fullyQualifiedTest() - { - prepare( "jiras/surefire745/TestTwo.java" ) - .executeTest() - .verifyErrorFree( 2 ) - .verifyErrorFreeLog() - .verifyTextInLog( "jiras.surefire745.TestTwo#testSuccessOne" ) - .verifyTextInLog( "jiras.surefire745.TestTwo#testSuccessTwo" ); + public void fullyQualifiedTest() { + prepare("jiras/surefire745/TestTwo.java") + .executeTest() + .verifyErrorFree(2) + .verifyErrorFreeLog() + .verifyTextInLog("jiras.surefire745.TestTwo#testSuccessOne") + .verifyTextInLog("jiras.surefire745.TestTwo#testSuccessTwo"); } @Test - public void shouldMatchSimpleClassNameAndMethod() - { - assumeThat( getSettings().getConfiguration(), is( TEST ) ); - prepare( "BasicTest#testSuccessTwo" ) - .executeTest() - .verifyErrorFree( 1 ) - .verifyErrorFreeLog() - .verifyTextInLog( "jiras.surefire745.BasicTest#testSuccessTwo" ); + public void shouldMatchSimpleClassNameAndMethod() { + assumeThat(getSettings().getConfiguration(), is(TEST)); + prepare("BasicTest#testSuccessTwo") + .executeTest() + .verifyErrorFree(1) + .verifyErrorFreeLog() + .verifyTextInLog("jiras.surefire745.BasicTest#testSuccessTwo"); } /** * This method name was shorten because it cause 261 character long path on Windows with Jenkins Pipeline. */ @Test - public void matchSimpleClassAndMethodWithJavaExt() - { - assumeThat( getSettings().getConfiguration(), is( TEST ) ); - prepare( "BasicTest.java#testSuccessTwo" ) - .executeTest() - .verifyErrorFree( 1 ) - .verifyErrorFreeLog() - .verifyTextInLog( "jiras.surefire745.BasicTest#testSuccessTwo" ); + public void matchSimpleClassAndMethodWithJavaExt() { + assumeThat(getSettings().getConfiguration(), is(TEST)); + prepare("BasicTest.java#testSuccessTwo") + .executeTest() + .verifyErrorFree(1) + .verifyErrorFreeLog() + .verifyTextInLog("jiras.surefire745.BasicTest#testSuccessTwo"); } /** * This method name was shorten because it cause 261 character long path on Windows with Jenkins Pipeline. */ @Test - public void matchSimpleClassAndMethodWithWildcardPkg() - { - assumeThat( getSettings().getConfiguration(), is( TEST ) ); - prepare( "**/BasicTest#testSuccessTwo" ) - .executeTest() - .verifyErrorFree( 1 ) - .verifyErrorFreeLog() - .verifyTextInLog( "jiras.surefire745.BasicTest#testSuccessTwo" ); + public void matchSimpleClassAndMethodWithWildcardPkg() { + assumeThat(getSettings().getConfiguration(), is(TEST)); + prepare("**/BasicTest#testSuccessTwo") + .executeTest() + .verifyErrorFree(1) + .verifyErrorFreeLog() + .verifyTextInLog("jiras.surefire745.BasicTest#testSuccessTwo"); } /** * This method name was shorten because it cause 261 character long path on Windows with Jenkins Pipeline. */ @Test - public void matchSimpleClassAndMethodWithJavaExtWildcardPkg() - { - assumeThat( getSettings().getConfiguration(), is( TEST ) ); - prepare( "**/BasicTest.java#testSuccessTwo" ) - .executeTest() - .verifyErrorFree( 1 ) - .verifyErrorFreeLog() - .verifyTextInLog( "jiras.surefire745.BasicTest#testSuccessTwo" ); + public void matchSimpleClassAndMethodWithJavaExtWildcardPkg() { + assumeThat(getSettings().getConfiguration(), is(TEST)); + prepare("**/BasicTest.java#testSuccessTwo") + .executeTest() + .verifyErrorFree(1) + .verifyErrorFreeLog() + .verifyTextInLog("jiras.surefire745.BasicTest#testSuccessTwo"); } @Test - public void shouldMatchWildcardPackageAndClassAndMethod() - { - assumeThat( getSettings().getConfiguration(), is( TEST ) ); - prepare( "jiras/**/BasicTest#testSuccessTwo" ) - .executeTest() - .verifyErrorFree( 1 ) - .verifyErrorFreeLog() - .verifyTextInLog( "jiras.surefire745.BasicTest#testSuccessTwo" ); + public void shouldMatchWildcardPackageAndClassAndMethod() { + assumeThat(getSettings().getConfiguration(), is(TEST)); + prepare("jiras/**/BasicTest#testSuccessTwo") + .executeTest() + .verifyErrorFree(1) + .verifyErrorFreeLog() + .verifyTextInLog("jiras.surefire745.BasicTest#testSuccessTwo"); } @Test - public void regexClass() - { - prepare( "%regex[.*.TestTwo.*]" ) - .executeTest() - .verifyErrorFree( 2 ) - .verifyErrorFreeLog() - .verifyTextInLog( "jiras.surefire745.TestTwo#testSuccessOne" ) - .verifyTextInLog( "jiras.surefire745.TestTwo#testSuccessTwo" ); + public void regexClass() { + prepare("%regex[.*.TestTwo.*]") + .executeTest() + .verifyErrorFree(2) + .verifyErrorFreeLog() + .verifyTextInLog("jiras.surefire745.TestTwo#testSuccessOne") + .verifyTextInLog("jiras.surefire745.TestTwo#testSuccessTwo"); } @Test - public void testSuccessTwo() - { - assumeThat( getSettings().getConfiguration(), is( TEST ) ); - prepare( "#testSuccessTwo" ) - .maven().debugLogging() - .executeTest() - .verifyErrorFree( 5 ) - .verifyErrorFreeLog(); + public void testSuccessTwo() { + assumeThat(getSettings().getConfiguration(), is(TEST)); + prepare("#testSuccessTwo") + .maven() + .debugLogging() + .executeTest() + .verifyErrorFree(5) + .verifyErrorFreeLog(); } @Test - public void testRegexSuccessTwo() - { - assumeThat( getSettings().getConfiguration(), is( TEST ) ); - prepare( "%regex[#testSuccessTwo]" ) - .executeTest() - .verifyErrorFree( 5 ) - .verifyErrorFreeLog(); + public void testRegexSuccessTwo() { + assumeThat(getSettings().getConfiguration(), is(TEST)); + prepare("%regex[#testSuccessTwo]").executeTest().verifyErrorFree(5).verifyErrorFreeLog(); } @Test - public void regexClassAndMethod() - { - assumeThat( getSettings().getConfiguration(), is( TEST ) ); - prepare( "%regex[.*.BasicTest.*#testSuccessTwo]" ) - .executeTest() - .verifyErrorFree( 1 ) - .verifyErrorFreeLog() - .verifyTextInLog( "jiras.surefire745.BasicTest#testSuccessTwo" ); + public void regexClassAndMethod() { + assumeThat(getSettings().getConfiguration(), is(TEST)); + prepare("%regex[.*.BasicTest.*#testSuccessTwo]") + .executeTest() + .verifyErrorFree(1) + .verifyErrorFreeLog() + .verifyTextInLog("jiras.surefire745.BasicTest#testSuccessTwo"); } @Test - public void shouldMatchExactClassAndMethodWildcard() - { - assumeThat( getSettings().getConfiguration(), is( TEST ) ); - prepare( "BasicTest#test*One" ) - .executeTest() - .verifyErrorFree( 1 ) - .verifyErrorFreeLog() - .verifyTextInLog( "jiras.surefire745.BasicTest#testSuccessOne" ); + public void shouldMatchExactClassAndMethodWildcard() { + assumeThat(getSettings().getConfiguration(), is(TEST)); + prepare("BasicTest#test*One") + .executeTest() + .verifyErrorFree(1) + .verifyErrorFreeLog() + .verifyTextInLog("jiras.surefire745.BasicTest#testSuccessOne"); } @Test - public void shouldMatchExactClassAndMethodsWildcard() - { - assumeThat( getSettings().getConfiguration(), is( TEST ) ); - prepare( "BasicTest#testSuccess*" ) - .executeTest() - .verifyErrorFree( 2 ) - .verifyErrorFreeLog() - .verifyTextInLog( "jiras.surefire745.BasicTest#testSuccessOne" ) - .verifyTextInLog( "jiras.surefire745.BasicTest#testSuccessTwo" ); + public void shouldMatchExactClassAndMethodsWildcard() { + assumeThat(getSettings().getConfiguration(), is(TEST)); + prepare("BasicTest#testSuccess*") + .executeTest() + .verifyErrorFree(2) + .verifyErrorFreeLog() + .verifyTextInLog("jiras.surefire745.BasicTest#testSuccessOne") + .verifyTextInLog("jiras.surefire745.BasicTest#testSuccessTwo"); } @Test - public void shouldMatchExactClassAndMethodCharacters() - { - assumeThat( getSettings().getConfiguration(), is( TEST ) ); - prepare( "BasicTest#test???????One" ) - .executeTest() - .verifyErrorFree( 1 ) - .verifyErrorFreeLog() - .verifyTextInLog( "jiras.surefire745.BasicTest#testSuccessOne" ); + public void shouldMatchExactClassAndMethodCharacters() { + assumeThat(getSettings().getConfiguration(), is(TEST)); + prepare("BasicTest#test???????One") + .executeTest() + .verifyErrorFree(1) + .verifyErrorFreeLog() + .verifyTextInLog("jiras.surefire745.BasicTest#testSuccessOne"); } @Test - public void shouldMatchExactClassAndMethodsPostfix() - { - assumeThat( getSettings().getConfiguration(), is( TEST ) ); - prepare( "TestFive#testSuccess???" ) - .executeTest() - .verifyErrorFree( 2 ) - .verifyErrorFreeLog() - .verifyTextInLog( "jiras.surefire745.TestFive#testSuccessOne" ) - .verifyTextInLog( "jiras.surefire745.TestFive#testSuccessTwo" ); + public void shouldMatchExactClassAndMethodsPostfix() { + assumeThat(getSettings().getConfiguration(), is(TEST)); + prepare("TestFive#testSuccess???") + .executeTest() + .verifyErrorFree(2) + .verifyErrorFreeLog() + .verifyTextInLog("jiras.surefire745.TestFive#testSuccessOne") + .verifyTextInLog("jiras.surefire745.TestFive#testSuccessTwo"); } @Test - public void shouldMatchExactClassAndMethodPostfix() - { - assumeThat( getSettings().getConfiguration(), is( TEST ) ); - prepare( "TestFive#testSuccess?????" ) - .executeTest() - .verifyErrorFree( 1 ) - .verifyErrorFreeLog() - .verifyTextInLog( "jiras.surefire745.TestFive#testSuccessThree" ); + public void shouldMatchExactClassAndMethodPostfix() { + assumeThat(getSettings().getConfiguration(), is(TEST)); + prepare("TestFive#testSuccess?????") + .executeTest() + .verifyErrorFree(1) + .verifyErrorFreeLog() + .verifyTextInLog("jiras.surefire745.TestFive#testSuccessThree"); } @Test - public void shouldMatchExactClassAndMultipleMethods() - { - assumeThat( getSettings().getConfiguration(), is( TEST ) ); - prepare( "TestFive#testSuccessOne+testSuccessThree" ) - .executeTest() - .verifyErrorFree( 2 ) - .verifyErrorFreeLog() - .verifyTextInLog( "jiras.surefire745.TestFive#testSuccessOne" ) - .verifyTextInLog( "jiras.surefire745.TestFive#testSuccessThree" ); + public void shouldMatchExactClassAndMultipleMethods() { + assumeThat(getSettings().getConfiguration(), is(TEST)); + prepare("TestFive#testSuccessOne+testSuccessThree") + .executeTest() + .verifyErrorFree(2) + .verifyErrorFreeLog() + .verifyTextInLog("jiras.surefire745.TestFive#testSuccessOne") + .verifyTextInLog("jiras.surefire745.TestFive#testSuccessThree"); } @Test - public void shouldMatchMultiplePatterns() - { - assumeThat( getSettings().getConfiguration(), is( TEST ) ); - String test = "jiras/surefire745/BasicTest#testSuccessOne+testSuccessTwo" //2 - + ',' + "jiras/**/TestTwo" //2 - + ',' + "jiras/surefire745/TestThree#testSuccess*" //2 - + ',' + "TestFour#testSuccess???" //2 - + ',' + "jiras/surefire745/*Five#test*One"; //1 + public void shouldMatchMultiplePatterns() { + assumeThat(getSettings().getConfiguration(), is(TEST)); + String test = "jiras/surefire745/BasicTest#testSuccessOne+testSuccessTwo" // 2 + + ',' + "jiras/**/TestTwo" // 2 + + ',' + "jiras/surefire745/TestThree#testSuccess*" // 2 + + ',' + "TestFour#testSuccess???" // 2 + + ',' + "jiras/surefire745/*Five#test*One"; // 1 - prepare( test ) - .executeTest() - .verifyErrorFree( 9 ) - .verifyErrorFreeLog(); + prepare(test).executeTest().verifyErrorFree(9).verifyErrorFreeLog(); } @Test - public void shouldMatchMultiplePatternsAsParallel() - { - assumeThat( getSettings().getFramework(), anyOf( is( JUNIT47 ), is( TestNG ) ) ); - assumeThat( getSettings().getConfiguration(), is( TEST ) ); - String test = "jiras/surefire745/BasicTest#testSuccessOne+testSuccessTwo" //2 - + ',' + "jiras/**/TestTwo" //2 - + ',' + "jiras/surefire745/TestThree#testSuccess*" //2 - + ',' + "TestFour#testSuccess???" //2 - + ',' + "jiras/surefire745/*Five#test*One"; //1 - - prepare( test ) - .parallel( "classes" ) - .useUnlimitedThreads() - .executeTest() - .verifyErrorFree( 9 ) - .verifyErrorFreeLog(); + public void shouldMatchMultiplePatternsAsParallel() { + assumeThat(getSettings().getFramework(), anyOf(is(JUNIT47), is(TestNG))); + assumeThat(getSettings().getConfiguration(), is(TEST)); + String test = "jiras/surefire745/BasicTest#testSuccessOne+testSuccessTwo" // 2 + + ',' + "jiras/**/TestTwo" // 2 + + ',' + "jiras/surefire745/TestThree#testSuccess*" // 2 + + ',' + "TestFour#testSuccess???" // 2 + + ',' + "jiras/surefire745/*Five#test*One"; // 1 + + prepare(test) + .parallel("classes") + .useUnlimitedThreads() + .executeTest() + .verifyErrorFree(9) + .verifyErrorFreeLog(); } @Test - public void shouldMatchMultiplePatternsComplex() - { - assumeThat( getSettings().getConfiguration(), is( TEST ) ); - String test = "**/BasicTest#testSuccessOne+testSuccessTwo" //2 - + ',' + "jiras/**/TestTwo" //2 - + ',' + "?????/surefire745/TestThree#testSuccess*" //2 - + ',' + "jiras/surefire745/TestFour.java#testSuccess???" //2 - + ',' + "jiras/surefire745/*Five#test*One"; //1 + public void shouldMatchMultiplePatternsComplex() { + assumeThat(getSettings().getConfiguration(), is(TEST)); + String test = "**/BasicTest#testSuccessOne+testSuccessTwo" // 2 + + ',' + "jiras/**/TestTwo" // 2 + + ',' + "?????/surefire745/TestThree#testSuccess*" // 2 + + ',' + "jiras/surefire745/TestFour.java#testSuccess???" // 2 + + ',' + "jiras/surefire745/*Five#test*One"; // 1 - prepare( test ) - .executeTest() - .verifyErrorFree( 9 ) - .verifyErrorFreeLog(); + prepare(test).executeTest().verifyErrorFree(9).verifyErrorFreeLog(); } @Test - public void shouldMatchMultiplePatternsComplexAsParallel() - { - assumeThat( getSettings().getFramework(), anyOf( is( JUNIT47 ), is( TestNG ) ) ); - assumeThat( getSettings().getConfiguration(), is( TEST ) ); - String test = "**/BasicTest#testSuccessOne+testSuccessTwo" //2 - + ',' + "jiras/**/TestTwo" //2 - + ',' + "?????/surefire745/TestThree#testSuccess*" //2 - + ',' + "jiras/surefire745/TestFour.java#testSuccess???" //2 - + ',' + "jiras/surefire745/*Five#test*One"; //1 - - prepare( test ) - .parallel( "classes" ) - .useUnlimitedThreads() - .executeTest() - .verifyErrorFree( 9 ) - .verifyErrorFreeLog(); + public void shouldMatchMultiplePatternsComplexAsParallel() { + assumeThat(getSettings().getFramework(), anyOf(is(JUNIT47), is(TestNG))); + assumeThat(getSettings().getConfiguration(), is(TEST)); + String test = "**/BasicTest#testSuccessOne+testSuccessTwo" // 2 + + ',' + "jiras/**/TestTwo" // 2 + + ',' + "?????/surefire745/TestThree#testSuccess*" // 2 + + ',' + "jiras/surefire745/TestFour.java#testSuccess???" // 2 + + ',' + "jiras/surefire745/*Five#test*One"; // 1 + + prepare(test) + .parallel("classes") + .useUnlimitedThreads() + .executeTest() + .verifyErrorFree(9) + .verifyErrorFreeLog(); } @Test - public void shouldNotRunExcludedClasses() - { - prepare( "!BasicTest, !**/TestTwo, !**/TestThree.java" ) - .executeTest() - .verifyErrorFree( 6 ) - .verifyErrorFreeLog(); + public void shouldNotRunExcludedClasses() { + prepare("!BasicTest, !**/TestTwo, !**/TestThree.java") + .executeTest() + .verifyErrorFree(6) + .verifyErrorFreeLog(); } @Test - public void shouldNotRunExcludedClassesIfIncluded() - { - prepare( "TestF*.java, !**/TestFour.java" ) - .executeTest() - .verifyErrorFree( 3 ) - .verifyErrorFreeLog(); + public void shouldNotRunExcludedClassesIfIncluded() { + prepare("TestF*.java, !**/TestFour.java") + .executeTest() + .verifyErrorFree(3) + .verifyErrorFreeLog(); } @Test - public void shouldNotRunExcludedMethods() - { - assumeThat( getSettings().getConfiguration(), is( TEST ) ); - prepare( "!#*Fail*, !%regex[#.*One], !#testSuccessThree" ) - .executeTest() - .verifyErrorFree( 5 ) - .verifyErrorFreeLog(); + public void shouldNotRunExcludedMethods() { + assumeThat(getSettings().getConfiguration(), is(TEST)); + prepare("!#*Fail*, !%regex[#.*One], !#testSuccessThree") + .executeTest() + .verifyErrorFree(5) + .verifyErrorFreeLog(); } @Test - public void shouldNotRunExcludedClassesAndMethods() - { - assumeThat( getSettings().getConfiguration(), is( TEST ) ); - prepare( "!#*Fail*, !TestFour#testSuccessTwo" ) - .executeTest() - .verifyErrorFree( 11 ) - .verifyErrorFreeLog(); + public void shouldNotRunExcludedClassesAndMethods() { + assumeThat(getSettings().getConfiguration(), is(TEST)); + prepare("!#*Fail*, !TestFour#testSuccessTwo") + .executeTest() + .verifyErrorFree(11) + .verifyErrorFreeLog(); } @Test - public void negativeTest() - { - assumeThat( getSettings().getConfiguration(), anyOf( is( INCLUDES ), is( INCLUDES_EXCLUDES ), - is( INCLUDES_FILE ), is( INCLUDES_EXCLUDES_FILE ) ) ); + public void negativeTest() { + assumeThat( + getSettings().getConfiguration(), + anyOf( + is(INCLUDES), is(INCLUDES_EXCLUDES), + is(INCLUDES_FILE), is(INCLUDES_EXCLUDES_FILE))); String pattern = "TestFive#testSuccessOne+testSuccessThree"; - prepare( pattern ) - .failNever() - .executeTest() - .verifyTextInLog( "Method filter prohibited in includes|excludes parameter: " + pattern ); + prepare(pattern) + .failNever() + .executeTest() + .verifyTextInLog("Method filter prohibited in includes|excludes parameter: " + pattern); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/AdditionalClasspathIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/AdditionalClasspathIT.java index 08191961d8..ee377f2254 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/AdditionalClasspathIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/AdditionalClasspathIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its; /* @@ -28,12 +46,9 @@ * @author Dan Fabulich * @author Kristian Rosenvold */ -public class AdditionalClasspathIT - extends SurefireJUnit4IntegrationTestCase -{ +public class AdditionalClasspathIT extends SurefireJUnit4IntegrationTestCase { @Test - public void additionalClasspath() - { - unpack( "/additional-classpath" ).executeTest().verifyErrorFree( 1 ); + public void additionalClasspath() { + unpack("/additional-classpath").executeTest().verifyErrorFree(1); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/AggregateReportIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/AggregateReportIT.java index ab8f64c897..a32145c4c8 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/AggregateReportIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/AggregateReportIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its; /* @@ -27,8 +45,8 @@ import org.apache.maven.surefire.its.fixture.TestFile; import org.junit.Test; -import static org.apache.maven.surefire.its.fixture.HelperAssertions.parseTestResults; import static org.apache.maven.surefire.its.fixture.HelperAssertions.assertTestSuiteResults; +import static org.apache.maven.surefire.its.fixture.HelperAssertions.parseTestResults; import static org.junit.Assert.assertTrue; /** @@ -37,21 +55,19 @@ * @author Dan Fabulich * @author Kristian Rosenvold */ -public class AggregateReportIT - extends SurefireJUnit4IntegrationTestCase -{ +public class AggregateReportIT extends SurefireJUnit4IntegrationTestCase { @Test - public void aggregateReport() - { - OutputValidator outputValidator = unpack( "/aggregate-report" ).addSurefireReportGoal().executeCurrentGoals(); - TestFile surefireReportHtml = outputValidator.getSiteFile( "surefire-report.html" ); - assertTrue( "surefire report missing: " + surefireReportHtml.getAbsolutePath(), surefireReportHtml.exists() ); + public void aggregateReport() { + OutputValidator outputValidator = + unpack("/aggregate-report").addSurefireReportGoal().executeCurrentGoals(); + TestFile surefireReportHtml = outputValidator.getSiteFile("surefire-report.html"); + assertTrue("surefire report missing: " + surefireReportHtml.getAbsolutePath(), surefireReportHtml.exists()); // TODO HtmlUnit tests on the surefire report - IntegrationTestSuiteResults suite = parseTestResults( new File( outputValidator.getBaseDir(), "child1" ), - new File( outputValidator.getBaseDir(), "child2" ) ); - assertTestSuiteResults( 2, 0, 1, 0, suite ); + IntegrationTestSuiteResults suite = parseTestResults( + new File(outputValidator.getBaseDir(), "child1"), new File(outputValidator.getBaseDir(), "child2")); + assertTestSuiteResults(2, 0, 1, 0, suite); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/ArgLineIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/ArgLineIT.java index c1ad8f7a9c..1735e57584 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/ArgLineIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/ArgLineIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its; /* @@ -28,12 +46,9 @@ * @author Dan Fabulich * @author Kristian Rosenvold */ -public class ArgLineIT - extends SurefireJUnit4IntegrationTestCase -{ +public class ArgLineIT extends SurefireJUnit4IntegrationTestCase { @Test - public void argLine() - { - unpack( "/argLine-parameter" ).executeTest().verifyErrorFree( 1 ); + public void argLine() { + unpack("/argLine-parameter").executeTest().verifyErrorFree(1); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/ArgLinePropertiesIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/ArgLinePropertiesIT.java index cf1074ede0..ac393ce265 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/ArgLinePropertiesIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/ArgLinePropertiesIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its; /* @@ -28,12 +46,9 @@ * @author Dan Fabulich * @author Kristian Rosenvold */ -public class ArgLinePropertiesIT - extends SurefireJUnit4IntegrationTestCase -{ +public class ArgLinePropertiesIT extends SurefireJUnit4IntegrationTestCase { @Test - public void argLine() - { - unpack( "/argLine-properties" ).executeTest().verifyErrorFree( 4 ); + public void argLine() { + unpack("/argLine-properties").executeTest().verifyErrorFree(4); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/AssumptionFailureReportIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/AssumptionFailureReportIT.java index f9da42c663..3ed86b05b7 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/AssumptionFailureReportIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/AssumptionFailureReportIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its; /* @@ -27,13 +45,12 @@ /** * */ -public class AssumptionFailureReportIT extends SurefireJUnit4IntegrationTestCase -{ +public class AssumptionFailureReportIT extends SurefireJUnit4IntegrationTestCase { @Test - public void testWriteSkippedMessageToReport() - { - final OutputValidator outputValidator = unpack( "/assumpationFailureReport" ).executeTest(); - TestFile xmlReportFile = outputValidator.getSurefireReportsXmlFile( "TEST-assumptionFailure.Test1.xml" ); - xmlReportFile.assertContainsText( "The test is skipped if it is false" ); + public void testWriteSkippedMessageToReport() { + final OutputValidator outputValidator = + unpack("/assumpationFailureReport").executeTest(); + TestFile xmlReportFile = outputValidator.getSurefireReportsXmlFile("TEST-assumptionFailure.Test1.xml"); + xmlReportFile.assertContainsText("The test is skipped if it is false"); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/CheckSingleTestIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/CheckSingleTestIT.java index 343d3b33ef..2574994f89 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/CheckSingleTestIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/CheckSingleTestIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its; /* @@ -33,41 +51,36 @@ * @author Dan Fabulich * @author Kristian Rosenvold */ -public class CheckSingleTestIT - extends SurefireJUnit4IntegrationTestCase -{ +public class CheckSingleTestIT extends SurefireJUnit4IntegrationTestCase { @Test - public void singleTest() - { - unpack().setTestToRun( "BasicTest" ).executeTest().verifyErrorFree( 1 ); + public void singleTest() { + unpack().setTestToRun("BasicTest").executeTest().verifyErrorFree(1); } @Test - public void singleTestDotJava() - { - unpack().setTestToRun( "BasicTest.java" ).executeTest().verifyErrorFree( 1 ); + public void singleTestDotJava() { + unpack().setTestToRun("BasicTest.java").executeTest().verifyErrorFree(1); } @Test - public void singleTestNonExistent() - { - final OutputValidator output = unpack().setTestToRun( "DoesNotExist" ).maven().withFailure().executeTest(); - TestFile reportsDir = output.getTargetFile( "surefire-reports" ); - assertFalse( "Unexpected reports directory", reportsDir.exists() ); + public void singleTestNonExistent() { + final OutputValidator output = + unpack().setTestToRun("DoesNotExist").maven().withFailure().executeTest(); + TestFile reportsDir = output.getTargetFile("surefire-reports"); + assertFalse("Unexpected reports directory", reportsDir.exists()); } @Test - public void singleTestNonExistentOverride() - { - final OutputValidator output = - unpack().setTestToRun( "DoesNotExist" ).failIfNoSpecifiedTests( false ).executeTest().verifyErrorFreeLog(); - output.getTargetFile( "surefire-reports" ); + public void singleTestNonExistentOverride() { + final OutputValidator output = unpack().setTestToRun("DoesNotExist") + .failIfNoSpecifiedTests(false) + .executeTest() + .verifyErrorFreeLog(); + output.getTargetFile("surefire-reports"); // assertFalse( "Unexpected reports directory", reportsDir.exists() ); Hmpf. Not really a good test } - private SurefireLauncher unpack() - { - return unpack( "/default-configuration" ); + private SurefireLauncher unpack() { + return unpack("/default-configuration"); } - } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/CheckTestFailIfNoTestsForkCountIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/CheckTestFailIfNoTestsForkCountIT.java index f9b2464742..ee54f35d79 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/CheckTestFailIfNoTestsForkCountIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/CheckTestFailIfNoTestsForkCountIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its; /* @@ -29,53 +47,42 @@ * @author Dan Fabulich * @author Kristian Rosenvold */ -public class CheckTestFailIfNoTestsForkCountIT - extends SurefireJUnit4IntegrationTestCase -{ +public class CheckTestFailIfNoTestsForkCountIT extends SurefireJUnit4IntegrationTestCase { @Test - public void failIfNoTestsForkAlways() - { - unpack().forkAlways().failIfNoTests( true ).maven().withFailure().executeTest(); + public void failIfNoTestsForkAlways() { + unpack().forkAlways().failIfNoTests(true).maven().withFailure().executeTest(); } @Test - public void failIfNoTestsForkNever() - { - unpack().forkNever().failIfNoTests( true ).maven().withFailure().executeTest(); + public void failIfNoTestsForkNever() { + unpack().forkNever().failIfNoTests(true).maven().withFailure().executeTest(); } @Test - public void failIfNoTestsForkOnce() - { - unpack().forkOnce().failIfNoTests( true ).maven().withFailure().executeTest(); + public void failIfNoTestsForkOnce() { + unpack().forkOnce().failIfNoTests(true).maven().withFailure().executeTest(); } @Test - public void dontFailIfNoTestsForkAlways() - { - doTest( unpack().forkAlways().failIfNoTests( false ) ); + public void dontFailIfNoTestsForkAlways() { + doTest(unpack().forkAlways().failIfNoTests(false)); } @Test - public void dontFailIfNoTestsForkNever() - { - doTest( unpack().forkNever().failIfNoTests( false ) ); + public void dontFailIfNoTestsForkNever() { + doTest(unpack().forkNever().failIfNoTests(false)); } @Test - public void dontFailIfNoTestsForkOnce() - { - doTest( unpack().forkOnce().failIfNoTests( false ) ); + public void dontFailIfNoTestsForkOnce() { + doTest(unpack().forkOnce().failIfNoTests(false)); } - private void doTest( SurefireLauncher launcher ) - { - launcher.executeTest().verifyErrorFreeLog().assertTestSuiteResults( 0, 0, 0, 0 ); + private void doTest(SurefireLauncher launcher) { + launcher.executeTest().verifyErrorFreeLog().assertTestSuiteResults(0, 0, 0, 0); } - private SurefireLauncher unpack() - { - return unpack( "default-configuration-classWithNoTests" ); + private SurefireLauncher unpack() { + return unpack("default-configuration-classWithNoTests"); } - } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/CheckTestFailIfNoTestsIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/CheckTestFailIfNoTestsIT.java index 02fad0c153..407f71d7a1 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/CheckTestFailIfNoTestsIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/CheckTestFailIfNoTestsIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its; /* @@ -33,34 +51,30 @@ * @author Dan Fabulich * @author Kristian Rosenvold */ -public class CheckTestFailIfNoTestsIT - extends SurefireJUnit4IntegrationTestCase -{ - private SurefireLauncher unpack() - { - return unpack( "/default-configuration-noTests" ); +public class CheckTestFailIfNoTestsIT extends SurefireJUnit4IntegrationTestCase { + private SurefireLauncher unpack() { + return unpack("/default-configuration-noTests"); } @Test - public void failIfNoTests() - { - unpack().failIfNoTests( true ).maven().withFailure().executeTest(); + public void failIfNoTests() { + unpack().failIfNoTests(true).maven().withFailure().executeTest(); } @Test - public void dontFailIfNoTests() - { - final OutputValidator outputValidator = unpack().failIfNoTests( false ).executeTest(); + public void dontFailIfNoTests() { + final OutputValidator outputValidator = unpack().failIfNoTests(false).executeTest(); outputValidator.verifyErrorFreeLog(); - TestFile reportsDir = outputValidator.getSurefireReportsFile( "" ); - assertFalse( "Unexpected reports directory", reportsDir.exists() ); + TestFile reportsDir = outputValidator.getSurefireReportsFile(""); + assertFalse("Unexpected reports directory", reportsDir.exists()); } @Test - public void jUnit48CategoriesFailWhenNoTests() - { - unpack().failIfNoTests( false ).activateProfile( "junit47" ).setJUnitVersion( - "4.8.1" ).executeTest().verifyErrorFreeLog(); + public void jUnit48CategoriesFailWhenNoTests() { + unpack().failIfNoTests(false) + .activateProfile("junit47") + .setJUnitVersion("4.8.1") + .executeTest() + .verifyErrorFreeLog(); } - } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/CheckTestNg740ParallelIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/CheckTestNg740ParallelIT.java index 2122e91a53..445f6efdac 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/CheckTestNg740ParallelIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/CheckTestNg740ParallelIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its; /* @@ -24,23 +42,15 @@ /** */ -@SuppressWarnings( "checkstyle:magicnumber" ) -public class CheckTestNg740ParallelIT - extends SurefireJUnit4IntegrationTestCase -{ +@SuppressWarnings("checkstyle:magicnumber") +public class CheckTestNg740ParallelIT extends SurefireJUnit4IntegrationTestCase { @Test - public void withTestNG740AndParallelSet() - { - unpack( "testng-740-parallel" ) - .executeTest() - .assertTestSuiteResults( 2, 0, 0, 0 ); + public void withTestNG740AndParallelSet() { + unpack("testng-740-parallel").executeTest().assertTestSuiteResults(2, 0, 0, 0); } - + @Test - public void withTestNG740AndParallelSetWithoutThreadCount() - { - unpack( "testng-740-parallel-without-threadcount" ) - .executeTest() - .assertTestSuiteResults( 2, 0, 0, 0 ); + public void withTestNG740AndParallelSetWithoutThreadCount() { + unpack("testng-740-parallel-without-threadcount").executeTest().assertTestSuiteResults(2, 0, 0, 0); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/CheckTestNgBeforeMethodFailureIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/CheckTestNgBeforeMethodFailureIT.java index 22d72a09be..ec9baf6664 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/CheckTestNgBeforeMethodFailureIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/CheckTestNgBeforeMethodFailureIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its; /* @@ -28,19 +46,16 @@ * @author Dan Fabulich * @author Kristian Rosenvold */ -public class CheckTestNgBeforeMethodFailureIT - extends SurefireJUnit4IntegrationTestCase -{ +public class CheckTestNgBeforeMethodFailureIT extends SurefireJUnit4IntegrationTestCase { @Test - public void testNgBeforeMethodFailure() - { - unpack( "/testng-beforeMethodFailure" ) + public void testNgBeforeMethodFailure() { + unpack("/testng-beforeMethodFailure") .maven() - .sysProp( "testNgVersion", "5.7" ) - .sysProp( "testNgClassifier", "jdk15" ) + .sysProp("testNgVersion", "5.7") + .sysProp("testNgClassifier", "jdk15") .withFailure() .executeTest() - .assertTestSuiteResults( 2, 0, 1, 1 ); + .assertTestSuiteResults(2, 0, 1, 1); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/CheckTestNgBeforeMethodIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/CheckTestNgBeforeMethodIT.java index 02fab32348..ba6395fdb2 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/CheckTestNgBeforeMethodIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/CheckTestNgBeforeMethodIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its; /* @@ -28,16 +46,13 @@ * @author Dan Fabulich * @author Kristian Rosenvold */ -public class CheckTestNgBeforeMethodIT - extends SurefireJUnit4IntegrationTestCase -{ +public class CheckTestNgBeforeMethodIT extends SurefireJUnit4IntegrationTestCase { @Test - public void testNgBeforeMethod() - { - unpack( "/testng-beforeMethod" ) - .sysProp( "testNgVersion", "5.7" ) - .sysProp( "testNgClassifier", "jdk15" ) + public void testNgBeforeMethod() { + unpack("/testng-beforeMethod") + .sysProp("testNgVersion", "5.7") + .sysProp("testNgClassifier", "jdk15") .executeTest() - .verifyErrorFree( 1 ); + .verifyErrorFree(1); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/CheckTestNgCustomObjectFactoryIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/CheckTestNgCustomObjectFactoryIT.java index 29f77898a8..57ecd53d06 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/CheckTestNgCustomObjectFactoryIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/CheckTestNgCustomObjectFactoryIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its; /* @@ -19,12 +37,12 @@ * under the License. */ +import java.io.File; + import org.apache.maven.surefire.its.fixture.SurefireJUnit4IntegrationTestCase; import org.apache.maven.surefire.its.fixture.SurefireLauncher; import org.junit.Test; -import java.io.File; - import static org.assertj.core.api.Assertions.assertThat; /** @@ -32,28 +50,22 @@ * * @author Orien Madgwick */ -public class CheckTestNgCustomObjectFactoryIT - extends SurefireJUnit4IntegrationTestCase -{ +public class CheckTestNgCustomObjectFactoryIT extends SurefireJUnit4IntegrationTestCase { @Test - public void testTestNgListenerReporter() - throws Exception - { - File baseDir = unpack() - .executeTest() - .verifyErrorFreeLog() - .assertTestSuiteResults( 1, 0, 0, 0 ) - .getBaseDir(); + public void testTestNgListenerReporter() throws Exception { + File baseDir = unpack().executeTest() + .verifyErrorFreeLog() + .assertTestSuiteResults(1, 0, 0, 0) + .getBaseDir(); baseDir = baseDir.getCanonicalFile(); - File targetDir = new File( baseDir, "target" ); - assertThat( targetDir ).isDirectory(); - assertThat( new File( targetDir, "objectFactory-output.txt" ) ).isFile(); + File targetDir = new File(baseDir, "target"); + assertThat(targetDir).isDirectory(); + assertThat(new File(targetDir, "objectFactory-output.txt")).isFile(); } - private SurefireLauncher unpack() - { - return unpack( "/testng-objectFactory" ); + private SurefireLauncher unpack() { + return unpack("/testng-objectFactory"); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/CheckTestNgCustomTestRunnerFactoryIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/CheckTestNgCustomTestRunnerFactoryIT.java index 856f146a57..3e390740e3 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/CheckTestNgCustomTestRunnerFactoryIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/CheckTestNgCustomTestRunnerFactoryIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its; /* @@ -19,13 +37,13 @@ * under the License. */ +import java.io.File; +import java.io.IOException; + import org.apache.maven.surefire.its.fixture.SurefireJUnit4IntegrationTestCase; import org.apache.maven.surefire.its.fixture.SurefireLauncher; import org.junit.Test; -import java.io.File; -import java.io.IOException; - import static org.assertj.core.api.Assertions.assertThat; /** @@ -33,29 +51,22 @@ * * @author Orien Madgwick */ -public class CheckTestNgCustomTestRunnerFactoryIT - extends SurefireJUnit4IntegrationTestCase -{ +public class CheckTestNgCustomTestRunnerFactoryIT extends SurefireJUnit4IntegrationTestCase { @Test - public void testTestNgListenerReporter() - throws IOException - { - File baseDir = unpack() - .executeTest() - .verifyErrorFreeLog() - .assertTestSuiteResults( 1, 0, 0, 0 ) - .getBaseDir(); + public void testTestNgListenerReporter() throws IOException { + File baseDir = unpack().executeTest() + .verifyErrorFreeLog() + .assertTestSuiteResults(1, 0, 0, 0) + .getBaseDir(); baseDir = baseDir.getCanonicalFile(); - File targetDir = new File( baseDir, "target" ); - assertThat( targetDir ).isDirectory(); - assertThat( new File( targetDir, "testrunnerfactory-output.txt" ) ).isFile(); + File targetDir = new File(baseDir, "target"); + assertThat(targetDir).isDirectory(); + assertThat(new File(targetDir, "testrunnerfactory-output.txt")).isFile(); } - private SurefireLauncher unpack() - { - return unpack( "/testng-testRunnerFactory" ); + private SurefireLauncher unpack() { + return unpack("/testng-testRunnerFactory"); } } - diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/CheckTestNgExecuteErrorIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/CheckTestNgExecuteErrorIT.java index 561de477f8..511b794b6d 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/CheckTestNgExecuteErrorIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/CheckTestNgExecuteErrorIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its; /* @@ -19,17 +37,16 @@ * under the License. */ +import java.io.File; +import java.io.FilenameFilter; + import org.apache.maven.surefire.its.fixture.OutputValidator; import org.apache.maven.surefire.its.fixture.SurefireJUnit4IntegrationTestCase; import org.junit.Test; -import java.io.File; -import java.io.FilenameFilter; - import static java.util.Objects.requireNonNull; import static org.assertj.core.api.Assertions.assertThat; - /** * Test for checking that the output from a forked suite is properly captured even if the suite encounters * a severe error. @@ -37,40 +54,31 @@ * @author Dan Fabulich * @author Kristian Rosenvold */ -public class CheckTestNgExecuteErrorIT - extends SurefireJUnit4IntegrationTestCase -{ +public class CheckTestNgExecuteErrorIT extends SurefireJUnit4IntegrationTestCase { @Test - public void executionError() - { - OutputValidator outputValidator = unpack( "/testng-execute-error" ) + public void executionError() { + OutputValidator outputValidator = unpack("/testng-execute-error") .maven() - .sysProp( "testNgVersion", "5.7" ) - .sysProp( "testNgClassifier", "jdk15" ) + .sysProp("testNgVersion", "5.7") + .sysProp("testNgClassifier", "jdk15") .showErrorStackTraces() .withFailure() .executeTest() - .verifyTextInLog( "Cyclic graph of methods" ) - .verifyTextInLog( "at org.apache.maven.surefire.testng.TestNGExecutor.run" ); + .verifyTextInLog("Cyclic graph of methods") + .verifyTextInLog("at org.apache.maven.surefire.testng.TestNGExecutor.run"); File reportDir = outputValidator.getSurefireReportsDirectory(); - String[] dumpFiles = reportDir.list( new FilenameFilter() - { - @Override - public boolean accept( File dir, String name ) - { - return name.endsWith( "-jvmRun1.dump" ); - } - } ); + String[] dumpFiles = reportDir.list(new FilenameFilter() { + @Override + public boolean accept(File dir, String name) { + return name.endsWith("-jvmRun1.dump"); + } + }); - assertThat( dumpFiles ) - .isNotNull() - .isNotEmpty(); + assertThat(dumpFiles).isNotNull().isNotEmpty(); - for ( String dump : requireNonNull( dumpFiles ) ) - { - outputValidator.getSurefireReportsFile( dump ) - .assertContainsText( "Cyclic graph of methods" ); + for (String dump : requireNonNull(dumpFiles)) { + outputValidator.getSurefireReportsFile(dump).assertContainsText("Cyclic graph of methods"); } } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/CheckTestNgGroupThreadParallelIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/CheckTestNgGroupThreadParallelIT.java index 5b200a689b..00f7c74fd0 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/CheckTestNgGroupThreadParallelIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/CheckTestNgGroupThreadParallelIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its; /* @@ -28,16 +46,13 @@ * @author Dan Fabulich * @author Kristian Rosenvold */ -public class CheckTestNgGroupThreadParallelIT - extends SurefireJUnit4IntegrationTestCase -{ +public class CheckTestNgGroupThreadParallelIT extends SurefireJUnit4IntegrationTestCase { @Test - public void testNgGroupThreadParallel() - { - unpack( "testng-group-thread-parallel" ) - .sysProp( "testNgVersion", "5.7" ) - .sysProp( "testNgClassifier", "jdk15" ) + public void testNgGroupThreadParallel() { + unpack("testng-group-thread-parallel") + .sysProp("testNgVersion", "5.7") + .sysProp("testNgClassifier", "jdk15") .executeTest() - .verifyErrorFree( 3 ); + .verifyErrorFree(3); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/CheckTestNgJdk14IT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/CheckTestNgJdk14IT.java index 63a970e316..3a2a272000 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/CheckTestNgJdk14IT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/CheckTestNgJdk14IT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its; /* @@ -27,14 +45,10 @@ * * @author Dan Fabulich */ -public class CheckTestNgJdk14IT - extends SurefireJUnit4IntegrationTestCase -{ +public class CheckTestNgJdk14IT extends SurefireJUnit4IntegrationTestCase { @Test - public void testNgJdk14() - { - unpack( "/testng-jdk14" ).executeTest().verifyErrorFree( 1 ); - + public void testNgJdk14() { + unpack("/testng-jdk14").executeTest().verifyErrorFree(1); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/CheckTestNgListenerReporterIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/CheckTestNgListenerReporterIT.java index 0d47fb26b5..2ba3ab45ab 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/CheckTestNgListenerReporterIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/CheckTestNgListenerReporterIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its; /* @@ -38,76 +56,73 @@ * @author Dan Fabulich * @author Kristian Rosenvold */ -@RunWith( Parameterized.class ) -@SuppressWarnings( { "checkstyle:magicnumber", "checkstyle:linelength" } ) -public class CheckTestNgListenerReporterIT - extends SurefireJUnit4IntegrationTestCase -{ - @Parameters( name = "{index}: TestNG {0}" ) - public static Collection data() - { - return Arrays.asList( new Object[][] - { - { "5.6", "jdk15" }, // First TestNG version with reporter support - { "5.7", "jdk15" }, // default version from pom of the test case - { "5.10", "jdk15" }, - { "5.13", null }, // "reporterslist" param becomes String instead of List - // "listener" param becomes String instead of List +@RunWith(Parameterized.class) +@SuppressWarnings({"checkstyle:magicnumber", "checkstyle:linelength"}) +public class CheckTestNgListenerReporterIT extends SurefireJUnit4IntegrationTestCase { + @Parameters(name = "{index}: TestNG {0}") + public static Collection data() { + return Arrays.asList(new Object[][] { + {"5.6", "jdk15"}, // First TestNG version with reporter support + {"5.7", "jdk15"}, // default version from pom of the test case + {"5.10", "jdk15"}, + {"5.13", null}, // "reporterslist" param becomes String instead of List + // "listener" param becomes String instead of List - // configure(Map) in 5.14.1 and 5.14.2 is transforming List into a String with a space as separator. - // Then configure(CommandLineArgs) splits this String into a List with , or ; as separator => fail. - // If we used configure(CommandLineArgs), we would not have the problem with white spaces. - //{ "5.14.1", null, "1.5" }, // "listener" param becomes List instead of String - // Fails: Issue with 5.14.1 and 5.14.2 => join with , split with "," - // TODO will work with "configure(CommandLineArgs)" - //{ "5.14.2", null, "1.5" }, // ReporterConfig is not available + // configure(Map) in 5.14.1 and 5.14.2 is transforming List into a String with a space as separator. + // Then configure(CommandLineArgs) splits this String into a List with , or ; as separator => fail. + // If we used configure(CommandLineArgs), we would not have the problem with white spaces. + // { "5.14.1", null, "1.5" }, // "listener" param becomes List instead of String + // Fails: Issue with 5.14.1 and 5.14.2 => join with , split with "," + // TODO will work with "configure(CommandLineArgs)" + // { "5.14.2", null, "1.5" }, // ReporterConfig is not available - //{ "5.14.3", null, "1.5" }, // TestNG uses "reporter" instead of "reporterslist" - // Both String or List are possible for "listener" - // Fails: not able to test due to system dependency org.testng:guice missed the path and use to break CI - // ClassNotFoundException: com.beust.jcommander.ParameterException + // { "5.14.3", null, "1.5" }, // TestNG uses "reporter" instead of "reporterslist" + // Both String or List are possible for "listener" + // Fails: not able to test due to system dependency org.testng:guice missed the path and use to break CI + // ClassNotFoundException: com.beust.jcommander.ParameterException - //{ "5.14.4", null, "1.5" }, { "5.14.5", null, "1.5" }, // Fails: not able to test due to system dependency org.testng:guice missed the path and use to break CI - // ClassNotFoundException: com.beust.jcommander.ParameterException + // { "5.14.4", null, "1.5" }, { "5.14.5", null, "1.5" }, // Fails: not able to test due to system dependency + // org.testng:guice missed the path and use to break CI + // ClassNotFoundException: com.beust.jcommander.ParameterException - { "5.14.6", null }, // Usage of org.testng:guice removed - { "5.14.9", null }, // Latest 5.14.x TestNG version - { "6.0", null }, - { "6.14.3", null }, - { "7.0.0", null } // Currently latest TestNG version - } ); + {"5.14.6", null}, // Usage of org.testng:guice removed + {"5.14.9", null}, // Latest 5.14.x TestNG version + {"6.0", null}, + {"6.14.3", null}, + {"7.0.0", null} // Currently latest TestNG version + }); } @Parameter - @SuppressWarnings( "checkstyle:visibilitymodifier" ) + @SuppressWarnings("checkstyle:visibilitymodifier") public String version; - @Parameter( 1 ) - @SuppressWarnings( "checkstyle:visibilitymodifier" ) + @Parameter(1) + @SuppressWarnings("checkstyle:visibilitymodifier") public String classifier; @Test - public void testNgListenerReporter() - { - if ( version.equals( "5.13" ) ) - { + public void testNgListenerReporter() { + if (version.equals("5.13")) { // only 5.13 uses Google Guice, reflection which breaks jdk 16+ // module java.base does not "opens java.lang" to unnamed module @209c0b14 - assumeJavaMaxVersion( 15 ); + assumeJavaMaxVersion(15); } - final SurefireLauncher launcher = unpack( "testng-listener-reporter", "_" + version ) - .sysProp( "testNgVersion", version ); + final SurefireLauncher launcher = + unpack("testng-listener-reporter", "_" + version).sysProp("testNgVersion", version); - if ( classifier != null ) - { - launcher.sysProp( "testNgClassifier", "jdk15" ); + if (classifier != null) { + launcher.sysProp("testNgClassifier", "jdk15"); } launcher.executeTest() - .assertTestSuiteResults( 1, 0, 0, 0 ) - .getTargetFile( "resultlistener-output.txt" ).assertFileExists() - .getTargetFile( "suitelistener-output.txt" ).assertFileExists() - .getTargetFile( "reporter-output.txt" ).assertFileExists(); + .assertTestSuiteResults(1, 0, 0, 0) + .getTargetFile("resultlistener-output.txt") + .assertFileExists() + .getTargetFile("suitelistener-output.txt") + .assertFileExists() + .getTargetFile("reporter-output.txt") + .assertFileExists(); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/CheckTestNgListenersIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/CheckTestNgListenersIT.java index beb3eb6a4c..f6ee41ee14 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/CheckTestNgListenersIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/CheckTestNgListenersIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its; /* @@ -25,13 +43,9 @@ /** * Test annotation-based TestNG listener */ -public class CheckTestNgListenersIT - extends SurefireJUnit4IntegrationTestCase -{ +public class CheckTestNgListenersIT extends SurefireJUnit4IntegrationTestCase { @Test - public void testNgListenerReporter() - { - unpack( "testng-listeners" ).mavenTestFailureIgnore( true ).executeTest().assertTestSuiteResults( 1, 0, 1, 0 ); + public void testNgListenerReporter() { + unpack("testng-listeners").mavenTestFailureIgnore(true).executeTest().assertTestSuiteResults(1, 0, 1, 0); } - } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/CheckTestNgPathWithSpacesIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/CheckTestNgPathWithSpacesIT.java index 654cfc294d..feb82b9b96 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/CheckTestNgPathWithSpacesIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/CheckTestNgPathWithSpacesIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its; /* @@ -27,16 +45,13 @@ * * @author Dan Fabulich */ -public class CheckTestNgPathWithSpacesIT - extends SurefireJUnit4IntegrationTestCase -{ +public class CheckTestNgPathWithSpacesIT extends SurefireJUnit4IntegrationTestCase { @Test - public void testWithSpaces() - { - unpack( "testng-path with spaces" ) - .sysProp( "testNgVersion", "5.7" ) - .sysProp( "testNgClassifier", "jdk15" ) + public void testWithSpaces() { + unpack("testng-path with spaces") + .sysProp("testNgVersion", "5.7") + .sysProp("testNgClassifier", "jdk15") .executeTest() - .verifyErrorFree( 1 ); + .verifyErrorFree(1); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/CheckTestNgReportTestIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/CheckTestNgReportTestIT.java index f5efb122e1..368b745df1 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/CheckTestNgReportTestIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/CheckTestNgReportTestIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its; /* @@ -30,44 +48,37 @@ * * @author Dan Fabulich */ -public class CheckTestNgReportTestIT - extends SurefireJUnit4IntegrationTestCase -{ +public class CheckTestNgReportTestIT extends SurefireJUnit4IntegrationTestCase { @Test - public void testNgReport() - { - unpack( "/testng-simple" ) - .sysProp( "testNgVersion", "5.7" ) - .sysProp( "testNgClassifier", "jdk15" ) + public void testNgReport() { + unpack("/testng-simple") + .sysProp("testNgVersion", "5.7") + .sysProp("testNgClassifier", "jdk15") .addSurefireReportGoal() .executeCurrentGoals() - .verifyErrorFree( 3 ) - .getSiteFile( "surefire-report.html" ) + .verifyErrorFree(3) + .getSiteFile("surefire-report.html") .assertFileExists(); } @Test - public void shouldNotBeVerbose() - throws Exception - { - unpack( "/testng-simple" ) - .sysProp( "testNgVersion", "5.10" ) - .sysProp( "testNgClassifier", "jdk15" ) - .executeTest() - .verifyErrorFreeLog() - .assertThatLogLine( containsString( "[Parser] Running:" ), is( 0 ) ); + public void shouldNotBeVerbose() throws Exception { + unpack("/testng-simple") + .sysProp("testNgVersion", "5.10") + .sysProp("testNgClassifier", "jdk15") + .executeTest() + .verifyErrorFreeLog() + .assertThatLogLine(containsString("[Parser] Running:"), is(0)); } @Test - public void shouldBeVerbose() - throws Exception - { - unpack( "/testng-simple" ) - .sysProp( "testNgVersion", "5.10" ) - .sysProp( "testNgClassifier", "jdk15" ) - .sysProp( "surefire.testng.verbose", "10" ) - .executeTest() - .verifyErrorFreeLog() - .assertThatLogLine( containsString( "[Parser] Running:" ), is( 1 ) ); + public void shouldBeVerbose() throws Exception { + unpack("/testng-simple") + .sysProp("testNgVersion", "5.10") + .sysProp("testNgClassifier", "jdk15") + .sysProp("surefire.testng.verbose", "10") + .executeTest() + .verifyErrorFreeLog() + .assertThatLogLine(containsString("[Parser] Running:"), is(1)); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/CheckTestNgSuiteXmlIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/CheckTestNgSuiteXmlIT.java index 2870a796ab..79d18044d2 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/CheckTestNgSuiteXmlIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/CheckTestNgSuiteXmlIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its; /* @@ -28,38 +46,23 @@ * * @author Dan Fabulich */ -public class CheckTestNgSuiteXmlIT - extends SurefireJUnit4IntegrationTestCase -{ +public class CheckTestNgSuiteXmlIT extends SurefireJUnit4IntegrationTestCase { @Test - public void suiteXml() - { - unpack() - .executeTest() - .assertTestSuiteResults( 2, 0, 0, 0 ); + public void suiteXml() { + unpack().executeTest().assertTestSuiteResults(2, 0, 0, 0); } @Test - public void suiteXmlForkAlways() - { - unpack().forkAlways() - .executeTest() - .verifyTextInLog( "Tests run: 2, Failures: 0, Errors: 0, Skipped: 0" ); + public void suiteXmlForkAlways() { + unpack().forkAlways().executeTest().verifyTextInLog("Tests run: 2, Failures: 0, Errors: 0, Skipped: 0"); } @Test - public void suiteXmlForkCountTwoReuse() - { - unpack().forkCount( 2 ) - .reuseForks( true ) - .executeTest() - .assertTestSuiteResults( 2, 0, 0, 0 ); + public void suiteXmlForkCountTwoReuse() { + unpack().forkCount(2).reuseForks(true).executeTest().assertTestSuiteResults(2, 0, 0, 0); } - private SurefireLauncher unpack() - { - return unpack( "testng-suite-xml" ) - .sysProp( "testNgVersion", "5.7" ) - .sysProp( "testNgClassifier", "jdk15" ); + private SurefireLauncher unpack() { + return unpack("testng-suite-xml").sysProp("testNgVersion", "5.7").sysProp("testNgClassifier", "jdk15"); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/CheckTestNgSuiteXmlSingleIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/CheckTestNgSuiteXmlSingleIT.java index bec8422483..c1be0ce80e 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/CheckTestNgSuiteXmlSingleIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/CheckTestNgSuiteXmlSingleIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its; /* @@ -27,18 +45,14 @@ * * @author Dan Fabulich */ -public class CheckTestNgSuiteXmlSingleIT - extends SurefireJUnit4IntegrationTestCase -{ +public class CheckTestNgSuiteXmlSingleIT extends SurefireJUnit4IntegrationTestCase { @Test - public void testNgSuite() - { - unpack( "/testng-twoTestCaseSuite" ) - .sysProp( "testNgVersion", "5.7" ) - .sysProp( "testNgClassifier", "jdk15" ) - .setTestToRun( "TestNGTestTwo" ) + public void testNgSuite() { + unpack("/testng-twoTestCaseSuite") + .sysProp("testNgVersion", "5.7") + .sysProp("testNgClassifier", "jdk15") + .setTestToRun("TestNGTestTwo") .executeTest() - .verifyErrorFree( 1 ); + .verifyErrorFree(1); } - } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/CheckTestNgVersionsIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/CheckTestNgVersionsIT.java index 48ac297cca..6606bfb9e9 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/CheckTestNgVersionsIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/CheckTestNgVersionsIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its; /* @@ -40,163 +58,154 @@ * @author Dan Fabulich * @author Kristian Rosenvold */ -public class CheckTestNgVersionsIT - extends SurefireJUnit4IntegrationTestCase -{ +public class CheckTestNgVersionsIT extends SurefireJUnit4IntegrationTestCase { - @Test public void test47() - { - runTestNgTest( "4.7", "jdk15" ); + @Test + public void test47() { + runTestNgTest("4.7", "jdk15"); } @Test - @Ignore( "5.0 and 5.0.1 jars on central are malformed SUREFIRE-375 + MAVENUPLOAD-1024" ) - public void xXXtest50() - { - runTestNgTest( "5.0", "jdk15" ); + @Ignore("5.0 and 5.0.1 jars on central are malformed SUREFIRE-375 + MAVENUPLOAD-1024") + public void xXXtest50() { + runTestNgTest("5.0", "jdk15"); } @Test - @Ignore( "5.0 and 5.0.1 jars on central are malformed SUREFIRE-375 + MAVENUPLOAD-1024" ) - public void xXXtest501() - { - runTestNgTest( "5.0.1", "jdk15" ); + @Ignore("5.0 and 5.0.1 jars on central are malformed SUREFIRE-375 + MAVENUPLOAD-1024") + public void xXXtest501() { + runTestNgTest("5.0.1", "jdk15"); } - @Test public void test502() - { - runTestNgTest( "5.0.2", "jdk15" ); + @Test + public void test502() { + runTestNgTest("5.0.2", "jdk15"); } - @Test public void test51() - { - runTestNgTest( "5.1", "jdk15" ); + @Test + public void test51() { + runTestNgTest("5.1", "jdk15"); } - @Test public void test55() - { - runTestNgTest( "5.5", "jdk15" ); + @Test + public void test55() { + runTestNgTest("5.5", "jdk15"); } - @Test public void test56() - { - runTestNgTest( "5.6", "jdk15" ); + @Test + public void test56() { + runTestNgTest("5.6", "jdk15"); } - @Test public void test57() - { - runTestNgTest( "5.7", "jdk15" ); + @Test + public void test57() { + runTestNgTest("5.7", "jdk15"); } - @Test public void test58() - { - runTestNgTest( "5.8", "jdk15" ); + @Test + public void test58() { + runTestNgTest("5.8", "jdk15"); } - @Test public void test59() - { - runTestNgTest( "5.9", "jdk15" ); + @Test + public void test59() { + runTestNgTest("5.9", "jdk15"); } - @Test public void test510() - { - runTestNgTest( "5.10", "jdk15" ); + @Test + public void test510() { + runTestNgTest("5.10", "jdk15"); } - @Test public void test511() - { - runTestNgTest( "5.11", "jdk15" ); + @Test + public void test511() { + runTestNgTest("5.11", "jdk15"); } - @Test public void test512() - { - runTestNgTest( "5.12.1" ); + @Test + public void test512() { + runTestNgTest("5.12.1"); } - @Test public void test513() - { - runTestNgTest( "5.13" ); + @Test + public void test513() { + runTestNgTest("5.13"); } - @Test public void test5131() - { - runTestNgTest( "5.13.1" ); + @Test + public void test5131() { + runTestNgTest("5.13.1"); } - @Test public void test514() - { - runTestNgTest( "5.14" ); + @Test + public void test514() { + runTestNgTest("5.14"); } - @Test public void test5141() - { - runTestNgTest( "5.14.1" ); + @Test + public void test5141() { + runTestNgTest("5.14.1"); } - @Test public void test5142() - { - runTestNgTest( "5.14.2" ); + @Test + public void test5142() { + runTestNgTest("5.14.2"); } - @Test public void test60() - { - runTestNgTest( "6.0" ); + @Test + public void test60() { + runTestNgTest("6.0"); } - @Test public void test685() - { - runTestNgTestWithRunOrder( "6.8.5" ); + @Test + public void test685() { + runTestNgTestWithRunOrder("6.8.5"); } - private void runTestNgTestWithRunOrder( String version ) - { - runTestNgTest( version, null, true ); + private void runTestNgTestWithRunOrder(String version) { + runTestNgTest(version, null, true); } - private void runTestNgTest( String version ) - { - runTestNgTest( version, null, false ); + private void runTestNgTest(String version) { + runTestNgTest(version, null, false); } - private void runTestNgTest( String version, String classifier ) - { - runTestNgTest( version, classifier, false ); + private void runTestNgTest(String version, String classifier) { + runTestNgTest(version, classifier, false); } - private void runTestNgTest( String version, String classifier, boolean validateRunOrder ) - { - final SurefireLauncher launcher = unpack( "testng-simple" ) - .sysProp( "testNgVersion", version ); + private void runTestNgTest(String version, String classifier, boolean validateRunOrder) { + final SurefireLauncher launcher = unpack("testng-simple").sysProp("testNgVersion", version); - if ( classifier != null ) - { - launcher.sysProp( "testNgClassifier", classifier ); + if (classifier != null) { + launcher.sysProp("testNgClassifier", classifier); } final OutputValidator outputValidator = launcher.executeTest(); - outputValidator.assertTestSuiteResults( 3, 0, 0, 0 ); + outputValidator.assertTestSuiteResults(3, 0, 0, 0); - if ( validateRunOrder ) - { + if (validateRunOrder) { // assert correct run order of tests - List report = HelperAssertions.extractReports( outputValidator.getBaseDir() ); + List report = HelperAssertions.extractReports(outputValidator.getBaseDir()); - assertEquals( 3, report.size() ); + assertEquals(3, report.size()); - assertTrue( "TestNGSuiteTestC was executed first", - getTestClass( report, 0 ).endsWith( "TestNGSuiteTestC" ) ); + assertTrue( + "TestNGSuiteTestC was executed first", + getTestClass(report, 0).endsWith("TestNGSuiteTestC")); - assertTrue( "TestNGSuiteTestB was executed second", - getTestClass( report, 1 ).endsWith( "TestNGSuiteTestB" ) ); + assertTrue( + "TestNGSuiteTestB was executed second", + getTestClass(report, 1).endsWith("TestNGSuiteTestB")); - assertTrue( "TestNGSuiteTestA was executed last", - getTestClass( report, 2 ).endsWith( "TestNGSuiteTestA" ) ); + assertTrue( + "TestNGSuiteTestA was executed last", + getTestClass(report, 2).endsWith("TestNGSuiteTestA")); } } - private String getTestClass( List report, int i ) - { - return report.get( i ).getFullClassName(); + private String getTestClass(List report, int i) { + return report.get(i).getFullClassName(); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/ClassPathOrderIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/ClassPathOrderIT.java index dfea90a922..d85d945d0e 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/ClassPathOrderIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/ClassPathOrderIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its; /* @@ -28,12 +46,9 @@ * @author Dan Fabulich * @author Kristian Rosenvold */ -public class ClassPathOrderIT - extends SurefireJUnit4IntegrationTestCase -{ +public class ClassPathOrderIT extends SurefireJUnit4IntegrationTestCase { @Test - public void classPathOrder() - { - unpack( "/classpath-order" ).executeTest().verifyErrorFree( 2 ); + public void classPathOrder() { + unpack("/classpath-order").executeTest().verifyErrorFree(2); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/ClasspathFilteringIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/ClasspathFilteringIT.java index 48a18e1e76..ca4db9907c 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/ClasspathFilteringIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/ClasspathFilteringIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its; /* @@ -27,12 +45,9 @@ * * @author pgier */ -public class ClasspathFilteringIT - extends SurefireJUnit4IntegrationTestCase -{ +public class ClasspathFilteringIT extends SurefireJUnit4IntegrationTestCase { @Test - public void additionalClasspath() - { - unpack( "classpath-filtering" ).debugLogging().executeTest().verifyErrorFree( 1 ); + public void additionalClasspath() { + unpack("classpath-filtering").debugLogging().executeTest().verifyErrorFree(1); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/ClasspathScopeFilteringIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/ClasspathScopeFilteringIT.java index ca64d874db..b59b1364f3 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/ClasspathScopeFilteringIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/ClasspathScopeFilteringIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its; /* @@ -28,12 +46,9 @@ * @author pgier * @author Kristian Rosenvold */ -public class ClasspathScopeFilteringIT - extends SurefireJUnit4IntegrationTestCase -{ +public class ClasspathScopeFilteringIT extends SurefireJUnit4IntegrationTestCase { @Test - public void additionalClasspath() - { - unpack( "classpath-scope-filtering" ).executeTest().verifyErrorFree( 1 ); + public void additionalClasspath() { + unpack("classpath-scope-filtering").executeTest().verifyErrorFree(1); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/ConsoleOutputIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/ConsoleOutputIT.java index b02c57dd8a..e866cfc2d7 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/ConsoleOutputIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/ConsoleOutputIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its; /* @@ -40,117 +58,91 @@ * * @author Kristian Rosenvold */ -@RunWith( Parameterized.class ) -public class ConsoleOutputIT - extends SurefireJUnit4IntegrationTestCase -{ - private static final String LEGACY_FORK_NODE = - "org.apache.maven.plugin.surefire.extensions.LegacyForkNodeFactory"; +@RunWith(Parameterized.class) +public class ConsoleOutputIT extends SurefireJUnit4IntegrationTestCase { + private static final String LEGACY_FORK_NODE = "org.apache.maven.plugin.surefire.extensions.LegacyForkNodeFactory"; private static final String SUREFIRE_FORK_NODE = - "org.apache.maven.plugin.surefire.extensions.SurefireForkNodeFactory"; + "org.apache.maven.plugin.surefire.extensions.SurefireForkNodeFactory"; @Parameters - public static Iterable data() - { + public static Iterable data() { ArrayList args = new ArrayList<>(); - args.add( new Object[] { "tcp" } ); - args.add( new Object[] { null } ); + args.add(new Object[] {"tcp"}); + args.add(new Object[] {null}); return args; } @Parameter - @SuppressWarnings( "checkstyle:visibilitymodifier" ) + @SuppressWarnings("checkstyle:visibilitymodifier") public String profileId; @Test - public void properNewlinesAndEncodingWithDefaultEncodings() throws Exception - { + public void properNewlinesAndEncodingWithDefaultEncodings() throws Exception { OutputValidator outputValidator = unpack().forkOnce().executeTest(); - validate( outputValidator, true ); + validate(outputValidator, true); } @Test - public void properNewlinesAndEncodingWithDifferentEncoding() throws Exception - { - OutputValidator outputValidator = unpack() - .forkOnce() - .argLine( "-Dfile.encoding=UTF-16" ) - .executeTest(); - validate( outputValidator, true ); + public void properNewlinesAndEncodingWithDifferentEncoding() throws Exception { + OutputValidator outputValidator = + unpack().forkOnce().argLine("-Dfile.encoding=UTF-16").executeTest(); + validate(outputValidator, true); } @Test - public void properNewlinesAndEncodingWithoutFork() throws Exception - { - OutputValidator outputValidator = unpack() - .forkNever() - .executeTest(); - validate( outputValidator, false ); + public void properNewlinesAndEncodingWithoutFork() throws Exception { + OutputValidator outputValidator = unpack().forkNever().executeTest(); + validate(outputValidator, false); } - private SurefireLauncher unpack() - { - SurefireLauncher launcher = - unpack( "/consoleOutput", profileId == null ? "" : "-" + profileId ) + private SurefireLauncher unpack() { + SurefireLauncher launcher = unpack("/consoleOutput", profileId == null ? "" : "-" + profileId) .debugLogging(); - if ( profileId != null ) - { - launcher.activateProfile( profileId ); + if (profileId != null) { + launcher.activateProfile(profileId); } return launcher; } - private void validate( final OutputValidator outputValidator, boolean canFork ) - throws Exception - { - TestFile xmlReportFile = outputValidator.getSurefireReportsXmlFile( "TEST-consoleOutput.Test1.xml" ); - xmlReportFile.assertContainsText( "SoutLine" ); - xmlReportFile.assertContainsText( "äöüß" ); - xmlReportFile.assertContainsText( "failing with ü" ); + private void validate(final OutputValidator outputValidator, boolean canFork) throws Exception { + TestFile xmlReportFile = outputValidator.getSurefireReportsXmlFile("TEST-consoleOutput.Test1.xml"); + xmlReportFile.assertContainsText("SoutLine"); + xmlReportFile.assertContainsText("äöüß"); + xmlReportFile.assertContainsText("failing with ü"); - TestFile outputFile = outputValidator.getSurefireReportsFile( "consoleOutput.Test1-output.txt", UTF_8 ); - outputFile.assertContainsText( "SoutAgain" ); - outputFile.assertContainsText( "SoutLine" ); - outputFile.assertContainsText( "äöüß" ); + TestFile outputFile = outputValidator.getSurefireReportsFile("consoleOutput.Test1-output.txt", UTF_8); + outputFile.assertContainsText("SoutAgain"); + outputFile.assertContainsText("SoutLine"); + outputFile.assertContainsText("äöüß"); String cls = profileId == null ? LEGACY_FORK_NODE : SUREFIRE_FORK_NODE; - if ( canFork ) - { - outputValidator - .assertThatLogLine( - containsString( "Found implementation of fork node factory: " + cls ), - equalTo( 1 ) ); + if (canFork) { + outputValidator.assertThatLogLine( + containsString("Found implementation of fork node factory: " + cls), equalTo(1)); } } @Test - public void largerSoutThanMemory() throws Exception - { - SurefireLauncher launcher = - unpackNoisy() - .setMavenOpts( "-Xmx64m" ) - .sysProp( "thousand", "32000" ); + public void largerSoutThanMemory() throws Exception { + SurefireLauncher launcher = unpackNoisy().setMavenOpts("-Xmx64m").sysProp("thousand", "32000"); String cls = profileId == null ? LEGACY_FORK_NODE : SUREFIRE_FORK_NODE; launcher.executeTest() - .verifyErrorFreeLog() - .assertThatLogLine( containsString( "Found implementation of fork node factory: " + cls ), equalTo( 1 ) ); + .verifyErrorFreeLog() + .assertThatLogLine(containsString("Found implementation of fork node factory: " + cls), equalTo(1)); } - private SurefireLauncher unpackNoisy() - { - SurefireLauncher launcher = - unpack( "consoleoutput-noisy", profileId == null ? "" : "-" + profileId ) + private SurefireLauncher unpackNoisy() { + SurefireLauncher launcher = unpack("consoleoutput-noisy", profileId == null ? "" : "-" + profileId) .debugLogging(); - if ( profileId != null ) - { - launcher.activateProfile( profileId ); + if (profileId != null) { + launcher.activateProfile(profileId); } return launcher; diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/CrashDetectionIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/CrashDetectionIT.java index e044defa8b..6d733b3735 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/CrashDetectionIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/CrashDetectionIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its; /* @@ -25,40 +43,34 @@ /** * @author Kristian Rosenvold */ -public class CrashDetectionIT - extends SurefireJUnit4IntegrationTestCase -{ +public class CrashDetectionIT extends SurefireJUnit4IntegrationTestCase { @Test - public void crashInFork() - { - unpack( "crash-detection" ).maven().withFailure().executeTest(); + public void crashInFork() { + unpack("crash-detection").maven().withFailure().executeTest(); } @Test - public void crashInReusableFork() - { - unpack( "crash-detection" ) - .forkPerThread( getThreadCount() ) - .threadCount( getThreadCount() ) + public void crashInReusableFork() { + unpack("crash-detection") + .forkPerThread(getThreadCount()) + .threadCount(getThreadCount()) .maven() .withFailure() .executeTest(); } @Test - public void hardCrashInReusableFork() - { - unpack( "crash-detection" ) - .forkPerThread( getThreadCount() ) - .threadCount( getThreadCount() ) - .addGoal( "-DkillHard=true" ) + public void hardCrashInReusableFork() { + unpack("crash-detection") + .forkPerThread(getThreadCount()) + .threadCount(getThreadCount()) + .addGoal("-DkillHard=true") .maven() .withFailure() .executeTest(); } - protected int getThreadCount() - { + protected int getThreadCount() { return 1; } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/DefaultConfigurationIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/DefaultConfigurationIT.java index b0907b87d8..53f728f25c 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/DefaultConfigurationIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/DefaultConfigurationIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its; /* @@ -27,12 +45,9 @@ * * @author Dan Fabulich */ -public class DefaultConfigurationIT - extends SurefireJUnit4IntegrationTestCase -{ +public class DefaultConfigurationIT extends SurefireJUnit4IntegrationTestCase { @Test - public void defaultConfiguration() - { - executeErrorFreeTest( "default-configuration", 1 ); + public void defaultConfiguration() { + executeErrorFreeTest("default-configuration", 1); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/EnvironmentVariableIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/EnvironmentVariableIT.java index 7f38a73d71..09aefda48e 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/EnvironmentVariableIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/EnvironmentVariableIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its; /* @@ -27,14 +45,11 @@ * * @author Dan Fabulich */ -public class EnvironmentVariableIT - extends SurefireJUnit4IntegrationTestCase -{ +public class EnvironmentVariableIT extends SurefireJUnit4IntegrationTestCase { @Test - public void environmentVariable() - { + public void environmentVariable() { - executeErrorFreeTest( "junit44-environment", 1 ); + executeErrorFreeTest("junit44-environment", 1); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/EnvironmentVariablesIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/EnvironmentVariablesIT.java index 97342dc611..6477234aa5 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/EnvironmentVariablesIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/EnvironmentVariablesIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its; /* @@ -25,40 +43,34 @@ /** * SUREFIRE-763 Asserts that environment variables are correctly populated using "useSystemClassLoader=false" * SUREFIRE-963 Asserts that empty environment variables are read as "". - * + * * @author Kristian Rosenvold * @author Christophe Deneux */ -public class EnvironmentVariablesIT - extends SurefireJUnit4IntegrationTestCase -{ +public class EnvironmentVariablesIT extends SurefireJUnit4IntegrationTestCase { @Test - public void testWhenUseSystemClassLoader() - { - unpack( "/environment-variables" ) + public void testWhenUseSystemClassLoader() { + unpack("/environment-variables") .debugLogging() - .addGoal( "-DuseSystemClassLoader=true" ) + .addGoal("-DuseSystemClassLoader=true") .executeTest(); } @Test - public void testWhenDontUseSystemClassLoader() - { - unpack( "/environment-variables" ) + public void testWhenDontUseSystemClassLoader() { + unpack("/environment-variables") .debugLogging() - .addGoal( "-DuseSystemClassLoader=false" ) + .addGoal("-DuseSystemClassLoader=false") .executeTest(); } @Test - public void testExcludedEnv() - { - unpack( "/environment-variables" ) + public void testExcludedEnv() { + unpack("/environment-variables") .maven() .debugLogging() - .addEnvVar( "UNDEFINED_VAR", "dwdijoi" ) - .sysProp( "surefire.excludedEnvironmentVariables", "UNDEFINED_VAR" ) + .addEnvVar("UNDEFINED_VAR", "dwdijoi") + .sysProp("surefire.excludedEnvironmentVariables", "UNDEFINED_VAR") .executeTest(); } - -} \ No newline at end of file +} diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/FailFastJUnitIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/FailFastJUnitIT.java index 8f18ec1958..c21ac45884 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/FailFastJUnitIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/FailFastJUnitIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its; /* @@ -29,13 +47,10 @@ * @author Tibor Digana (tibor17) * @since 2.19 */ -public class FailFastJUnitIT - extends AbstractFailFastIT -{ - @Parameters( name = "{0}" ) - @SuppressWarnings( { "checkstyle:visibilitymodifier", "checkstyle:linelength" } ) - public static Iterable data() - { +public class FailFastJUnitIT extends AbstractFailFastIT { + @Parameters(name = "{0}") + @SuppressWarnings({"checkstyle:visibilitymodifier", "checkstyle:linelength"}) + public static Iterable data() { /** * reuseForks=false is not used because of race conditions and unpredictable commands received by * MasterProcessReader, this feature has significant limitation. @@ -51,26 +66,25 @@ public static Iterable data() // errors // skipped // pipes - args.add( new Object[] { "junit4-oneFork-ff1", "junit4", props( 1, 1, true ), 5, 0, 1, 4, true } ); - args.add( new Object[] { "junit47-oneFork-ff1", "junit47", props( 1, 1, true ), 5, 0, 1, 4, true } ); - args.add( new Object[] { "junit4-oneFork-ff2", "junit4", props( 1, 2, true ), 5, 0, 2, 3, true } ); - args.add( new Object[] { "junit47-oneFork-ff2", "junit47", props( 1, 2, true ), 5, 0, 2, 3, true } ); - args.add( new Object[] { "junit4-twoForks-ff1", "junit4", props( 2, 1, true ), 5, 0, 2, 3, true } ); - args.add( new Object[] { "junit47-twoForks-ff1", "junit47", props( 2, 1, true ), 5, 0, 2, 3, true } ); - args.add( new Object[] { "junit4-twoForks-ff2", "junit4", props( 2, 2, true ), 5, 0, 2, 2, true } ); - args.add( new Object[] { "junit4-twoForks-ff2-tcp", "junit4", props( 2, 2, true ), 5, 0, 2, 2, false } ); - args.add( new Object[] { "junit47-twoForks-ff2", "junit47", props( 2, 2, true ), 5, 0, 2, 2, true } ); - args.add( new Object[] { "junit4-oneFork-ff3", "junit4", props( 1, 3, true ), 5, 0, 2, 0, true } ); - args.add( new Object[] { "junit47-oneFork-ff3", "junit47", props( 1, 3, true ), 5, 0, 2, 0, true } ); - args.add( new Object[] { "junit4-twoForks-ff3", "junit4", props( 2, 3, true ), 5, 0, 2, 0, true } ); - args.add( new Object[] { "junit47-twoForks-ff3", "junit47", props( 2, 3, true ), 5, 0, 2, 0, true } ); - args.add( new Object[] { "junit47-twoForks-ff3-tcp", "junit47", props( 2, 3, true ), 5, 0, 2, 0, false } ); + args.add(new Object[] {"junit4-oneFork-ff1", "junit4", props(1, 1, true), 5, 0, 1, 4, true}); + args.add(new Object[] {"junit47-oneFork-ff1", "junit47", props(1, 1, true), 5, 0, 1, 4, true}); + args.add(new Object[] {"junit4-oneFork-ff2", "junit4", props(1, 2, true), 5, 0, 2, 3, true}); + args.add(new Object[] {"junit47-oneFork-ff2", "junit47", props(1, 2, true), 5, 0, 2, 3, true}); + args.add(new Object[] {"junit4-twoForks-ff1", "junit4", props(2, 1, true), 5, 0, 2, 3, true}); + args.add(new Object[] {"junit47-twoForks-ff1", "junit47", props(2, 1, true), 5, 0, 2, 3, true}); + args.add(new Object[] {"junit4-twoForks-ff2", "junit4", props(2, 2, true), 5, 0, 2, 2, true}); + args.add(new Object[] {"junit4-twoForks-ff2-tcp", "junit4", props(2, 2, true), 5, 0, 2, 2, false}); + args.add(new Object[] {"junit47-twoForks-ff2", "junit47", props(2, 2, true), 5, 0, 2, 2, true}); + args.add(new Object[] {"junit4-oneFork-ff3", "junit4", props(1, 3, true), 5, 0, 2, 0, true}); + args.add(new Object[] {"junit47-oneFork-ff3", "junit47", props(1, 3, true), 5, 0, 2, 0, true}); + args.add(new Object[] {"junit4-twoForks-ff3", "junit4", props(2, 3, true), 5, 0, 2, 0, true}); + args.add(new Object[] {"junit47-twoForks-ff3", "junit47", props(2, 3, true), 5, 0, 2, 0, true}); + args.add(new Object[] {"junit47-twoForks-ff3-tcp", "junit47", props(2, 3, true), 5, 0, 2, 0, false}); return args; } @Override - protected String withProvider() - { + protected String withProvider() { return "junit"; } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/FailFastTestNgIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/FailFastTestNgIT.java index d8df1d4fa6..b3671f0a39 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/FailFastTestNgIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/FailFastTestNgIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its; /* @@ -29,14 +47,11 @@ * @author Tibor Digana (tibor17) * @since 2.19 */ -public class FailFastTestNgIT - extends AbstractFailFastIT -{ +public class FailFastTestNgIT extends AbstractFailFastIT { - @Parameters( name = "{0}" ) - @SuppressWarnings( "checkstyle:linelength" ) - public static Iterable data() - { + @Parameters(name = "{0}") + @SuppressWarnings("checkstyle:linelength") + public static Iterable data() { /** * reuseForks=false is not used because of race conditions and unpredictable commands received by * MasterProcessReader, this feature has significant limitation. @@ -52,20 +67,19 @@ public static Iterable data() // errors // skipped // pipes - args.add( new Object[] { "testng-oneFork-ff1", null, props( 1, 1, true ), 5, 1, 0, 4, true } ); - args.add( new Object[] { "testng-oneFork-ff2", null, props( 1, 2, true ), 5, 2, 0, 3, true } ); - args.add( new Object[] { "testng-twoForks-ff1", null, props( 2, 1, true ), 5, 2, 0, 3, true } ); - args.add( new Object[] { "testng-twoForks-ff2", null, props( 2, 2, true ), 5, 2, 0, 2, true } ); - args.add( new Object[] { "testng-twoForks-ff2-tcp", null, props( 2, 2, true ), 5, 2, 0, 2, false } ); - args.add( new Object[] { "testng-oneFork-ff3", null, props( 1, 3, true ), 5, 2, 0, 0, true } ); - args.add( new Object[] { "testng-twoForks-ff3", null, props( 2, 3, true ), 5, 2, 0, 0, true } ); - args.add( new Object[] { "testng-twoForks-ff3-tcp", null, props( 2, 3, true ), 5, 2, 0, 0, false } ); + args.add(new Object[] {"testng-oneFork-ff1", null, props(1, 1, true), 5, 1, 0, 4, true}); + args.add(new Object[] {"testng-oneFork-ff2", null, props(1, 2, true), 5, 2, 0, 3, true}); + args.add(new Object[] {"testng-twoForks-ff1", null, props(2, 1, true), 5, 2, 0, 3, true}); + args.add(new Object[] {"testng-twoForks-ff2", null, props(2, 2, true), 5, 2, 0, 2, true}); + args.add(new Object[] {"testng-twoForks-ff2-tcp", null, props(2, 2, true), 5, 2, 0, 2, false}); + args.add(new Object[] {"testng-oneFork-ff3", null, props(1, 3, true), 5, 2, 0, 0, true}); + args.add(new Object[] {"testng-twoForks-ff3", null, props(2, 3, true), 5, 2, 0, 0, true}); + args.add(new Object[] {"testng-twoForks-ff3-tcp", null, props(2, 3, true), 5, 2, 0, 0, false}); return args; } @Override - protected String withProvider() - { + protected String withProvider() { return "testng"; } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/ForkConsoleOutputIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/ForkConsoleOutputIT.java index 6aac33068e..702ce98b76 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/ForkConsoleOutputIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/ForkConsoleOutputIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its; /* @@ -30,58 +48,50 @@ * * @author Kristian Rosenvold */ -public class ForkConsoleOutputIT - extends SurefireJUnit4IntegrationTestCase -{ +public class ForkConsoleOutputIT extends SurefireJUnit4IntegrationTestCase { @Test - public void printSummaryTrueWithRedirect() - { + public void printSummaryTrueWithRedirect() { unpack().setForkJvm() - .redirectToFile( true ) - .printSummary( true ) + .redirectToFile(true) + .printSummary(true) .executeTest() - .getSurefireReportsFile( "forkConsoleOutput.Test1-output.txt" ) + .getSurefireReportsFile("forkConsoleOutput.Test1-output.txt") .assertFileExists(); } @Test - public void printSummaryTrueWithoutRedirect() - { + public void printSummaryTrueWithoutRedirect() { unpack().setForkJvm() - .redirectToFile( false ) - .printSummary( true ) + .redirectToFile(false) + .printSummary(true) .executeTest() - .getSurefireReportsFile( "forkConsoleOutput.Test1-output.txt" ) + .getSurefireReportsFile("forkConsoleOutput.Test1-output.txt") .assertFileNotExists(); } @Test - public void printSummaryFalseWithRedirect() - { + public void printSummaryFalseWithRedirect() { unpack().setForkJvm() - .redirectToFile( true ) - .printSummary( false ) + .redirectToFile(true) + .printSummary(false) .debugLogging() .showErrorStackTraces() .executeTest() - .getSurefireReportsFile( "forkConsoleOutput.Test1-output.txt" ) + .getSurefireReportsFile("forkConsoleOutput.Test1-output.txt") .assertFileExists(); } @Test - public void printSummaryFalseWithoutRedirect() - { + public void printSummaryFalseWithoutRedirect() { unpack().setForkJvm() - .redirectToFile( false ) - .printSummary( false ) + .redirectToFile(false) + .printSummary(false) .executeTest() - .getSurefireReportsFile( "forkConsoleOutput.Test1-output.txt" ) + .getSurefireReportsFile("forkConsoleOutput.Test1-output.txt") .assertFileNotExists(); } - - private SurefireLauncher unpack() - { - return unpack( "/fork-consoleOutput" ); + private SurefireLauncher unpack() { + return unpack("/fork-consoleOutput"); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/ForkConsoleOutputWithErrorsIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/ForkConsoleOutputWithErrorsIT.java index e5feb7fe91..648a4e97e5 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/ForkConsoleOutputWithErrorsIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/ForkConsoleOutputWithErrorsIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its; /* @@ -29,19 +47,16 @@ * * @author Kristian Rosenvold */ -public class ForkConsoleOutputWithErrorsIT - extends SurefireJUnit4IntegrationTestCase -{ +public class ForkConsoleOutputWithErrorsIT extends SurefireJUnit4IntegrationTestCase { @Test - public void xmlFileContainsConsoleOutput() - { - unpack( "/fork-consoleOutputWithErrors" ) + public void xmlFileContainsConsoleOutput() { + unpack("/fork-consoleOutputWithErrors") .setForkJvm() .failNever() - .redirectToFile( true ) + .redirectToFile(true) .executeTest() - .getSurefireReportsXmlFile( "TEST-forkConsoleOutput.Test2.xml" ) - .assertContainsText( "sout: Will Fail soon" ) - .assertContainsText( "serr: Will Fail now" ); + .getSurefireReportsXmlFile("TEST-forkConsoleOutput.Test2.xml") + .assertContainsText("sout: Will Fail soon") + .assertContainsText("serr: Will Fail now"); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/ForkCountIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/ForkCountIT.java index 0eebb83e12..1cb7090f70 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/ForkCountIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/ForkCountIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its; /* @@ -19,10 +37,6 @@ * under the License. */ -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.fail; - import java.util.Arrays; import java.util.HashSet; import java.util.Set; @@ -34,171 +48,148 @@ import org.junit.BeforeClass; import org.junit.Test; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.fail; + /** * Test forkCount and reuseForks - * + * * @author Dan Fabulich */ -public class ForkCountIT - extends SurefireJUnit4IntegrationTestCase -{ +public class ForkCountIT extends SurefireJUnit4IntegrationTestCase { private OutputValidator outputValidator; @BeforeClass - public static void installDumpPidPlugin() - { - unpack( ForkCountIT.class, "test-helper-dump-pid-plugin", "plugin" ).executeInstall(); + public static void installDumpPidPlugin() { + unpack(ForkCountIT.class, "test-helper-dump-pid-plugin", "plugin").executeInstall(); } @Test - public void testForkNever() - { - String[] pids = doTest( unpack( getProject() ).forkNever() ); - assertSamePids( pids ); - assertEndWith( pids, "_1_1", 3 ); - assertEquals( "my pid is equal to pid 1 of the test", getMainPID(), pids[0] ); + public void testForkNever() { + String[] pids = doTest(unpack(getProject()).forkNever()); + assertSamePids(pids); + assertEndWith(pids, "_1_1", 3); + assertEquals("my pid is equal to pid 1 of the test", getMainPID(), pids[0]); } @Test - public void testForkOncePerThreadSingleThread() - { + public void testForkOncePerThreadSingleThread() { int threadCount = 1; - String[] pids = doTest( unpack( getProject() ) - .setForkJvm() - .forkPerThread( threadCount ) - .threadCount( threadCount ) ); - assertSamePids( pids ); - assertEndWith( pids, "_1_1", 3 ); - assertNotEquals( "pid 1 is not the same as the main process' pid", pids[0], getMainPID() ); + String[] pids = doTest( + unpack(getProject()).setForkJvm().forkPerThread(threadCount).threadCount(threadCount)); + assertSamePids(pids); + assertEndWith(pids, "_1_1", 3); + assertNotEquals("pid 1 is not the same as the main process' pid", pids[0], getMainPID()); } @Test - public void testForkOncePerThreadTwoThreads() - { + public void testForkOncePerThreadTwoThreads() { int threadCount = 2; - String[] pids = doTest( unpack( getProject() ) - .forkPerThread( threadCount ) - .threadCount( threadCount ) - .addGoal( "-DsleepLength=7200" ) ); - assertDifferentPids( pids, 2 ); - assertNotEquals( "pid 1 is not the same as the main process' pid", pids[0], getMainPID() ); + String[] pids = doTest(unpack(getProject()) + .forkPerThread(threadCount) + .threadCount(threadCount) + .addGoal("-DsleepLength=7200")); + assertDifferentPids(pids, 2); + assertNotEquals("pid 1 is not the same as the main process' pid", pids[0], getMainPID()); } @Test - public void testForkCountOneNoReuse() - { - String[] pids = doTest( unpack( getProject() ).setForkJvm().forkCount( 1 ).reuseForks( false ) ); - assertDifferentPids( pids ); - assertEndWith( pids, "_1_1", 3 ); - assertNotEquals( "pid 1 is not the same as the main process' pid", pids[0], getMainPID() ); + public void testForkCountOneNoReuse() { + String[] pids = doTest(unpack(getProject()).setForkJvm().forkCount(1).reuseForks(false)); + assertDifferentPids(pids); + assertEndWith(pids, "_1_1", 3); + assertNotEquals("pid 1 is not the same as the main process' pid", pids[0], getMainPID()); } @Test - public void testForkCountOneReuse() - { - String[] pids = doTest( unpack( getProject() ).setForkJvm().forkCount( 1 ).reuseForks( true ) ); - assertSamePids( pids ); - assertEndWith( pids, "_1_1", 3 ); - assertNotEquals( "pid 1 is not the same as the main process' pid", pids[0], getMainPID() ); + public void testForkCountOneReuse() { + String[] pids = doTest(unpack(getProject()).setForkJvm().forkCount(1).reuseForks(true)); + assertSamePids(pids); + assertEndWith(pids, "_1_1", 3); + assertNotEquals("pid 1 is not the same as the main process' pid", pids[0], getMainPID()); } @Test - public void testForkCountTwoNoReuse() - { - String[] pids = doTest( unpack( getProject() ).setForkJvm().forkCount( 2 ).reuseForks( false ) - .addGoal( "-DsleepLength=7200" ) ); - assertDifferentPids( pids ); - assertNotEquals( "pid 1 is not the same as the main process' pid", pids[0], getMainPID() ); + public void testForkCountTwoNoReuse() { + String[] pids = doTest( + unpack(getProject()).setForkJvm().forkCount(2).reuseForks(false).addGoal("-DsleepLength=7200")); + assertDifferentPids(pids); + assertNotEquals("pid 1 is not the same as the main process' pid", pids[0], getMainPID()); } @Test - public void testForkCountTwoReuse() - { + public void testForkCountTwoReuse() { String[] pids = - doTest( unpack( getProject() ).forkCount( 2 ).reuseForks( true ).addGoal( "-DsleepLength=7200" ) ); - assertDifferentPids( pids, 2 ); - assertNotEquals( "pid 1 is not the same as the main process' pid", pids[0], getMainPID() ); + doTest(unpack(getProject()).forkCount(2).reuseForks(true).addGoal("-DsleepLength=7200")); + assertDifferentPids(pids, 2); + assertNotEquals("pid 1 is not the same as the main process' pid", pids[0], getMainPID()); } - private void assertEndWith( String[] pids, String suffix, int expectedMatches ) - { + private void assertEndWith(String[] pids, String suffix, int expectedMatches) { int matches = 0; - for ( String pid : pids ) - { - if ( pid.endsWith( suffix ) ) - { + for (String pid : pids) { + if (pid.endsWith(suffix)) { matches++; } } - assertEquals( "suffix " + suffix + " matched the correct number of pids", expectedMatches, matches ); + assertEquals("suffix " + suffix + " matched the correct number of pids", expectedMatches, matches); } - private void assertDifferentPids( String[] pids, int numOfDifferentPids ) - { - Set pidSet = new HashSet<>( Arrays.asList( pids ) ); - assertEquals( "number of different pids is not as expected", numOfDifferentPids, pidSet.size() ); + private void assertDifferentPids(String[] pids, int numOfDifferentPids) { + Set pidSet = new HashSet<>(Arrays.asList(pids)); + assertEquals("number of different pids is not as expected", numOfDifferentPids, pidSet.size()); } @Test - public void testForkOnce() - { - String[] pids = doTest( unpack( getProject() ).forkOnce() ); - assertSamePids( pids ); - assertNotEquals( "pid 1 is not the same as the main process' pid", pids[0], getMainPID() ); + public void testForkOnce() { + String[] pids = doTest(unpack(getProject()).forkOnce()); + assertSamePids(pids); + assertNotEquals("pid 1 is not the same as the main process' pid", pids[0], getMainPID()); } - private String getMainPID() - { - final TestFile targetFile = outputValidator.getTargetFile( "maven.pid" ); + private String getMainPID() { + final TestFile targetFile = outputValidator.getTargetFile("maven.pid"); String pid = targetFile.slurpFile(); return pid + " testValue_1_1"; } - private void assertSamePids( String[] pids ) - { - assertEquals( "pid 1 didn't match pid 2", pids[0], pids[1] ); - assertEquals( "pid 1 didn't match pid 3", pids[0], pids[2] ); + private void assertSamePids(String[] pids) { + assertEquals("pid 1 didn't match pid 2", pids[0], pids[1]); + assertEquals("pid 1 didn't match pid 3", pids[0], pids[2]); } - private void assertDifferentPids( String[] pids ) - { - if ( pids[0].equals( pids[1] ) ) - { - fail( "pid 1 matched pid 2: " + pids[0] ); + private void assertDifferentPids(String[] pids) { + if (pids[0].equals(pids[1])) { + fail("pid 1 matched pid 2: " + pids[0]); } - if ( pids[0].equals( pids[2] ) ) - { - fail( "pid 1 matched pid 3: " + pids[0] ); + if (pids[0].equals(pids[2])) { + fail("pid 1 matched pid 3: " + pids[0]); } - if ( pids[1].equals( pids[2] ) ) - { - fail( "pid 2 matched pid 3: " + pids[0] ); + if (pids[1].equals(pids[2])) { + fail("pid 2 matched pid 3: " + pids[0]); } } - private String[] doTest( SurefireLauncher forkLauncher ) - { - forkLauncher.sysProp( "testProperty", "testValue_${surefire.threadNumber}_${surefire.forkNumber}" ); - forkLauncher.addGoal( "org.apache.maven.plugins.surefire:maven-dump-pid-plugin:dump-pid" ); + private String[] doTest(SurefireLauncher forkLauncher) { + forkLauncher.sysProp("testProperty", "testValue_${surefire.threadNumber}_${surefire.forkNumber}"); + forkLauncher.addGoal("org.apache.maven.plugins.surefire:maven-dump-pid-plugin:dump-pid"); outputValidator = forkLauncher.executeTest(); - outputValidator.verifyErrorFreeLog().assertTestSuiteResults( 3, 0, 0, 0 ); + outputValidator.verifyErrorFreeLog().assertTestSuiteResults(3, 0, 0, 0); String[] pids = new String[3]; - for ( int i = 1; i <= pids.length; i++ ) - { - final TestFile targetFile = outputValidator.getTargetFile( "test" + i + "-pid" ); + for (int i = 1; i <= pids.length; i++) { + final TestFile targetFile = outputValidator.getTargetFile("test" + i + "-pid"); String pid = targetFile.slurpFile(); pids[i - 1] = pid; } return pids; } - protected String getProject() - { + protected String getProject() { return "fork-count"; } - } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/ForkCountMultiModuleIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/ForkCountMultiModuleIT.java index fd3c4f8549..a10307914d 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/ForkCountMultiModuleIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/ForkCountMultiModuleIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its; /* @@ -19,6 +37,12 @@ * under the License. */ +import java.io.File; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + import org.apache.maven.surefire.its.fixture.HelperAssertions; import org.apache.maven.surefire.its.fixture.OutputValidator; import org.apache.maven.surefire.its.fixture.SurefireJUnit4IntegrationTestCase; @@ -26,12 +50,6 @@ import org.apache.maven.surefire.its.fixture.TestFile; import org.junit.Test; -import java.io.File; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; @@ -40,127 +58,113 @@ * * @author Andreas Gudian */ -public class ForkCountMultiModuleIT extends SurefireJUnit4IntegrationTestCase -{ +public class ForkCountMultiModuleIT extends SurefireJUnit4IntegrationTestCase { @Test - public void testForkCountOneNoReuse() - { - List pids = doTest( unpack( getProject() ).forkCount( 1 ).reuseForks( false ) ); - assertAllDifferentPids( pids ); - int matchesOne = countSuffixMatches( pids, "_1_1" ); - int matchesTwo = countSuffixMatches( pids, "_2_2" ); - assertTrue( "At least one fork had forkNumber 1", matchesOne >= 1 ); - assertTrue( "At least one fork had forkNumber 2", matchesTwo >= 1 ); - assertEquals( "No other forkNumbers than 1 and 2 have been used", 6, matchesOne + matchesTwo ); + public void testForkCountOneNoReuse() { + List pids = doTest(unpack(getProject()).forkCount(1).reuseForks(false)); + assertAllDifferentPids(pids); + int matchesOne = countSuffixMatches(pids, "_1_1"); + int matchesTwo = countSuffixMatches(pids, "_2_2"); + assertTrue("At least one fork had forkNumber 1", matchesOne >= 1); + assertTrue("At least one fork had forkNumber 2", matchesTwo >= 1); + assertEquals("No other forkNumbers than 1 and 2 have been used", 6, matchesOne + matchesTwo); } - @Test - public void testForkCountOneReuse() - { - List pids = doTest( unpack( getProject() ).forkCount( 1 ).reuseForks( true ) ); - assertDifferentPids( pids, 2 ); - assertEndWith( pids, "_1_1", 3 ); - assertEndWith( pids, "_2_2", 3 ); + public void testForkCountOneReuse() { + List pids = doTest(unpack(getProject()).forkCount(1).reuseForks(true)); + assertDifferentPids(pids, 2); + assertEndWith(pids, "_1_1", 3); + assertEndWith(pids, "_2_2", 3); } @Test - public void testForkCountTwoNoReuse() - { - List pids = doTest( unpack( getProject() ).forkCount( 2 ).reuseForks( false ) ); - assertAllDifferentPids( pids ); - int matchesOne = countSuffixMatches( pids, "_1_1" ); - int matchesTwo = countSuffixMatches( pids, "_2_2" ); - int matchesThree = countSuffixMatches( pids, "_3_3" ); - int matchesFour = countSuffixMatches( pids, "_4_4" ); - assertTrue( "At least one fork had forkNumber 1", matchesOne >= 1 ); - assertTrue( "At least one fork had forkNumber 2", matchesTwo >= 1 ); - assertTrue( "At least one fork had forkNumber 3", matchesThree >= 1 ); - assertTrue( "At least one fork had forkNumber 4", matchesFour >= 1 ); - assertEquals( "No other forkNumbers than 1, 2, 3, or 4 have been used", 6, - matchesOne + matchesTwo + matchesThree + matchesFour ); + public void testForkCountTwoNoReuse() { + List pids = doTest(unpack(getProject()).forkCount(2).reuseForks(false)); + assertAllDifferentPids(pids); + int matchesOne = countSuffixMatches(pids, "_1_1"); + int matchesTwo = countSuffixMatches(pids, "_2_2"); + int matchesThree = countSuffixMatches(pids, "_3_3"); + int matchesFour = countSuffixMatches(pids, "_4_4"); + assertTrue("At least one fork had forkNumber 1", matchesOne >= 1); + assertTrue("At least one fork had forkNumber 2", matchesTwo >= 1); + assertTrue("At least one fork had forkNumber 3", matchesThree >= 1); + assertTrue("At least one fork had forkNumber 4", matchesFour >= 1); + assertEquals( + "No other forkNumbers than 1, 2, 3, or 4 have been used", + 6, + matchesOne + matchesTwo + matchesThree + matchesFour); } @Test - public void testForkCountTwoReuse() - { - List pids = doTest( unpack( getProject() ).forkCount( 2 ).reuseForks( true ) ); - assertDifferentPids( pids, 4 ); - - int matchesOne = countSuffixMatches( pids, "_1_1" ); - int matchesTwo = countSuffixMatches( pids, "_2_2" ); - int matchesThree = countSuffixMatches( pids, "_3_3" ); - int matchesFour = countSuffixMatches( pids, "_4_4" ); - assertTrue( "At least one fork had forkNumber 1", matchesOne >= 1 ); - assertTrue( "At least one fork had forkNumber 2", matchesTwo >= 1 ); - assertTrue( "At least one fork had forkNumber 3", matchesThree >= 1 ); - assertTrue( "At least one fork had forkNumber 4", matchesFour >= 1 ); - assertEquals( "No other forkNumbers than 1, 2, 3, or 4 have been used", 6, - matchesOne + matchesTwo + matchesThree + matchesFour ); + public void testForkCountTwoReuse() { + List pids = doTest(unpack(getProject()).forkCount(2).reuseForks(true)); + assertDifferentPids(pids, 4); + + int matchesOne = countSuffixMatches(pids, "_1_1"); + int matchesTwo = countSuffixMatches(pids, "_2_2"); + int matchesThree = countSuffixMatches(pids, "_3_3"); + int matchesFour = countSuffixMatches(pids, "_4_4"); + assertTrue("At least one fork had forkNumber 1", matchesOne >= 1); + assertTrue("At least one fork had forkNumber 2", matchesTwo >= 1); + assertTrue("At least one fork had forkNumber 3", matchesThree >= 1); + assertTrue("At least one fork had forkNumber 4", matchesFour >= 1); + assertEquals( + "No other forkNumbers than 1, 2, 3, or 4 have been used", + 6, + matchesOne + matchesTwo + matchesThree + matchesFour); } - private void assertEndWith( List pids, String suffix, int expectedMatches ) - { - int matches = countSuffixMatches( pids, suffix ); + private void assertEndWith(List pids, String suffix, int expectedMatches) { + int matches = countSuffixMatches(pids, suffix); - assertEquals( "suffix " + suffix + " matched the correct number of pids", expectedMatches, matches ); + assertEquals("suffix " + suffix + " matched the correct number of pids", expectedMatches, matches); } - private int countSuffixMatches( List pids, String suffix ) - { + private int countSuffixMatches(List pids, String suffix) { int matches = 0; - for ( String pid : pids ) - { - if ( pid.endsWith( suffix ) ) - { + for (String pid : pids) { + if (pid.endsWith(suffix)) { matches++; } } return matches; } - private void assertDifferentPids( List pids, int numOfDifferentPids ) - { - Set pidSet = new HashSet<>( pids ); - assertEquals( "number of different pids is not as expected", numOfDifferentPids, pidSet.size() ); + private void assertDifferentPids(List pids, int numOfDifferentPids) { + Set pidSet = new HashSet<>(pids); + assertEquals("number of different pids is not as expected", numOfDifferentPids, pidSet.size()); } - private void assertAllDifferentPids( List pids ) - { - assertDifferentPids( pids, pids.size() ); + private void assertAllDifferentPids(List pids) { + assertDifferentPids(pids, pids.size()); } - private List doTest( SurefireLauncher forkLauncher ) - { - forkLauncher.addGoal( "-T2" ); - forkLauncher.sysProp( "testProperty", "testValue_${surefire.threadNumber}_${surefire.forkNumber}" ); + private List doTest(SurefireLauncher forkLauncher) { + forkLauncher.addGoal("-T2"); + forkLauncher.sysProp("testProperty", "testValue_${surefire.threadNumber}_${surefire.forkNumber}"); final OutputValidator outputValidator = forkLauncher.setForkJvm().executeTest(); - List pids = new ArrayList<>( 6 ); - pids.addAll( validateModule( outputValidator, "module-a" ) ); - pids.addAll( validateModule( outputValidator, "module-b" ) ); + List pids = new ArrayList<>(6); + pids.addAll(validateModule(outputValidator, "module-a")); + pids.addAll(validateModule(outputValidator, "module-b")); return pids; } - private List validateModule( OutputValidator outputValidator, String module ) - { - HelperAssertions.assertTestSuiteResults( 3, 0, 0, 0, new File( outputValidator.getBaseDir(), module ) ); + private List validateModule(OutputValidator outputValidator, String module) { + HelperAssertions.assertTestSuiteResults(3, 0, 0, 0, new File(outputValidator.getBaseDir(), module)); - List pids = new ArrayList<>( 3 ); - for ( int i = 1; i <= 3; i++ ) - { - final TestFile targetFile = outputValidator.getTargetFile( module, "test" + i + "-pid" ); + List pids = new ArrayList<>(3); + for (int i = 1; i <= 3; i++) { + final TestFile targetFile = outputValidator.getTargetFile(module, "test" + i + "-pid"); String pid = targetFile.slurpFile(); - pids.add( pid ); + pids.add(pid); } return pids; } - protected String getProject() - { + protected String getProject() { return "fork-count-multimodule"; } - - } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/ForkCountTestNGIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/ForkCountTestNGIT.java index a25413cc30..c2e0e8285f 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/ForkCountTestNGIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/ForkCountTestNGIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its; /* @@ -24,12 +42,9 @@ * * @author Marvin Froeder */ -public class ForkCountTestNGIT - extends ForkCountIT -{ +public class ForkCountTestNGIT extends ForkCountIT { @Override - protected String getProject() - { + protected String getProject() { return "fork-count-testng"; } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/IncludesExcludesFromFileIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/IncludesExcludesFromFileIT.java index 89e735f930..a539011010 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/IncludesExcludesFromFileIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/IncludesExcludesFromFileIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its; /* @@ -29,67 +47,55 @@ *
    * Based on {@link IncludesExcludesIT}. */ -public class IncludesExcludesFromFileIT - extends SurefireJUnit4IntegrationTestCase -{ - private SurefireLauncher unpack() - { - return unpack( "/includes-excludes-from-file" ); +public class IncludesExcludesFromFileIT extends SurefireJUnit4IntegrationTestCase { + private SurefireLauncher unpack() { + return unpack("/includes-excludes-from-file"); } @Test - public void testSimple() - { - testWithProfile( "simple" ); + public void testSimple() { + testWithProfile("simple"); } @Test - public void testSimpleMixed() - { - testWithProfile( "simple-mixed" ); + public void testSimpleMixed() { + testWithProfile("simple-mixed"); } @Test - public void testRegex() - { - testWithProfile( "regex" ); + public void testRegex() { + testWithProfile("regex"); } @Test - public void testPath() - { - testWithProfile( "path" ); + public void testPath() { + testWithProfile("path"); } @Test - public void testMissingExcludes() - { - expectBuildFailure( "missing-excludes-file", "Failed to load list from file", "no-such-excludes-file" ); + public void testMissingExcludes() { + expectBuildFailure("missing-excludes-file", "Failed to load list from file", "no-such-excludes-file"); } @Test - public void testMissingIncludes() - { - expectBuildFailure( "missing-includes-file", "Failed to load list from file", "no-such-includes-file" ); + public void testMissingIncludes() { + expectBuildFailure("missing-includes-file", "Failed to load list from file", "no-such-includes-file"); } - private void testWithProfile( String profile ) - { - final OutputValidator outputValidator = unpack(). - activateProfile( profile ).executeTest().verifyErrorFree( 2 ); + private void testWithProfile(String profile) { + final OutputValidator outputValidator = + unpack().activateProfile(profile).executeTest().verifyErrorFree(2); - outputValidator.getTargetFile( "testTouchFile.txt" ).assertFileExists(); - outputValidator.getTargetFile( "defaultTestTouchFile.txt" ).assertFileExists(); + outputValidator.getTargetFile("testTouchFile.txt").assertFileExists(); + outputValidator.getTargetFile("defaultTestTouchFile.txt").assertFileExists(); } - private void expectBuildFailure( final String profile, final String... messages ) - { - final OutputValidator outputValidator = unpack().activateProfile( profile ) - .maven().withFailure().executeTest(); + private void expectBuildFailure(final String profile, final String... messages) { + final OutputValidator outputValidator = + unpack().activateProfile(profile).maven().withFailure().executeTest(); - for ( String message : messages ) - { - outputValidator.verifyTextInLog( message ); + for (String message : messages) { + outputValidator.verifyTextInLog(message); } } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/IncludesExcludesIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/IncludesExcludesIT.java index 46bdeb6916..e47fef15cb 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/IncludesExcludesIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/IncludesExcludesIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its; /* @@ -29,40 +47,33 @@ * * @author Benjamin Bentmann */ -public class IncludesExcludesIT - extends SurefireJUnit4IntegrationTestCase -{ - private SurefireLauncher unpack() - { - return unpack( "/includes-excludes" ); +public class IncludesExcludesIT extends SurefireJUnit4IntegrationTestCase { + private SurefireLauncher unpack() { + return unpack("/includes-excludes"); } /** * Test surefire inclusions/exclusions */ @Test - public void testIncludesExcludes() - { - testWithProfile( "simple" ); + public void testIncludesExcludes() { + testWithProfile("simple"); } @Test - public void testRegexIncludesExcludes() - { - testWithProfile( "regex" ); + public void testRegexIncludesExcludes() { + testWithProfile("regex"); } @Test - public void testPathBasedIncludesExcludes() - { - testWithProfile( "path" ); + public void testPathBasedIncludesExcludes() { + testWithProfile("path"); } - private void testWithProfile( String profile ) - { - final OutputValidator outputValidator = unpack(). - activateProfile( profile ).executeTest().verifyErrorFree( 2 ); - outputValidator.getTargetFile( "testTouchFile.txt" ).assertFileExists(); - outputValidator.getTargetFile( "defaultTestTouchFile.txt" ).assertFileExists(); + private void testWithProfile(String profile) { + final OutputValidator outputValidator = + unpack().activateProfile(profile).executeTest().verifyErrorFree(2); + outputValidator.getTargetFile("testTouchFile.txt").assertFileExists(); + outputValidator.getTargetFile("defaultTestTouchFile.txt").assertFileExists(); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/JUnit44HamcrestIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/JUnit44HamcrestIT.java index 7bf90f038b..542011af88 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/JUnit44HamcrestIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/JUnit44HamcrestIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its; /* @@ -27,12 +45,9 @@ * * @author Dan Fabulich */ -public class JUnit44HamcrestIT - extends SurefireJUnit4IntegrationTestCase -{ +public class JUnit44HamcrestIT extends SurefireJUnit4IntegrationTestCase { @Test - public void testJUnit44Hamcrest() - { - executeErrorFreeTest( "junit44-hamcrest", 1 ); + public void testJUnit44Hamcrest() { + executeErrorFreeTest("junit44-hamcrest", 1); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/JUnit47ConcurrencyIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/JUnit47ConcurrencyIT.java index b07f4566f5..a87204b37a 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/JUnit47ConcurrencyIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/JUnit47ConcurrencyIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its; /* @@ -23,41 +41,35 @@ import org.apache.maven.surefire.its.fixture.SurefireJUnit4IntegrationTestCase; import org.junit.Test; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertNotNull; import static org.hamcrest.CoreMatchers.anyOf; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.endsWith; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertThat; /** * Basic suite test using all known versions of JUnit 4.x * * @author Kristian Rosenvold */ -public class JUnit47ConcurrencyIT - extends SurefireJUnit4IntegrationTestCase -{ +public class JUnit47ConcurrencyIT extends SurefireJUnit4IntegrationTestCase { @Test - public void test47() - throws Exception - { - OutputValidator validator = unpack( "junit47-concurrency" ) - .executeTest() - .verifyErrorFree( 4 ); + public void test47() throws Exception { + OutputValidator validator = unpack("junit47-concurrency").executeTest().verifyErrorFree(4); String result = null; - for ( String line : validator.loadLogLines() ) - { - if ( line.startsWith( "[INFO] Tests run: 4, Failures: 0, Errors: 0, Skipped: 0, Time elapsed:" ) ) - { + for (String line : validator.loadLogLines()) { + if (line.startsWith("[INFO] Tests run: 4, Failures: 0, Errors: 0, Skipped: 0, Time elapsed:")) { result = line; break; } } - assertNotNull( result ); - assertThat( result, anyOf( - containsString( "Time elapsed: 1." ), - containsString( "Time elapsed: 1 s" ), - containsString( "Time elapsed: 0.9" ) ) ); - assertThat( result, endsWith( " s - in concurrentjunit47.src.test.java.junit47.BasicTest" ) ); + assertNotNull(result); + assertThat( + result, + anyOf( + containsString("Time elapsed: 1."), + containsString("Time elapsed: 1 s"), + containsString("Time elapsed: 0.9"))); + assertThat(result, endsWith(" s - in concurrentjunit47.src.test.java.junit47.BasicTest")); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/JUnit47ParallelIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/JUnit47ParallelIT.java index 94fa291664..dfce79b9f8 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/JUnit47ParallelIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/JUnit47ParallelIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its; /* @@ -19,13 +37,13 @@ * under the License. */ +import java.util.Iterator; + import org.apache.maven.surefire.its.fixture.OutputValidator; import org.apache.maven.surefire.its.fixture.SurefireJUnit4IntegrationTestCase; import org.apache.maven.surefire.its.fixture.SurefireLauncher; import org.junit.Test; -import java.util.Iterator; - import static org.assertj.core.api.Assertions.assertThat; /** @@ -34,518 +52,693 @@ * @author Tibor Digana (tibor17) * @since 2.16 */ -@SuppressWarnings( "checkstyle:magicnumber" ) -public class JUnit47ParallelIT extends SurefireJUnit4IntegrationTestCase -{ +@SuppressWarnings("checkstyle:magicnumber") +public class JUnit47ParallelIT extends SurefireJUnit4IntegrationTestCase { @Test - public void unknownThreadCountSuites() - { - unpack().parallelSuites().setTestToRun( "TestClass" ).failNever().executeTest().verifyTextInLog( - "Use threadCount or threadCountSuites > 0 or useUnlimitedThreads=true for parallel='suites'" ); + public void unknownThreadCountSuites() { + unpack().parallelSuites() + .setTestToRun("TestClass") + .failNever() + .executeTest() + .verifyTextInLog( + "Use threadCount or threadCountSuites > 0 or useUnlimitedThreads=true for parallel='suites'"); } @Test - public void unknownThreadCountClasses() - { - unpack().parallelClasses().setTestToRun( "TestClass" ).failNever().executeTest().verifyTextInLog( - "Use threadCount or threadCountClasses > 0 or useUnlimitedThreads=true for parallel='classes'" ); + public void unknownThreadCountClasses() { + unpack().parallelClasses() + .setTestToRun("TestClass") + .failNever() + .executeTest() + .verifyTextInLog( + "Use threadCount or threadCountClasses > 0 or useUnlimitedThreads=true for parallel='classes'"); } @Test - public void unknownThreadCountMethods() - { - unpack().parallelMethods().setTestToRun( "TestClass" ).failNever().executeTest().verifyTextInLog( - "Use threadCount or threadCountMethods > 0 or useUnlimitedThreads=true for parallel='methods'" ); - + public void unknownThreadCountMethods() { + unpack().parallelMethods() + .setTestToRun("TestClass") + .failNever() + .executeTest() + .verifyTextInLog( + "Use threadCount or threadCountMethods > 0 or useUnlimitedThreads=true for parallel='methods'"); } @Test - public void unknownThreadCountBoth() - { - unpack().parallelBoth().setTestToRun( "TestClass" ).failNever().executeTest().verifyTextInLog( - "Use useUnlimitedThreads=true, " + "or only threadCount > 0, " + "or (threadCountClasses > 0 and " + public void unknownThreadCountBoth() { + unpack().parallelBoth() + .setTestToRun("TestClass") + .failNever() + .executeTest() + .verifyTextInLog("Use useUnlimitedThreads=true, " + "or only threadCount > 0, " + + "or (threadCountClasses > 0 and " + "threadCountMethods > 0), " + "or (threadCount > 0 and threadCountClasses > 0 and " + "threadCountMethods > 0), " + "or (threadCount > 0 and threadCountClasses > 0 and " + "threadCount > threadCountClasses) " + "for parallel='both' or " - + "parallel='classesAndMethods'" ); + + "parallel='classesAndMethods'"); } @Test - public void unknownThreadCountAll() - { - unpack().parallelAll().setTestToRun( "TestClass" ).failNever().executeTest().verifyTextInLog( - "Use useUnlimitedThreads=true, " + "or only threadCount > 0, " + "or (threadCountSuites > 0 and " + public void unknownThreadCountAll() { + unpack().parallelAll() + .setTestToRun("TestClass") + .failNever() + .executeTest() + .verifyTextInLog("Use useUnlimitedThreads=true, " + "or only threadCount > 0, " + + "or (threadCountSuites > 0 and " + "threadCountClasses > 0 and threadCountMethods > 0), " + "or every thread-count is " + "specified, " + "or (threadCount > 0 and threadCountSuites > 0 and threadCountClasses > 0 " - + "and threadCount > threadCountSuites + threadCountClasses) " + "for parallel='all'" ); + + "and threadCount > threadCountSuites + threadCountClasses) " + "for parallel='all'"); } @Test - public void unknownThreadCountSuitesAndClasses() - { - unpack().parallelSuitesAndClasses().setTestToRun( "TestClass" ).failNever().executeTest().verifyTextInLog( - "Use useUnlimitedThreads=true, " + "or only threadCount > 0, " + "or (threadCountSuites > 0 and " + public void unknownThreadCountSuitesAndClasses() { + unpack().parallelSuitesAndClasses() + .setTestToRun("TestClass") + .failNever() + .executeTest() + .verifyTextInLog("Use useUnlimitedThreads=true, " + "or only threadCount > 0, " + + "or (threadCountSuites > 0 and " + "threadCountClasses > 0), " + "or (threadCount > 0 and threadCountSuites > 0 and " + "threadCountClasses > 0) " + "or (threadCount > 0 and threadCountSuites > 0 and threadCount" - + " > threadCountSuites) " + "for parallel='suitesAndClasses' or 'both'" ); + + " > threadCountSuites) " + "for parallel='suitesAndClasses' or 'both'"); } @Test - public void unknownThreadCountSuitesAndMethods() - { - unpack().parallelSuitesAndMethods().setTestToRun( "TestClass" ).failNever().executeTest().verifyTextInLog( - "Use useUnlimitedThreads=true, " + "or only threadCount > 0, " + "or (threadCountSuites > 0 and " + public void unknownThreadCountSuitesAndMethods() { + unpack().parallelSuitesAndMethods() + .setTestToRun("TestClass") + .failNever() + .executeTest() + .verifyTextInLog("Use useUnlimitedThreads=true, " + "or only threadCount > 0, " + + "or (threadCountSuites > 0 and " + "threadCountMethods > 0), " + "or (threadCount > 0 and threadCountSuites > 0 and " + "threadCountMethods > 0), " + "or (threadCount > 0 and threadCountSuites > 0 and " - + "threadCount > threadCountSuites) " + "for parallel='suitesAndMethods'" ); + + "threadCount > threadCountSuites) " + "for parallel='suitesAndMethods'"); } @Test - public void unknownThreadCountClassesAndMethods() - { - unpack().parallelClassesAndMethods().setTestToRun( "TestClass" ).failNever().executeTest().verifyTextInLog( - "Use useUnlimitedThreads=true, " + "or only threadCount > 0, " + "or (threadCountClasses > 0 and " + public void unknownThreadCountClassesAndMethods() { + unpack().parallelClassesAndMethods() + .setTestToRun("TestClass") + .failNever() + .executeTest() + .verifyTextInLog("Use useUnlimitedThreads=true, " + "or only threadCount > 0, " + + "or (threadCountClasses > 0 and " + "threadCountMethods > 0), " + "or (threadCount > 0 and threadCountClasses > 0 and " + "threadCountMethods > 0), " + "or (threadCount > 0 and threadCountClasses > 0 and " + "threadCount > threadCountClasses) " + "for parallel='both' or " - + "parallel='classesAndMethods'" ); + + "parallel='classesAndMethods'"); } @Test - public void serial() - { + public void serial() { // takes 7.2 sec - unpack().setTestToRun( "Suite*Test" ).executeTest().verifyErrorFree( 24 ); + unpack().setTestToRun("Suite*Test").executeTest().verifyErrorFree(24); } @Test - public void unlimitedThreadsSuites1() - { + public void unlimitedThreadsSuites1() { // takes 3.6 sec - unpack().parallelSuites().useUnlimitedThreads().setTestToRun( "Suite*Test" ).executeTest().verifyErrorFree( - 24 ); + unpack().parallelSuites() + .useUnlimitedThreads() + .setTestToRun("Suite*Test") + .executeTest() + .verifyErrorFree(24); } @Test - public void unlimitedThreadsSuites2() - { + public void unlimitedThreadsSuites2() { // takes 3.6 sec - unpack().parallelSuites().useUnlimitedThreads().threadCountSuites( 5 ).setTestToRun( - "Suite*Test" ).executeTest().verifyErrorFree( 24 ); + unpack().parallelSuites() + .useUnlimitedThreads() + .threadCountSuites(5) + .setTestToRun("Suite*Test") + .executeTest() + .verifyErrorFree(24); } @Test - public void unlimitedThreadsClasses1() - { + public void unlimitedThreadsClasses1() { // takes 1.8 sec - unpack().parallelClasses().useUnlimitedThreads().setTestToRun( "Suite*Test" ).executeTest().verifyErrorFree( - 24 ); + unpack().parallelClasses() + .useUnlimitedThreads() + .setTestToRun("Suite*Test") + .executeTest() + .verifyErrorFree(24); } @Test - public void unlimitedThreadsClasses2() - { + public void unlimitedThreadsClasses2() { // takes 1.8 sec - unpack().parallelClasses().useUnlimitedThreads().threadCountClasses( 5 ).setTestToRun( - "Suite*Test" ).executeTest().verifyErrorFree( 24 ); + unpack().parallelClasses() + .useUnlimitedThreads() + .threadCountClasses(5) + .setTestToRun("Suite*Test") + .executeTest() + .verifyErrorFree(24); } @Test - public void unlimitedThreadsMethods1() - { + public void unlimitedThreadsMethods1() { // takes 2.4 sec - unpack().parallelMethods().useUnlimitedThreads().setTestToRun( "Suite*Test" ).executeTest().verifyErrorFree( - 24 ); + unpack().parallelMethods() + .useUnlimitedThreads() + .setTestToRun("Suite*Test") + .executeTest() + .verifyErrorFree(24); } @Test - public void unlimitedThreadsMethods2() - { + public void unlimitedThreadsMethods2() { // takes 2.4 sec - unpack().parallelMethods().useUnlimitedThreads().threadCountMethods( 5 ).setTestToRun( - "Suite*Test" ).executeTest().verifyErrorFree( 24 ); + unpack().parallelMethods() + .useUnlimitedThreads() + .threadCountMethods(5) + .setTestToRun("Suite*Test") + .executeTest() + .verifyErrorFree(24); } @Test - public void unlimitedThreadsSuitesAndClasses1() - { + public void unlimitedThreadsSuitesAndClasses1() { // takes 0.9 sec - unpack().parallelSuitesAndClasses().useUnlimitedThreads().setTestToRun( - "Suite*Test" ).executeTest().verifyErrorFree( 24 ); + unpack().parallelSuitesAndClasses() + .useUnlimitedThreads() + .setTestToRun("Suite*Test") + .executeTest() + .verifyErrorFree(24); } @Test - public void unlimitedThreadsSuitesAndClasses2() - { + public void unlimitedThreadsSuitesAndClasses2() { // takes 0.9 sec // 1.8 sec with 4 parallel classes - unpack().parallelSuitesAndClasses().useUnlimitedThreads().threadCountSuites( 5 ).threadCountClasses( - 15 ).setTestToRun( "Suite*Test" ).executeTest().verifyErrorFree( 24 ); + unpack().parallelSuitesAndClasses() + .useUnlimitedThreads() + .threadCountSuites(5) + .threadCountClasses(15) + .setTestToRun("Suite*Test") + .executeTest() + .verifyErrorFree(24); } @Test - public void unlimitedThreadsSuitesAndMethods1() - { + public void unlimitedThreadsSuitesAndMethods1() { // takes 1.2 sec - unpack().parallelSuitesAndMethods().useUnlimitedThreads().setTestToRun( - "Suite*Test" ).executeTest().verifyErrorFree( 24 ); + unpack().parallelSuitesAndMethods() + .useUnlimitedThreads() + .setTestToRun("Suite*Test") + .executeTest() + .verifyErrorFree(24); } @Test - public void unlimitedThreadsSuitesAndMethods2() - { + public void unlimitedThreadsSuitesAndMethods2() { // takes 1.2 sec - unpack().parallelSuitesAndMethods().useUnlimitedThreads().threadCountSuites( 5 ).threadCountMethods( - 15 ).setTestToRun( "Suite*Test" ).executeTest().verifyErrorFree( 24 ); + unpack().parallelSuitesAndMethods() + .useUnlimitedThreads() + .threadCountSuites(5) + .threadCountMethods(15) + .setTestToRun("Suite*Test") + .executeTest() + .verifyErrorFree(24); } @Test - public void unlimitedThreadsClassesAndMethods1() - { + public void unlimitedThreadsClassesAndMethods1() { // takes 0.6 sec - unpack().parallelClassesAndMethods().useUnlimitedThreads().setTestToRun( - "Suite*Test" ).executeTest().verifyErrorFree( 24 ); + unpack().parallelClassesAndMethods() + .useUnlimitedThreads() + .setTestToRun("Suite*Test") + .executeTest() + .verifyErrorFree(24); } @Test - public void unlimitedThreadsClassesAndMethods2() - { + public void unlimitedThreadsClassesAndMethods2() { // takes 0.6 sec - unpack().parallelClassesAndMethods().useUnlimitedThreads().threadCountClasses( 5 ).threadCountMethods( - 15 ).setTestToRun( "Suite*Test" ).executeTest().verifyErrorFree( 24 ); + unpack().parallelClassesAndMethods() + .useUnlimitedThreads() + .threadCountClasses(5) + .threadCountMethods(15) + .setTestToRun("Suite*Test") + .executeTest() + .verifyErrorFree(24); } @Test - public void unlimitedThreadsAll1() - { + public void unlimitedThreadsAll1() { // takes 0.3 sec - unpack().parallelAll().useUnlimitedThreads().setTestToRun( "Suite*Test" ).executeTest().verifyErrorFree( 24 ); + unpack().parallelAll() + .useUnlimitedThreads() + .setTestToRun("Suite*Test") + .executeTest() + .verifyErrorFree(24); } @Test - public void unlimitedThreadsAll2() - { + public void unlimitedThreadsAll2() { // takes 0.3 sec - unpack().parallelAll().useUnlimitedThreads().threadCountSuites( 5 ).threadCountClasses( 15 ).threadCountMethods( - 30 ).setTestToRun( "Suite*Test" ).executeTest().verifyErrorFree( 24 ); + unpack().parallelAll() + .useUnlimitedThreads() + .threadCountSuites(5) + .threadCountClasses(15) + .threadCountMethods(30) + .setTestToRun("Suite*Test") + .executeTest() + .verifyErrorFree(24); } @Test - public void threadCountSuites() - { + public void threadCountSuites() { // takes 3.6 sec - unpack().parallelSuites().threadCount( 3 ).setTestToRun( "Suite*Test" ).executeTest().verifyErrorFree( 24 ); + unpack().parallelSuites() + .threadCount(3) + .setTestToRun("Suite*Test") + .executeTest() + .verifyErrorFree(24); } @Test - public void threadCountClasses() - { + public void threadCountClasses() { // takes 3.6 sec for single core // takes 1.8 sec for double core - unpack().parallelClasses().threadCount( 3 ).setTestToRun( "Suite*Test" ).executeTest().verifyErrorFree( 24 ); + unpack().parallelClasses() + .threadCount(3) + .setTestToRun("Suite*Test") + .executeTest() + .verifyErrorFree(24); } @Test - public void threadCountMethods() - { + public void threadCountMethods() { // takes 2.4 sec - unpack().parallelMethods().threadCount( 3 ).setTestToRun( "Suite*Test" ).executeTest().verifyErrorFree( 24 ); + unpack().parallelMethods() + .threadCount(3) + .setTestToRun("Suite*Test") + .executeTest() + .verifyErrorFree(24); } @Test - public void threadCountClassesAndMethodsOneCore() - { + public void threadCountClassesAndMethodsOneCore() { // takes 4.8 sec - unpack().disablePerCoreThreadCount().disableParallelOptimization().parallelClassesAndMethods().threadCount( - 3 ).setTestToRun( "Suite*Test" ).executeTest().verifyErrorFree( 24 ); + unpack().disablePerCoreThreadCount() + .disableParallelOptimization() + .parallelClassesAndMethods() + .threadCount(3) + .setTestToRun("Suite*Test") + .executeTest() + .verifyErrorFree(24); } @Test - public void threadCountClassesAndMethodsOneCoreOptimized() - { + public void threadCountClassesAndMethodsOneCoreOptimized() { // the number of reused threads in leafs depends on the number of runners and CPU - unpack().disablePerCoreThreadCount().parallelClassesAndMethods().threadCount( 3 ).setTestToRun( - "Suite*Test" ).executeTest().verifyErrorFree( 24 ); + unpack().disablePerCoreThreadCount() + .parallelClassesAndMethods() + .threadCount(3) + .setTestToRun("Suite*Test") + .executeTest() + .verifyErrorFree(24); } @Test - public void threadCountClassesAndMethods() - { + public void threadCountClassesAndMethods() { // takes 2.4 sec for double core CPU - unpack().disableParallelOptimization().parallelClassesAndMethods().threadCount( 3 ).setTestToRun( - "Suite*Test" ).executeTest().verifyErrorFree( 24 ); + unpack().disableParallelOptimization() + .parallelClassesAndMethods() + .threadCount(3) + .setTestToRun("Suite*Test") + .executeTest() + .verifyErrorFree(24); } @Test - public void threadCountClassesAndMethodsOptimized() - { + public void threadCountClassesAndMethodsOptimized() { // the number of reused threads in leafs depends on the number of runners and CPU - unpack().parallelClassesAndMethods().threadCount( 3 ).setTestToRun( - "Suite*Test" ).executeTest().verifyErrorFree( 24 ); + unpack().parallelClassesAndMethods() + .threadCount(3) + .setTestToRun("Suite*Test") + .executeTest() + .verifyErrorFree(24); } @Test - public void threadCountSuitesAndMethods() - { + public void threadCountSuitesAndMethods() { // usually 24 times 0.3 sec = 7.2 sec with one core CPU // takes 1.8 sec for double core CPU - unpack().disableParallelOptimization().parallelSuitesAndMethods().threadCount( 3 ).setTestToRun( - "Suite*Test" ).executeTest().verifyErrorFree( 24 ); + unpack().disableParallelOptimization() + .parallelSuitesAndMethods() + .threadCount(3) + .setTestToRun("Suite*Test") + .executeTest() + .verifyErrorFree(24); } @Test - public void threadCountSuitesAndMethodsOptimized() - { + public void threadCountSuitesAndMethodsOptimized() { // the number of reused threads in leafs depends on the number of runners and CPU - unpack().parallelSuitesAndMethods().threadCount( 3 ).setTestToRun( "Suite*Test" ).executeTest().verifyErrorFree( - 24 ); + unpack().parallelSuitesAndMethods() + .threadCount(3) + .setTestToRun("Suite*Test") + .executeTest() + .verifyErrorFree(24); } @Test - public void threadCountSuitesAndClasses() - { - unpack().disableParallelOptimization().parallelSuitesAndClasses().threadCount( 3 ).setTestToRun( - "Suite*Test" ).executeTest().verifyErrorFree( 24 ); + public void threadCountSuitesAndClasses() { + unpack().disableParallelOptimization() + .parallelSuitesAndClasses() + .threadCount(3) + .setTestToRun("Suite*Test") + .executeTest() + .verifyErrorFree(24); } @Test - public void threadCountSuitesAndClassesOptimized() - { + public void threadCountSuitesAndClassesOptimized() { // the number of reused threads in leafs depends on the number of runners and CPU - unpack().parallelSuitesAndClasses().threadCount( 3 ).setTestToRun( "Suite*Test" ).executeTest().verifyErrorFree( - 24 ); + unpack().parallelSuitesAndClasses() + .threadCount(3) + .setTestToRun("Suite*Test") + .executeTest() + .verifyErrorFree(24); } @Test - public void threadCountAll() - { - unpack().disableParallelOptimization().parallelAll().threadCount( 3 ).setTestToRun( - "Suite*Test" ).executeTest().verifyErrorFree( 24 ); + public void threadCountAll() { + unpack().disableParallelOptimization() + .parallelAll() + .threadCount(3) + .setTestToRun("Suite*Test") + .executeTest() + .verifyErrorFree(24); } @Test - public void threadCountAllOptimized() - { + public void threadCountAllOptimized() { // the number of reused threads in leafs depends on the number of runners and CPU - unpack().parallelAll().threadCount( 3 ).setTestToRun( "Suite*Test" ).executeTest().verifyErrorFree( 24 ); + unpack().parallelAll() + .threadCount(3) + .setTestToRun("Suite*Test") + .executeTest() + .verifyErrorFree(24); } @Test - public void everyThreadCountSuitesAndClasses() - { + public void everyThreadCountSuitesAndClasses() { // takes 1.8 sec for double core CPU - unpack().parallelSuitesAndClasses().threadCount( 3 ).threadCountSuites( 34 ).threadCountClasses( - 66 ).setTestToRun( "Suite*Test" ).executeTest().verifyErrorFree( 24 ); + unpack().parallelSuitesAndClasses() + .threadCount(3) + .threadCountSuites(34) + .threadCountClasses(66) + .setTestToRun("Suite*Test") + .executeTest() + .verifyErrorFree(24); } @Test - public void everyThreadCountSuitesAndMethods() - { + public void everyThreadCountSuitesAndMethods() { // takes 1.8 sec for double core CPU - unpack().parallelSuitesAndMethods().threadCount( 3 ).threadCountSuites( 34 ).threadCountMethods( - 66 ).setTestToRun( "Suite*Test" ).executeTest().verifyErrorFree( 24 ); + unpack().parallelSuitesAndMethods() + .threadCount(3) + .threadCountSuites(34) + .threadCountMethods(66) + .setTestToRun("Suite*Test") + .executeTest() + .verifyErrorFree(24); } @Test - public void everyThreadCountClassesAndMethods() - { + public void everyThreadCountClassesAndMethods() { // takes 1.8 sec for double core CPU - unpack().parallelClassesAndMethods().threadCount( 3 ).threadCountClasses( 34 ).threadCountMethods( - 66 ).setTestToRun( "Suite*Test" ).executeTest().verifyErrorFree( 24 ); + unpack().parallelClassesAndMethods() + .threadCount(3) + .threadCountClasses(34) + .threadCountMethods(66) + .setTestToRun("Suite*Test") + .executeTest() + .verifyErrorFree(24); } @Test - public void everyThreadCountAll() - { + public void everyThreadCountAll() { // takes 2.4 sec for double core CPU - unpack().parallelAll().threadCount( 3 ).threadCountSuites( 17 ).threadCountClasses( 34 ).threadCountMethods( - 49 ).setTestToRun( "Suite*Test" ).executeTest().verifyErrorFree( 24 ); + unpack().parallelAll() + .threadCount(3) + .threadCountSuites(17) + .threadCountClasses(34) + .threadCountMethods(49) + .setTestToRun("Suite*Test") + .executeTest() + .verifyErrorFree(24); } @Test - public void reusableThreadCountSuitesAndClasses() - { + public void reusableThreadCountSuitesAndClasses() { // 4 * cpu to 5 * cpu threads to run test classes // takes cca 1.8 sec - unpack().disableParallelOptimization().parallelSuitesAndClasses().disablePerCoreThreadCount().threadCount( - 6 ).threadCountSuites( 2 ).setTestToRun( "Suite*Test" ).executeTest().verifyErrorFree( 24 ); + unpack().disableParallelOptimization() + .parallelSuitesAndClasses() + .disablePerCoreThreadCount() + .threadCount(6) + .threadCountSuites(2) + .setTestToRun("Suite*Test") + .executeTest() + .verifyErrorFree(24); } @Test - public void reusableThreadCountSuitesAndClassesOptimized() - { + public void reusableThreadCountSuitesAndClassesOptimized() { // the number of reused threads in leafs depends on the number of runners and CPU - unpack().parallelSuitesAndClasses().disablePerCoreThreadCount().threadCount( 6 ).threadCountSuites( - 2 ).setTestToRun( "Suite*Test" ).executeTest().verifyErrorFree( 24 ); + unpack().parallelSuitesAndClasses() + .disablePerCoreThreadCount() + .threadCount(6) + .threadCountSuites(2) + .setTestToRun("Suite*Test") + .executeTest() + .verifyErrorFree(24); } @Test - public void reusableThreadCountSuitesAndMethods() - { + public void reusableThreadCountSuitesAndMethods() { // 4 * cpu to 5 * cpu threads to run test methods // takes cca 1.8 sec - unpack().disableParallelOptimization().parallelSuitesAndMethods().disablePerCoreThreadCount().threadCount( - 6 ).threadCountSuites( 2 ).setTestToRun( "Suite*Test" ).executeTest().verifyErrorFree( 24 ); + unpack().disableParallelOptimization() + .parallelSuitesAndMethods() + .disablePerCoreThreadCount() + .threadCount(6) + .threadCountSuites(2) + .setTestToRun("Suite*Test") + .executeTest() + .verifyErrorFree(24); } @Test - public void reusableThreadCountSuitesAndMethodsOptimized() - { + public void reusableThreadCountSuitesAndMethodsOptimized() { // the number of reused threads in leafs depends on the number of runners and CPU - unpack().parallelSuitesAndMethods().disablePerCoreThreadCount().threadCount( 6 ).threadCountSuites( - 2 ).setTestToRun( "Suite*Test" ).executeTest().verifyErrorFree( 24 ); + unpack().parallelSuitesAndMethods() + .disablePerCoreThreadCount() + .threadCount(6) + .threadCountSuites(2) + .setTestToRun("Suite*Test") + .executeTest() + .verifyErrorFree(24); } @Test - public void reusableThreadCountClassesAndMethods() - { + public void reusableThreadCountClassesAndMethods() { // 4 * cpu to 5 * cpu threads to run test methods // takes cca 1.8 sec - unpack().disableParallelOptimization().parallelClassesAndMethods().disablePerCoreThreadCount().threadCount( - 6 ).threadCountClasses( 2 ).setTestToRun( "Suite*Test" ).executeTest().verifyErrorFree( 24 ); + unpack().disableParallelOptimization() + .parallelClassesAndMethods() + .disablePerCoreThreadCount() + .threadCount(6) + .threadCountClasses(2) + .setTestToRun("Suite*Test") + .executeTest() + .verifyErrorFree(24); } @Test - public void reusableThreadCountClassesAndMethodsOptimized() - { + public void reusableThreadCountClassesAndMethodsOptimized() { // the number of reused threads in leafs depends on the number of runners and CPU - unpack().parallelClassesAndMethods().disablePerCoreThreadCount().threadCount( 6 ).threadCountClasses( - 2 ).setTestToRun( "Suite*Test" ).executeTest().verifyErrorFree( 24 ); + unpack().parallelClassesAndMethods() + .disablePerCoreThreadCount() + .threadCount(6) + .threadCountClasses(2) + .setTestToRun("Suite*Test") + .executeTest() + .verifyErrorFree(24); } @Test - public void reusableThreadCountAll() - { + public void reusableThreadCountAll() { // 8 * cpu to 13 * cpu threads to run test methods // takes 0.9 sec - unpack().disableParallelOptimization().parallelAll().disablePerCoreThreadCount().threadCount( - 14 ).threadCountSuites( 2 ).threadCountClasses( 4 ).setTestToRun( - "Suite*Test" ).executeTest().verifyErrorFree( 24 ); + unpack().disableParallelOptimization() + .parallelAll() + .disablePerCoreThreadCount() + .threadCount(14) + .threadCountSuites(2) + .threadCountClasses(4) + .setTestToRun("Suite*Test") + .executeTest() + .verifyErrorFree(24); } @Test - public void reusableThreadCountAllOptimized() - { + public void reusableThreadCountAllOptimized() { // the number of reused threads in leafs depends on the number of runners and CPU - unpack().parallelAll().disablePerCoreThreadCount().threadCount( 14 ).threadCountSuites( 2 ).threadCountClasses( - 4 ).setTestToRun( "Suite*Test" ).executeTest().verifyErrorFree( 24 ); + unpack().parallelAll() + .disablePerCoreThreadCount() + .threadCount(14) + .threadCountSuites(2) + .threadCountClasses(4) + .setTestToRun("Suite*Test") + .executeTest() + .verifyErrorFree(24); } @Test - public void suites() - { + public void suites() { // takes 3.6 sec - unpack().parallelSuites().threadCountSuites( 5 ).setTestToRun( "Suite*Test" ).executeTest().verifyErrorFree( - 24 ); + unpack().parallelSuites() + .threadCountSuites(5) + .setTestToRun("Suite*Test") + .executeTest() + .verifyErrorFree(24); } @Test - public void classes() - { + public void classes() { // takes 1.8 sec on any CPU because the suites are running in a sequence - unpack().parallelClasses().threadCountClasses( 5 ).setTestToRun( "Suite*Test" ).executeTest().verifyErrorFree( - 24 ); + unpack().parallelClasses() + .threadCountClasses(5) + .setTestToRun("Suite*Test") + .executeTest() + .verifyErrorFree(24); } @Test - public void methods() - { + public void methods() { // takes 2.4 sec on any CPU because every class has only three methods // and the suites and classes are running in a sequence - unpack().parallelMethods().threadCountMethods( 5 ).setTestToRun( "Suite*Test" ).executeTest().verifyErrorFree( - 24 ); + unpack().parallelMethods() + .threadCountMethods(5) + .setTestToRun("Suite*Test") + .executeTest() + .verifyErrorFree(24); } @Test - public void suitesAndClasses() - { + public void suitesAndClasses() { // takes 0.9 sec - unpack().parallelSuitesAndClasses().threadCountSuites( 5 ).threadCountClasses( 15 ).setTestToRun( - "Suite*Test" ).executeTest().verifyErrorFree( 24 ); + unpack().parallelSuitesAndClasses() + .threadCountSuites(5) + .threadCountClasses(15) + .setTestToRun("Suite*Test") + .executeTest() + .verifyErrorFree(24); } @Test - public void suitesAndMethods() - { + public void suitesAndMethods() { // takes 1.2 sec on any CPU - unpack().parallelSuitesAndMethods().threadCountSuites( 5 ).threadCountMethods( 15 ).setTestToRun( - "Suite*Test" ).executeTest().verifyErrorFree( 24 ); + unpack().parallelSuitesAndMethods() + .threadCountSuites(5) + .threadCountMethods(15) + .setTestToRun("Suite*Test") + .executeTest() + .verifyErrorFree(24); } @Test - public void classesAndMethods() - { + public void classesAndMethods() { // takes 0.6 sec on any CPU - unpack().parallelClassesAndMethods().threadCountClasses( 5 ).threadCountMethods( 15 ).setTestToRun( - "Suite*Test" ).executeTest().verifyErrorFree( 24 ); + unpack().parallelClassesAndMethods() + .threadCountClasses(5) + .threadCountMethods(15) + .setTestToRun("Suite*Test") + .executeTest() + .verifyErrorFree(24); } @Test - public void all() - { + public void all() { // takes 0.3 sec on any CPU - unpack().parallelAll().threadCountSuites( 5 ).threadCountClasses( 15 ).threadCountMethods( 30 ).setTestToRun( - "Suite*Test" ).executeTest().verifyErrorFree( 24 ); + unpack().parallelAll() + .threadCountSuites(5) + .threadCountClasses(15) + .threadCountMethods(30) + .setTestToRun("Suite*Test") + .executeTest() + .verifyErrorFree(24); } @Test - public void shutdown() - { + public void shutdown() { // executes for 2.5 sec until timeout has elapsed - unpack().parallelMethods().threadCountMethods( 2 ).parallelTestsTimeoutInSeconds( 2.5d ).setTestToRun( - "TestClass" ).failNever().executeTest().verifyTextInLog( - "The test run has finished abruptly after timeout of 2.5 seconds." ); + unpack().parallelMethods() + .threadCountMethods(2) + .parallelTestsTimeoutInSeconds(2.5d) + .setTestToRun("TestClass") + .failNever() + .executeTest() + .verifyTextInLog("The test run has finished abruptly after timeout of 2.5 seconds."); } @Test - public void forcedShutdown() - { + public void forcedShutdown() { // executes for 2.5 sec until timeout has elapsed - unpack().parallelMethods().threadCountMethods( 2 ).parallelTestsTimeoutForcedInSeconds( 2.5d ).setTestToRun( - "TestClass" ).failNever().executeTest().verifyTextInLog( - "The test run has finished abruptly after timeout of 2.5 seconds." ); + unpack().parallelMethods() + .threadCountMethods(2) + .parallelTestsTimeoutForcedInSeconds(2.5d) + .setTestToRun("TestClass") + .failNever() + .executeTest() + .verifyTextInLog("The test run has finished abruptly after timeout of 2.5 seconds."); } @Test - public void timeoutAndForcedShutdown() - { + public void timeoutAndForcedShutdown() { // executes for one sec until timeout has elapsed - unpack().parallelMethods().threadCountMethods( 2 ).parallelTestsTimeoutInSeconds( - 1 ).parallelTestsTimeoutForcedInSeconds( 2.5d ).setTestToRun( - "TestClass" ).failNever().executeTest().verifyTextInLog( - "The test run has finished abruptly after timeout of 1.0 seconds." ); + unpack().parallelMethods() + .threadCountMethods(2) + .parallelTestsTimeoutInSeconds(1) + .parallelTestsTimeoutForcedInSeconds(2.5d) + .setTestToRun("TestClass") + .failNever() + .executeTest() + .verifyTextInLog("The test run has finished abruptly after timeout of 1.0 seconds."); } @Test - public void forcedShutdownVerifyingLogs() - throws Exception - { + public void forcedShutdownVerifyingLogs() throws Exception { // attempts to run for 2.4 sec until timeout has elapsed - OutputValidator validator = unpack() - .parallelMethods() - .threadCountMethods( 3 ) - .disablePerCoreThreadCount() - .parallelTestsTimeoutForcedInSeconds( 1.05d ) - .setTestToRun( "Waiting*Test" ) - .failNever() - .executeTest() - .verifyTextInLog( "The test run has finished abruptly after timeout of 1.05 seconds." ) - .verifyTextInLog( "These tests were executed in prior to the shutdown operation:" ); - - for ( Iterator it = validator.loadLogLines().iterator(); it.hasNext(); ) - { + OutputValidator validator = unpack().parallelMethods() + .threadCountMethods(3) + .disablePerCoreThreadCount() + .parallelTestsTimeoutForcedInSeconds(1.05d) + .setTestToRun("Waiting*Test") + .failNever() + .executeTest() + .verifyTextInLog("The test run has finished abruptly after timeout of 1.05 seconds.") + .verifyTextInLog("These tests were executed in prior to the shutdown operation:"); + + for (Iterator it = validator.loadLogLines().iterator(); it.hasNext(); ) { String line = it.next(); - if ( line.contains( "These tests are incomplete:" ) ) - { - assertThat( it.hasNext() ).isTrue(); - assertThat( it.next() ).matches( "^.*surefireparallel\\.Waiting(\\d{1,1})Test$" ); + if (line.contains("These tests are incomplete:")) { + assertThat(it.hasNext()).isTrue(); + assertThat(it.next()).matches("^.*surefireparallel\\.Waiting(\\d{1,1})Test$"); } } } - private SurefireLauncher unpack() - { - return unpack( "junit47-parallel" ).showErrorStackTraces().forkOnce().redirectToFile( false ); + private SurefireLauncher unpack() { + return unpack("junit47-parallel").showErrorStackTraces().forkOnce().redirectToFile(false); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/JUnit47ParallelNotThreadSafeIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/JUnit47ParallelNotThreadSafeIT.java index bf393caa72..e561fb50d1 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/JUnit47ParallelNotThreadSafeIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/JUnit47ParallelNotThreadSafeIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its; /* @@ -29,24 +47,19 @@ * @author Tibor Digana (tibor17) * @since 2.19 */ -public class JUnit47ParallelNotThreadSafeIT - extends SurefireJUnit4IntegrationTestCase -{ +public class JUnit47ParallelNotThreadSafeIT extends SurefireJUnit4IntegrationTestCase { - private SurefireLauncher unpack() - { - return unpack( "junit47-parallel-nts" ); + private SurefireLauncher unpack() { + return unpack("junit47-parallel-nts"); } @Test - public void test() - { - unpack() - .parallelAll() - .useUnlimitedThreads() - .executeTest() - .verifyErrorFree( 2 ) - .verifyTextInLog( "xxx-maven-surefire-plugin@NotThreadSafe" ) - .verifyTextInLog( "expected-thread" ); + public void test() { + unpack().parallelAll() + .useUnlimitedThreads() + .executeTest() + .verifyErrorFree(2) + .verifyTextInLog("xxx-maven-surefire-plugin@NotThreadSafe") + .verifyTextInLog("expected-thread"); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/JUnit47RedirectOutputIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/JUnit47RedirectOutputIT.java index 758fae0842..c88c4d6fee 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/JUnit47RedirectOutputIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/JUnit47RedirectOutputIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its; /* @@ -31,39 +49,36 @@ /** * */ -public class JUnit47RedirectOutputIT - extends SurefireJUnit4IntegrationTestCase -{ +public class JUnit47RedirectOutputIT extends SurefireJUnit4IntegrationTestCase { @Test - public void testPrintSummaryTrueWithRedirect() - { - final OutputValidator clean = unpack().redirectToFile( true ).addGoal( "clean" ).executeTest(); - checkReports( clean ); + public void testPrintSummaryTrueWithRedirect() { + final OutputValidator clean = + unpack().redirectToFile(true).addGoal("clean").executeTest(); + checkReports(clean); } @Test - public void testClassesParallel() - { + public void testClassesParallel() { final OutputValidator clean = - unpack().redirectToFile( true ).parallelClasses().addGoal( "clean" ).executeTest(); - checkReports( clean ); + unpack().redirectToFile(true).parallelClasses().addGoal("clean").executeTest(); + checkReports(clean); } - private void checkReports( OutputValidator validator ) - { - String report = StringUtils.trimToNull( - validator.getSurefireReportsFile( "junit47ConsoleOutput.Test1-output.txt" ).readFileToString() ); - assertNotNull( report ); - String report2 = StringUtils.trimToNull( - validator.getSurefireReportsFile( "junit47ConsoleOutput.Test2-output.txt" ).readFileToString() ); - assertNotNull( report2 ); - assertFalse( validator.getSurefireReportsFile( "junit47ConsoleOutput.Test3-output.txt" ).exists() ); + private void checkReports(OutputValidator validator) { + String report = StringUtils.trimToNull(validator + .getSurefireReportsFile("junit47ConsoleOutput.Test1-output.txt") + .readFileToString()); + assertNotNull(report); + String report2 = StringUtils.trimToNull(validator + .getSurefireReportsFile("junit47ConsoleOutput.Test2-output.txt") + .readFileToString()); + assertNotNull(report2); + assertFalse(validator + .getSurefireReportsFile("junit47ConsoleOutput.Test3-output.txt") + .exists()); } - - private SurefireLauncher unpack() - { - return unpack( "/junit47-redirect-output" ); + private SurefireLauncher unpack() { + return unpack("/junit47-redirect-output"); } - } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/JUnit47RerunFailingTestWithCucumberIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/JUnit47RerunFailingTestWithCucumberIT.java index 13c48d6b91..063510c96f 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/JUnit47RerunFailingTestWithCucumberIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/JUnit47RerunFailingTestWithCucumberIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its; /* @@ -40,89 +58,69 @@ * * @author mpkorstanje */ -@RunWith( Parameterized.class ) -@SuppressWarnings( "checkstyle:magicnumber" ) -public class JUnit47RerunFailingTestWithCucumberIT extends SurefireJUnit4IntegrationTestCase -{ - private static final String LEGACY_FORK_NODE = - "org.apache.maven.plugin.surefire.extensions.LegacyForkNodeFactory"; +@RunWith(Parameterized.class) +@SuppressWarnings("checkstyle:magicnumber") +public class JUnit47RerunFailingTestWithCucumberIT extends SurefireJUnit4IntegrationTestCase { + private static final String LEGACY_FORK_NODE = "org.apache.maven.plugin.surefire.extensions.LegacyForkNodeFactory"; private static final String SUREFIRE_FORK_NODE = - "org.apache.maven.plugin.surefire.extensions.SurefireForkNodeFactory"; + "org.apache.maven.plugin.surefire.extensions.SurefireForkNodeFactory"; @Parameters - public static Iterable data() - { + public static Iterable data() { ArrayList args = new ArrayList<>(); - args.add( new Object[] { "tcp" } ); - args.add( new Object[] { null } ); + args.add(new Object[] {"tcp"}); + args.add(new Object[] {null}); return args; } @Parameter - @SuppressWarnings( "checkstyle:visibilitymodifier" ) + @SuppressWarnings("checkstyle:visibilitymodifier") public String profileId; - private SurefireLauncher unpack() - { + private SurefireLauncher unpack() { SurefireLauncher launcher = - unpack( "junit47-rerun-failing-tests-with-cucumber", profileId == null ? "" : "-" + profileId ); + unpack("junit47-rerun-failing-tests-with-cucumber", profileId == null ? "" : "-" + profileId); - if ( profileId != null ) - { - launcher.activateProfile( profileId ); + if (profileId != null) { + launcher.activateProfile(profileId); } return launcher; } @Test - public void testRerunFailingErrorTestsFalse() - throws VerificationException - { + public void testRerunFailingErrorTestsFalse() throws VerificationException { String cls = profileId == null ? LEGACY_FORK_NODE : SUREFIRE_FORK_NODE; - unpack() - .debugLogging() - .maven() - .sysProp( "surefire.rerunFailingTestsCount", 0 ) - .withFailure() - .executeTest() - .assertTestSuiteResults( 1, 0, 1, 0, 0 ) - .assertThatLogLine( - containsString( "Found implementation of fork node factory: " + cls ), - equalTo( 1 ) ); + unpack().debugLogging() + .maven() + .sysProp("surefire.rerunFailingTestsCount", 0) + .withFailure() + .executeTest() + .assertTestSuiteResults(1, 0, 1, 0, 0) + .assertThatLogLine(containsString("Found implementation of fork node factory: " + cls), equalTo(1)); } @Test - public void testRerunFailingErrorTestsWithOneRetry() - throws VerificationException - { + public void testRerunFailingErrorTestsWithOneRetry() throws VerificationException { String cls = profileId == null ? LEGACY_FORK_NODE : SUREFIRE_FORK_NODE; - unpack() - .debugLogging() - .maven() - .sysProp( "surefire.rerunFailingTestsCount", 1 ) - .withFailure() - .executeTest() - .assertTestSuiteResults( 1, 0, 1, 0, 0 ) - .assertThatLogLine( - containsString( "Found implementation of fork node factory: " + cls ), - equalTo( 1 ) ); + unpack().debugLogging() + .maven() + .sysProp("surefire.rerunFailingTestsCount", 1) + .withFailure() + .executeTest() + .assertTestSuiteResults(1, 0, 1, 0, 0) + .assertThatLogLine(containsString("Found implementation of fork node factory: " + cls), equalTo(1)); } @Test - public void testRerunFailingErrorTestsTwoRetry() - throws VerificationException - { + public void testRerunFailingErrorTestsTwoRetry() throws VerificationException { String cls = profileId == null ? LEGACY_FORK_NODE : SUREFIRE_FORK_NODE; - unpack() - .maven() - .debugLogging() - .sysProp( "surefire.rerunFailingTestsCount", 2 ) - .executeTest() - .assertTestSuiteResults( 1, 0, 0, 0, 2 ) - .assertThatLogLine( - containsString( "Found implementation of fork node factory: " + cls ), - equalTo( 1 ) ); + unpack().maven() + .debugLogging() + .sysProp("surefire.rerunFailingTestsCount", 2) + .executeTest() + .assertTestSuiteResults(1, 0, 0, 0, 2) + .assertThatLogLine(containsString("Found implementation of fork node factory: " + cls), equalTo(1)); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/JUnit47StaticInnerClassTestsIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/JUnit47StaticInnerClassTestsIT.java index c3e2e972dc..d6308f1f5b 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/JUnit47StaticInnerClassTestsIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/JUnit47StaticInnerClassTestsIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its; /* @@ -25,13 +43,10 @@ /** * */ -public class JUnit47StaticInnerClassTestsIT - extends SurefireJUnit4IntegrationTestCase -{ +public class JUnit47StaticInnerClassTestsIT extends SurefireJUnit4IntegrationTestCase { @Test - public void testStaticInnerClassTests() - { - executeErrorFreeTest( "junit47-static-inner-class-tests", 3 ); + public void testStaticInnerClassTests() { + executeErrorFreeTest("junit47-static-inner-class-tests", 3); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/JUnit47WithCucumberIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/JUnit47WithCucumberIT.java index ccb37df32a..441107da4e 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/JUnit47WithCucumberIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/JUnit47WithCucumberIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its; /* @@ -27,31 +45,26 @@ * glitches in the reports with parallel=classes), but at least all tests are executed, the execution times are counted * correctly and failing tests are reported. The main problem that the junit47 provider has with the cucumber runner is * that the junit Description instance created by the runner has a null test class attribute. - * + * * @author agudian */ -@SuppressWarnings( "checkstyle:magicnumber" ) -public class JUnit47WithCucumberIT - extends SurefireJUnit4IntegrationTestCase -{ +@SuppressWarnings("checkstyle:magicnumber") +public class JUnit47WithCucumberIT extends SurefireJUnit4IntegrationTestCase { @Test - public void testWithoutParallel() - { - doTest( "none" ); + public void testWithoutParallel() { + doTest("none"); } @Test - public void testWithParallelClasses() - { - doTest( "classes" ); + public void testWithParallelClasses() { + doTest("classes"); } - private void doTest( String parallel ) - { - unpack( "junit47-cucumber" ) - .parallel( parallel ) - .threadCount( 2 ) + private void doTest(String parallel) { + unpack("junit47-cucumber") + .parallel(parallel) + .threadCount(2) .executeTest() - .assertTestSuiteResults( 2, 0, 1, 0 ); + .assertTestSuiteResults(2, 0, 1, 0); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/JUnit48TestCategoriesIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/JUnit48TestCategoriesIT.java index fdb56f79cc..64bcc37cb3 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/JUnit48TestCategoriesIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/JUnit48TestCategoriesIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its; /* @@ -29,117 +47,97 @@ * @author Todd Lipcon * @author Kristian Rosenvold */ -public class JUnit48TestCategoriesIT - extends SurefireJUnit4IntegrationTestCase -{ +public class JUnit48TestCategoriesIT extends SurefireJUnit4IntegrationTestCase { @Test - public void testCategoriesAB() - { - runAB( unpacked() ); + public void testCategoriesAB() { + runAB(unpacked()); } @Test - public void testCategoriesABForkAlways() - { - runAB( unpacked().forkAlways() ); + public void testCategoriesABForkAlways() { + runAB(unpacked().forkAlways()); } @Test - public void testCategoriesACFullyQualifiedClassName() - { - runACFullyQualifiedClassName( unpacked() ); + public void testCategoriesACFullyQualifiedClassName() { + runACFullyQualifiedClassName(unpacked()); } @Test - public void testCategoriesACFullyQualifiedClassNameForkAlways() - { - runACFullyQualifiedClassName( unpacked().forkAlways() ); + public void testCategoriesACFullyQualifiedClassNameForkAlways() { + runACFullyQualifiedClassName(unpacked().forkAlways()); } @Test - public void testCategoriesACClassNameSuffix() - { - runACClassNameSuffix( unpacked() ); + public void testCategoriesACClassNameSuffix() { + runACClassNameSuffix(unpacked()); } @Test - public void testCategoriesACClassNameSuffixForkAlways() - { - runACClassNameSuffix( unpacked().forkAlways() ); + public void testCategoriesACClassNameSuffixForkAlways() { + runACClassNameSuffix(unpacked().forkAlways()); } @Test - public void testCategoriesBadCategory() - { - runBadCategory( unpacked() ); + public void testCategoriesBadCategory() { + runBadCategory(unpacked()); } @Test - public void testBadCategoryForkAlways() - { - runBadCategory( unpacked().forkAlways() ); + public void testBadCategoryForkAlways() { + runBadCategory(unpacked().forkAlways()); } - private static void runAB( SurefireLauncher unpacked ) - { + private static void runAB(SurefireLauncher unpacked) { unpacked.executeTest() .verifyErrorFreeLog() - .assertTestSuiteResults( 3, 0, 0, 0 ) - .verifyTextInLog( "catA: 1" ) - .verifyTextInLog( "catB: 1" ) - .verifyTextInLog( "catC: 0" ) - .verifyTextInLog( "catNone: 0" ); + .assertTestSuiteResults(3, 0, 0, 0) + .verifyTextInLog("catA: 1") + .verifyTextInLog("catB: 1") + .verifyTextInLog("catC: 0") + .verifyTextInLog("catNone: 0"); } - private static void runACClassNameSuffix( SurefireLauncher unpacked ) - { - unpacked.groups( "CategoryA,CategoryC" ) + private static void runACClassNameSuffix(SurefireLauncher unpacked) { + unpacked.groups("CategoryA,CategoryC") .executeTest() .verifyErrorFreeLog() - .assertTestSuiteResults( 6, 0, 0, 0 ) - .verifyTextInLog( "catA: 1" ) - .verifyTextInLog( "catB: 0" ) - .verifyTextInLog( "catC: 1" ) - .verifyTextInLog( "catNone: 0" ) - .verifyTextInLog( "mA: 1" ) + .assertTestSuiteResults(6, 0, 0, 0) + .verifyTextInLog("catA: 1") + .verifyTextInLog("catB: 0") + .verifyTextInLog("catC: 1") + .verifyTextInLog("catNone: 0") + .verifyTextInLog("mA: 1") // This seems questionable !? The class is annotated with category C and method with B - .verifyTextInLog( "mB: 1" ) - - .verifyTextInLog( "mC: 1" ) - .verifyTextInLog( "CatNone: 1" ); + .verifyTextInLog("mB: 1") + .verifyTextInLog("mC: 1") + .verifyTextInLog("CatNone: 1"); } - private static void runACFullyQualifiedClassName( SurefireLauncher unpacked ) - { - unpacked.groups( "junit4.CategoryA,junit4.CategoryC" ) + private static void runACFullyQualifiedClassName(SurefireLauncher unpacked) { + unpacked.groups("junit4.CategoryA,junit4.CategoryC") .executeTest() .verifyErrorFreeLog() - .assertTestSuiteResults( 6, 0, 0, 0 ) - .verifyTextInLog( "catA: 1" ) - .verifyTextInLog( "catB: 0" ) - .verifyTextInLog( "catC: 1" ) - .verifyTextInLog( "catNone: 0" ) - .verifyTextInLog( "mA: 1" ) + .assertTestSuiteResults(6, 0, 0, 0) + .verifyTextInLog("catA: 1") + .verifyTextInLog("catB: 0") + .verifyTextInLog("catC: 1") + .verifyTextInLog("catNone: 0") + .verifyTextInLog("mA: 1") // This seems questionable !? The class is annotated with category C and method with B - .verifyTextInLog( "mB: 1" ) - - .verifyTextInLog( "mC: 1" ) - .verifyTextInLog( "CatNone: 1" ); + .verifyTextInLog("mB: 1") + .verifyTextInLog("mC: 1") + .verifyTextInLog("CatNone: 1"); } - private static void runBadCategory( SurefireLauncher unpacked ) - { - unpacked.failIfNoTests( false ) - .groups( "BadCategory" ) - .executeTest() - .verifyErrorFreeLog(); + private static void runBadCategory(SurefireLauncher unpacked) { + unpacked.failIfNoTests(false).groups("BadCategory").executeTest().verifyErrorFreeLog(); } - private SurefireLauncher unpacked() - { - return unpack( "/junit48-categories" ); + private SurefireLauncher unpacked() { + return unpack("/junit48-categories"); // .debugSurefireFork(); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/JUnit4ForkAlwaysStaticInitPollutionIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/JUnit4ForkAlwaysStaticInitPollutionIT.java index 19b937d47d..5174b0e4e3 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/JUnit4ForkAlwaysStaticInitPollutionIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/JUnit4ForkAlwaysStaticInitPollutionIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its; /* @@ -27,12 +45,9 @@ * * @author Dan Fabulich */ -public class JUnit4ForkAlwaysStaticInitPollutionIT - extends SurefireJUnit4IntegrationTestCase -{ +public class JUnit4ForkAlwaysStaticInitPollutionIT extends SurefireJUnit4IntegrationTestCase { @Test - public void testJunit4Ignore() - { - executeErrorFreeTest( "junit4-forkAlways-staticInit", 2 ); + public void testJunit4Ignore() { + executeErrorFreeTest("junit4-forkAlways-staticInit", 2); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/JUnit4IgnoreIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/JUnit4IgnoreIT.java index 71ec3d8b5b..043346575d 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/JUnit4IgnoreIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/JUnit4IgnoreIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its; /* @@ -28,25 +46,23 @@ * * @author Dan Fabulich */ -public class JUnit4IgnoreIT - extends SurefireJUnit4IntegrationTestCase -{ +public class JUnit4IgnoreIT extends SurefireJUnit4IntegrationTestCase { @Test - public void testJunit4Ignore() - { + public void testJunit4Ignore() { // Todo: Support assumption failure == ignore for junit4 - unpack().executeTest().verifyErrorFreeLog().assertTestSuiteResults( 7, 0, 0, 6 ); + unpack().executeTest().verifyErrorFreeLog().assertTestSuiteResults(7, 0, 0, 6); } @Test - public void testJunit47ParallelIgnore() - { - unpack().setJUnitVersion( "4.8.1" ).parallelClasses().executeTest().verifyErrorFreeLog().assertTestSuiteResults( - 7, 0, 0, 7 ); + public void testJunit47ParallelIgnore() { + unpack().setJUnitVersion("4.8.1") + .parallelClasses() + .executeTest() + .verifyErrorFreeLog() + .assertTestSuiteResults(7, 0, 0, 7); } - private SurefireLauncher unpack() - { - return unpack( "/junit-ignore" ); + private SurefireLauncher unpack() { + return unpack("/junit-ignore"); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/JUnit4RerunFailingTestsIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/JUnit4RerunFailingTestsIT.java index 3903dd431c..99d9cfbd6b 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/JUnit4RerunFailingTestsIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/JUnit4RerunFailingTestsIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its; /* @@ -29,247 +47,321 @@ * * @author Qingzhou Luo */ -public class JUnit4RerunFailingTestsIT - extends SurefireJUnit4IntegrationTestCase -{ +public class JUnit4RerunFailingTestsIT extends SurefireJUnit4IntegrationTestCase { private static final String VERSION = "4.13.2"; - private SurefireLauncher unpack() - { - return unpack( "/junit4-rerun-failing-tests" ); + private SurefireLauncher unpack() { + return unpack("/junit4-rerun-failing-tests"); } @Test - public void testRerunFailingErrorTestsWithOneRetry() - { - OutputValidator outputValidator = - unpack().addGoal( "-Dprovider=surefire-junit4" ).setJUnitVersion( VERSION ).maven().addGoal( - "-Dsurefire.rerunFailingTestsCount=1" ).withFailure().executeTest().assertTestSuiteResults( 5, 1, 1, 0, - 0 ); - verifyFailuresOneRetryAllClasses( outputValidator ); - - outputValidator = unpack().addGoal( "-Dprovider=surefire-junit4" ).setJUnitVersion( VERSION ).maven().addGoal( - "-Dsurefire.rerunFailingTestsCount=1" ).addGoal( - "-DforkCount=2" ).withFailure().executeTest().assertTestSuiteResults( 5, 1, 1, 0, 0 ); - verifyFailuresOneRetryAllClasses( outputValidator ); - - outputValidator = unpack().addGoal( "-Dprovider=surefire-junit4" ).setJUnitVersion( VERSION ).maven().addGoal( - "-Dsurefire.rerunFailingTestsCount=1" ).addGoal( "-Dparallel=methods" ).addGoal( - "-DuseUnlimitedThreads=true" ).withFailure().executeTest().assertTestSuiteResults( 5, 1, 1, 0, 0 ); - verifyFailuresOneRetryAllClasses( outputValidator ); - - outputValidator = unpack().addGoal( "-Dprovider=surefire-junit4" ).setJUnitVersion( VERSION ).maven().addGoal( - "-Dsurefire.rerunFailingTestsCount=1" ).addGoal( "-Dparallel=classes" ).addGoal( - "-DuseUnlimitedThreads=true" ).withFailure().executeTest().assertTestSuiteResults( 5, 1, 1, 0, 0 ); - verifyFailuresOneRetryAllClasses( outputValidator ); + public void testRerunFailingErrorTestsWithOneRetry() { + OutputValidator outputValidator = unpack().addGoal("-Dprovider=surefire-junit4") + .setJUnitVersion(VERSION) + .maven() + .addGoal("-Dsurefire.rerunFailingTestsCount=1") + .withFailure() + .executeTest() + .assertTestSuiteResults(5, 1, 1, 0, 0); + verifyFailuresOneRetryAllClasses(outputValidator); + + outputValidator = unpack().addGoal("-Dprovider=surefire-junit4") + .setJUnitVersion(VERSION) + .maven() + .addGoal("-Dsurefire.rerunFailingTestsCount=1") + .addGoal("-DforkCount=2") + .withFailure() + .executeTest() + .assertTestSuiteResults(5, 1, 1, 0, 0); + verifyFailuresOneRetryAllClasses(outputValidator); + + outputValidator = unpack().addGoal("-Dprovider=surefire-junit4") + .setJUnitVersion(VERSION) + .maven() + .addGoal("-Dsurefire.rerunFailingTestsCount=1") + .addGoal("-Dparallel=methods") + .addGoal("-DuseUnlimitedThreads=true") + .withFailure() + .executeTest() + .assertTestSuiteResults(5, 1, 1, 0, 0); + verifyFailuresOneRetryAllClasses(outputValidator); + + outputValidator = unpack().addGoal("-Dprovider=surefire-junit4") + .setJUnitVersion(VERSION) + .maven() + .addGoal("-Dsurefire.rerunFailingTestsCount=1") + .addGoal("-Dparallel=classes") + .addGoal("-DuseUnlimitedThreads=true") + .withFailure() + .executeTest() + .assertTestSuiteResults(5, 1, 1, 0, 0); + verifyFailuresOneRetryAllClasses(outputValidator); } @Test - public void testRerunFailingErrorTestsTwoRetry() - { + public void testRerunFailingErrorTestsTwoRetry() { // Four flakes, both tests have been re-run twice - OutputValidator outputValidator = - unpack().addGoal( "-Dprovider=surefire-junit4" ).setJUnitVersion( VERSION ).maven().addGoal( - "-Dsurefire.rerunFailingTestsCount=2" ).executeTest().assertTestSuiteResults( 5, 0, 0, 0, 4 ); - - verifyFailuresTwoRetryAllClasses( outputValidator ); - - outputValidator = unpack().addGoal( "-Dprovider=surefire-junit4" ).setJUnitVersion( VERSION ).maven().addGoal( - "-Dsurefire.rerunFailingTestsCount=2" ).addGoal( "-DforkCount=3" ).executeTest() - .assertTestSuiteResults( 5, 0, 0, 0, 4 ); - - verifyFailuresTwoRetryAllClasses( outputValidator ); - - outputValidator = unpack().addGoal( "-Dprovider=surefire-junit4" ).setJUnitVersion( VERSION ).maven().addGoal( - "-Dsurefire.rerunFailingTestsCount=2" ).addGoal( "-Dparallel=methods" ).addGoal( - "-DuseUnlimitedThreads=true" ).executeTest().assertTestSuiteResults( 5, 0, 0, 0, 4 ); - - verifyFailuresTwoRetryAllClasses( outputValidator ); - - outputValidator = unpack().addGoal( "-Dprovider=surefire-junit4" ).setJUnitVersion( VERSION ).maven().addGoal( - "-Dsurefire.rerunFailingTestsCount=2" ).addGoal( "-Dparallel=classes" ).addGoal( - "-DuseUnlimitedThreads=true" ).executeTest().assertTestSuiteResults( 5, 0, 0, 0, 4 ); - - verifyFailuresTwoRetryAllClasses( outputValidator ); + OutputValidator outputValidator = unpack().addGoal("-Dprovider=surefire-junit4") + .setJUnitVersion(VERSION) + .maven() + .addGoal("-Dsurefire.rerunFailingTestsCount=2") + .executeTest() + .assertTestSuiteResults(5, 0, 0, 0, 4); + + verifyFailuresTwoRetryAllClasses(outputValidator); + + outputValidator = unpack().addGoal("-Dprovider=surefire-junit4") + .setJUnitVersion(VERSION) + .maven() + .addGoal("-Dsurefire.rerunFailingTestsCount=2") + .addGoal("-DforkCount=3") + .executeTest() + .assertTestSuiteResults(5, 0, 0, 0, 4); + + verifyFailuresTwoRetryAllClasses(outputValidator); + + outputValidator = unpack().addGoal("-Dprovider=surefire-junit4") + .setJUnitVersion(VERSION) + .maven() + .addGoal("-Dsurefire.rerunFailingTestsCount=2") + .addGoal("-Dparallel=methods") + .addGoal("-DuseUnlimitedThreads=true") + .executeTest() + .assertTestSuiteResults(5, 0, 0, 0, 4); + + verifyFailuresTwoRetryAllClasses(outputValidator); + + outputValidator = unpack().addGoal("-Dprovider=surefire-junit4") + .setJUnitVersion(VERSION) + .maven() + .addGoal("-Dsurefire.rerunFailingTestsCount=2") + .addGoal("-Dparallel=classes") + .addGoal("-DuseUnlimitedThreads=true") + .executeTest() + .assertTestSuiteResults(5, 0, 0, 0, 4); + + verifyFailuresTwoRetryAllClasses(outputValidator); } @Test - public void testRerunFailingErrorTestsFalse() - { - OutputValidator outputValidator = unpack().addGoal( "-Dprovider=surefire-junit4" ).setJUnitVersion( - VERSION ).maven().withFailure().executeTest().assertTestSuiteResults( 5, 1, 1, 0, 0 ); - - verifyFailuresNoRetryAllClasses( outputValidator ); - - outputValidator = unpack().addGoal( "-Dprovider=surefire-junit4" ).setJUnitVersion( VERSION ).maven().addGoal( - "-DforkCount=3" ).withFailure().executeTest().assertTestSuiteResults( 5, 1, 1, 0, 0 ); - - verifyFailuresNoRetryAllClasses( outputValidator ); - - outputValidator = unpack().addGoal( "-Dprovider=surefire-junit4" ).setJUnitVersion( VERSION ).maven().addGoal( - "-Dparallel=methods" ).addGoal( - "-DuseUnlimitedThreads=true" ).withFailure().executeTest().assertTestSuiteResults( 5, 1, 1, 0, 0 ); - - verifyFailuresNoRetryAllClasses( outputValidator ); - - outputValidator = unpack().addGoal( "-Dprovider=surefire-junit4" ).setJUnitVersion( VERSION ).maven().addGoal( - "-Dparallel=classes" ).addGoal( - "-DuseUnlimitedThreads=true" ).withFailure().executeTest().assertTestSuiteResults( 5, 1, 1, 0, 0 ); - - verifyFailuresNoRetryAllClasses( outputValidator ); + public void testRerunFailingErrorTestsFalse() { + OutputValidator outputValidator = unpack().addGoal("-Dprovider=surefire-junit4") + .setJUnitVersion(VERSION) + .maven() + .withFailure() + .executeTest() + .assertTestSuiteResults(5, 1, 1, 0, 0); + + verifyFailuresNoRetryAllClasses(outputValidator); + + outputValidator = unpack().addGoal("-Dprovider=surefire-junit4") + .setJUnitVersion(VERSION) + .maven() + .addGoal("-DforkCount=3") + .withFailure() + .executeTest() + .assertTestSuiteResults(5, 1, 1, 0, 0); + + verifyFailuresNoRetryAllClasses(outputValidator); + + outputValidator = unpack().addGoal("-Dprovider=surefire-junit4") + .setJUnitVersion(VERSION) + .maven() + .addGoal("-Dparallel=methods") + .addGoal("-DuseUnlimitedThreads=true") + .withFailure() + .executeTest() + .assertTestSuiteResults(5, 1, 1, 0, 0); + + verifyFailuresNoRetryAllClasses(outputValidator); + + outputValidator = unpack().addGoal("-Dprovider=surefire-junit4") + .setJUnitVersion(VERSION) + .maven() + .addGoal("-Dparallel=classes") + .addGoal("-DuseUnlimitedThreads=true") + .withFailure() + .executeTest() + .assertTestSuiteResults(5, 1, 1, 0, 0); + + verifyFailuresNoRetryAllClasses(outputValidator); } @Test - public void testRerunOneTestClass() - { - OutputValidator outputValidator = - unpack().addGoal( "-Dprovider=surefire-junit4" ).setJUnitVersion( VERSION ).maven().addGoal( - "-Dsurefire.rerunFailingTestsCount=1" ).addGoal( - "-Dtest=FlakyFirstTimeTest" ).withFailure().executeTest().assertTestSuiteResults( 3, 1, 1, 0, 0 ); - - verifyFailuresOneRetryOneClass( outputValidator ); - - outputValidator = unpack().addGoal( "-Dprovider=surefire-junit4" ).setJUnitVersion( VERSION ).maven().addGoal( - "-Dsurefire.rerunFailingTestsCount=1" ).addGoal( "-DforkCount=3" ).addGoal( - "-Dtest=FlakyFirstTimeTest" ).withFailure().executeTest().assertTestSuiteResults( 3, 1, 1, 0, 0 ); - - verifyFailuresOneRetryOneClass( outputValidator ); - - outputValidator = unpack().addGoal( "-Dprovider=surefire-junit4" ).setJUnitVersion( VERSION ).maven().addGoal( - "-Dsurefire.rerunFailingTestsCount=1" ).addGoal( "-Dparallel=methods" ).addGoal( - "-DuseUnlimitedThreads=true" ).addGoal( - "-Dtest=FlakyFirstTimeTest" ).withFailure().executeTest().assertTestSuiteResults( 3, 1, 1, 0, 0 ); - - verifyFailuresOneRetryOneClass( outputValidator ); - - outputValidator = unpack().addGoal( "-Dprovider=surefire-junit4" ).setJUnitVersion( VERSION ).maven().addGoal( - "-Dsurefire.rerunFailingTestsCount=1" ).addGoal( "-Dparallel=classes" ).addGoal( - "-DuseUnlimitedThreads=true" ).addGoal( - "-Dtest=FlakyFirstTimeTest" ).withFailure().executeTest().assertTestSuiteResults( 3, 1, 1, 0, 0 ); - - verifyFailuresOneRetryOneClass( outputValidator ); + public void testRerunOneTestClass() { + OutputValidator outputValidator = unpack().addGoal("-Dprovider=surefire-junit4") + .setJUnitVersion(VERSION) + .maven() + .addGoal("-Dsurefire.rerunFailingTestsCount=1") + .addGoal("-Dtest=FlakyFirstTimeTest") + .withFailure() + .executeTest() + .assertTestSuiteResults(3, 1, 1, 0, 0); + + verifyFailuresOneRetryOneClass(outputValidator); + + outputValidator = unpack().addGoal("-Dprovider=surefire-junit4") + .setJUnitVersion(VERSION) + .maven() + .addGoal("-Dsurefire.rerunFailingTestsCount=1") + .addGoal("-DforkCount=3") + .addGoal("-Dtest=FlakyFirstTimeTest") + .withFailure() + .executeTest() + .assertTestSuiteResults(3, 1, 1, 0, 0); + + verifyFailuresOneRetryOneClass(outputValidator); + + outputValidator = unpack().addGoal("-Dprovider=surefire-junit4") + .setJUnitVersion(VERSION) + .maven() + .addGoal("-Dsurefire.rerunFailingTestsCount=1") + .addGoal("-Dparallel=methods") + .addGoal("-DuseUnlimitedThreads=true") + .addGoal("-Dtest=FlakyFirstTimeTest") + .withFailure() + .executeTest() + .assertTestSuiteResults(3, 1, 1, 0, 0); + + verifyFailuresOneRetryOneClass(outputValidator); + + outputValidator = unpack().addGoal("-Dprovider=surefire-junit4") + .setJUnitVersion(VERSION) + .maven() + .addGoal("-Dsurefire.rerunFailingTestsCount=1") + .addGoal("-Dparallel=classes") + .addGoal("-DuseUnlimitedThreads=true") + .addGoal("-Dtest=FlakyFirstTimeTest") + .withFailure() + .executeTest() + .assertTestSuiteResults(3, 1, 1, 0, 0); + + verifyFailuresOneRetryOneClass(outputValidator); } @Test - public void testRerunOneTestMethod() - { - OutputValidator outputValidator = - unpack().addGoal( "-Dprovider=surefire-junit4" ).setJUnitVersion( VERSION ).maven().addGoal( - "-Dsurefire.rerunFailingTestsCount=1" ).addGoal( - "-Dtest=FlakyFirstTimeTest#testFailing*" ).withFailure().executeTest().assertTestSuiteResults( 1, 0, 1, - 0, 0 ); - - verifyFailuresOneRetryOneMethod( outputValidator ); - - outputValidator = unpack().addGoal( "-Dprovider=surefire-junit4" ).setJUnitVersion( VERSION ).maven().addGoal( - "-Dsurefire.rerunFailingTestsCount=1" ).addGoal( "-DforkCount=3" ).addGoal( - "-Dtest=FlakyFirstTimeTest#testFailing*" ).withFailure().executeTest().assertTestSuiteResults( 1, 0, 1, 0, - 0 ); - - verifyFailuresOneRetryOneMethod( outputValidator ); - - outputValidator = unpack().addGoal( "-Dprovider=surefire-junit4" ).setJUnitVersion( VERSION ).maven().addGoal( - "-Dsurefire.rerunFailingTestsCount=1" ).addGoal( "-Dparallel=methods" ).addGoal( - "-DuseUnlimitedThreads=true" ).addGoal( - "-Dtest=FlakyFirstTimeTest#testFailing*" ).withFailure().executeTest().assertTestSuiteResults( 1, 0, 1, 0, - 0 ); - - verifyFailuresOneRetryOneMethod( outputValidator ); - - outputValidator = unpack().addGoal( "-Dprovider=surefire-junit4" ).setJUnitVersion( VERSION ).maven().addGoal( - "-Dsurefire.rerunFailingTestsCount=1" ).addGoal( "-Dparallel=classes" ).addGoal( - "-DuseUnlimitedThreads=true" ).addGoal( - "-Dtest=FlakyFirstTimeTest#testFailing*" ).withFailure().executeTest().assertTestSuiteResults( 1, 0, 1, 0, - 0 ); - - verifyFailuresOneRetryOneMethod( outputValidator ); + public void testRerunOneTestMethod() { + OutputValidator outputValidator = unpack().addGoal("-Dprovider=surefire-junit4") + .setJUnitVersion(VERSION) + .maven() + .addGoal("-Dsurefire.rerunFailingTestsCount=1") + .addGoal("-Dtest=FlakyFirstTimeTest#testFailing*") + .withFailure() + .executeTest() + .assertTestSuiteResults(1, 0, 1, 0, 0); + + verifyFailuresOneRetryOneMethod(outputValidator); + + outputValidator = unpack().addGoal("-Dprovider=surefire-junit4") + .setJUnitVersion(VERSION) + .maven() + .addGoal("-Dsurefire.rerunFailingTestsCount=1") + .addGoal("-DforkCount=3") + .addGoal("-Dtest=FlakyFirstTimeTest#testFailing*") + .withFailure() + .executeTest() + .assertTestSuiteResults(1, 0, 1, 0, 0); + + verifyFailuresOneRetryOneMethod(outputValidator); + + outputValidator = unpack().addGoal("-Dprovider=surefire-junit4") + .setJUnitVersion(VERSION) + .maven() + .addGoal("-Dsurefire.rerunFailingTestsCount=1") + .addGoal("-Dparallel=methods") + .addGoal("-DuseUnlimitedThreads=true") + .addGoal("-Dtest=FlakyFirstTimeTest#testFailing*") + .withFailure() + .executeTest() + .assertTestSuiteResults(1, 0, 1, 0, 0); + + verifyFailuresOneRetryOneMethod(outputValidator); + + outputValidator = unpack().addGoal("-Dprovider=surefire-junit4") + .setJUnitVersion(VERSION) + .maven() + .addGoal("-Dsurefire.rerunFailingTestsCount=1") + .addGoal("-Dparallel=classes") + .addGoal("-DuseUnlimitedThreads=true") + .addGoal("-Dtest=FlakyFirstTimeTest#testFailing*") + .withFailure() + .executeTest() + .assertTestSuiteResults(1, 0, 1, 0, 0); + + verifyFailuresOneRetryOneMethod(outputValidator); } - private void verifyFailuresOneRetryAllClasses( OutputValidator outputValidator ) - { - verifyFailuresOneRetry( outputValidator, 5, 1, 1, 0 ); + private void verifyFailuresOneRetryAllClasses(OutputValidator outputValidator) { + verifyFailuresOneRetry(outputValidator, 5, 1, 1, 0); } - private void verifyFailuresTwoRetryAllClasses( OutputValidator outputValidator ) - { - verifyFailuresTwoRetry( outputValidator, 5, 0, 0, 2 ); + private void verifyFailuresTwoRetryAllClasses(OutputValidator outputValidator) { + verifyFailuresTwoRetry(outputValidator, 5, 0, 0, 2); } - private void verifyFailuresNoRetryAllClasses( OutputValidator outputValidator ) - { - verifyFailuresNoRetry( outputValidator, 5, 1, 1, 0 ); + private void verifyFailuresNoRetryAllClasses(OutputValidator outputValidator) { + verifyFailuresNoRetry(outputValidator, 5, 1, 1, 0); } - private void verifyFailuresOneRetryOneClass( OutputValidator outputValidator ) - { - verifyFailuresOneRetry( outputValidator, 3, 1, 1, 0 ); + private void verifyFailuresOneRetryOneClass(OutputValidator outputValidator) { + verifyFailuresOneRetry(outputValidator, 3, 1, 1, 0); } - private void verifyFailuresOneRetryOneMethod( OutputValidator outputValidator ) - { - verifyOnlyFailuresOneRetry( outputValidator, 1, 1, 0, 0 ); + private void verifyFailuresOneRetryOneMethod(OutputValidator outputValidator) { + verifyOnlyFailuresOneRetry(outputValidator, 1, 1, 0, 0); } - private void verifyFailuresOneRetry( OutputValidator outputValidator, int run, int failures, int errors, - int flakes ) - { - outputValidator.verifyTextInLog( "Failures:" ); - outputValidator.verifyTextInLog( "Run 1: FlakyFirstTimeTest.testFailingTestOne" ); - outputValidator.verifyTextInLog( "Run 2: FlakyFirstTimeTest.testFailingTestOne" ); + private void verifyFailuresOneRetry( + OutputValidator outputValidator, int run, int failures, int errors, int flakes) { + outputValidator.verifyTextInLog("Failures:"); + outputValidator.verifyTextInLog("Run 1: FlakyFirstTimeTest.testFailingTestOne"); + outputValidator.verifyTextInLog("Run 2: FlakyFirstTimeTest.testFailingTestOne"); - outputValidator.verifyTextInLog( "Errors:" ); - outputValidator.verifyTextInLog( "Run 1: FlakyFirstTimeTest.testErrorTestOne" ); - outputValidator.verifyTextInLog( "Run 2: FlakyFirstTimeTest.testErrorTestOne" ); + outputValidator.verifyTextInLog("Errors:"); + outputValidator.verifyTextInLog("Run 1: FlakyFirstTimeTest.testErrorTestOne"); + outputValidator.verifyTextInLog("Run 2: FlakyFirstTimeTest.testErrorTestOne"); - verifyStatistics( outputValidator, run, failures, errors, flakes ); + verifyStatistics(outputValidator, run, failures, errors, flakes); } - private void verifyOnlyFailuresOneRetry( OutputValidator outputValidator, int run, int failures, int errors, - int flakes ) - { - outputValidator.verifyTextInLog( "Failures:" ); - outputValidator.verifyTextInLog( "Run 1: FlakyFirstTimeTest.testFailingTestOne" ); - outputValidator.verifyTextInLog( "Run 2: FlakyFirstTimeTest.testFailingTestOne" ); + private void verifyOnlyFailuresOneRetry( + OutputValidator outputValidator, int run, int failures, int errors, int flakes) { + outputValidator.verifyTextInLog("Failures:"); + outputValidator.verifyTextInLog("Run 1: FlakyFirstTimeTest.testFailingTestOne"); + outputValidator.verifyTextInLog("Run 2: FlakyFirstTimeTest.testFailingTestOne"); - verifyStatistics( outputValidator, run, failures, errors, flakes ); + verifyStatistics(outputValidator, run, failures, errors, flakes); } - private void verifyFailuresTwoRetry( OutputValidator outputValidator, int run, int failures, int errors, - int flakes ) - { - outputValidator.verifyTextInLog( "Flakes:" ); - outputValidator.verifyTextInLog( "Run 1: FlakyFirstTimeTest.testFailingTestOne" ); - outputValidator.verifyTextInLog( "Run 2: FlakyFirstTimeTest.testFailingTestOne" ); - outputValidator.verifyTextInLog( "Run 3: PASS" ); + private void verifyFailuresTwoRetry( + OutputValidator outputValidator, int run, int failures, int errors, int flakes) { + outputValidator.verifyTextInLog("Flakes:"); + outputValidator.verifyTextInLog("Run 1: FlakyFirstTimeTest.testFailingTestOne"); + outputValidator.verifyTextInLog("Run 2: FlakyFirstTimeTest.testFailingTestOne"); + outputValidator.verifyTextInLog("Run 3: PASS"); - outputValidator.verifyTextInLog( "Run 1: FlakyFirstTimeTest.testErrorTestOne" ); - outputValidator.verifyTextInLog( "Run 2: FlakyFirstTimeTest.testErrorTestOne" ); + outputValidator.verifyTextInLog("Run 1: FlakyFirstTimeTest.testErrorTestOne"); + outputValidator.verifyTextInLog("Run 2: FlakyFirstTimeTest.testErrorTestOne"); - verifyStatistics( outputValidator, run, failures, errors, flakes ); + verifyStatistics(outputValidator, run, failures, errors, flakes); } - private void verifyFailuresNoRetry( OutputValidator outputValidator, int run, int failures, int errors, int flakes ) - { - outputValidator.verifyTextInLog( "Failures:" ); - outputValidator.verifyTextInLog( "junit4.FlakyFirstTimeTest.testFailingTestOne" ); - outputValidator.verifyTextInLog( "ERROR" ); - outputValidator.verifyTextInLog( "junit4.FlakyFirstTimeTest.testErrorTestOne" ); + private void verifyFailuresNoRetry(OutputValidator outputValidator, int run, int failures, int errors, int flakes) { + outputValidator.verifyTextInLog("Failures:"); + outputValidator.verifyTextInLog("junit4.FlakyFirstTimeTest.testFailingTestOne"); + outputValidator.verifyTextInLog("ERROR"); + outputValidator.verifyTextInLog("junit4.FlakyFirstTimeTest.testErrorTestOne"); - verifyStatistics( outputValidator, run, failures, errors, flakes ); + verifyStatistics(outputValidator, run, failures, errors, flakes); } - private void verifyStatistics( OutputValidator outputValidator, int run, int failures, int errors, int flakes ) - { - if ( flakes > 0 ) - { - outputValidator.verifyTextInLog( - "Tests run: " + run + ", Failures: " + failures + ", Errors: " + errors + ", Skipped: 0, Flakes: " - + flakes ); - } - else - { + private void verifyStatistics(OutputValidator outputValidator, int run, int failures, int errors, int flakes) { + if (flakes > 0) { + outputValidator.verifyTextInLog("Tests run: " + run + ", Failures: " + failures + ", Errors: " + errors + + ", Skipped: 0, Flakes: " + flakes); + } else { outputValidator.verifyTextInLog( - "Tests run: " + run + ", Failures: " + failures + ", Errors: " + errors + ", Skipped: 0" ); + "Tests run: " + run + ", Failures: " + failures + ", Errors: " + errors + ", Skipped: 0"); } } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/JUnit4RunListenerIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/JUnit4RunListenerIT.java index adf96e62ba..a62125de19 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/JUnit4RunListenerIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/JUnit4RunListenerIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its; /* @@ -29,43 +47,39 @@ * * @author Matthew Gilliard */ -public class JUnit4RunListenerIT - extends SurefireJUnit4IntegrationTestCase -{ - private SurefireLauncher unpack() - { - return unpack( "/junit4-runlistener" ); +public class JUnit4RunListenerIT extends SurefireJUnit4IntegrationTestCase { + private SurefireLauncher unpack() { + return unpack("/junit4-runlistener"); } @Test - public void testJUnit4RunListener() - { - final OutputValidator outputValidator = unpack().addGoal( "-Dprovider=surefire-junit4" ).setJUnitVersion( - "4.4" ).executeTest().verifyErrorFreeLog(); - assertResults( outputValidator ); - outputValidator.verifyTextInLog( "testRunStarted null" ); - outputValidator.verifyTextInLog( "testFinished simpleTest" ); - outputValidator.verifyTextInLog( "testRunFinished org.junit.runner.Result" ); + public void testJUnit4RunListener() { + final OutputValidator outputValidator = unpack().addGoal("-Dprovider=surefire-junit4") + .setJUnitVersion("4.4") + .executeTest() + .verifyErrorFreeLog(); + assertResults(outputValidator); + outputValidator.verifyTextInLog("testRunStarted null"); + outputValidator.verifyTextInLog("testFinished simpleTest"); + outputValidator.verifyTextInLog("testRunFinished org.junit.runner.Result"); } @Test - public void testRunlistenerJunitCoreProvider() - { - final OutputValidator outputValidator = - unpack().addGoal( "-Dprovider=surefire-junit47" ).setJUnitVersion( "4.8.1" ).addGoal( - "-DjunitVersion=4.8.1" ).executeTest().verifyErrorFreeLog(); // Todo: Fix junitVesion - assertResults( outputValidator ); - outputValidator.verifyTextInLog( "testRunStarted null" ); - outputValidator.verifyTextInLog( "testFinished simpleTest" ); - outputValidator.verifyTextInLog( "testRunFinished org.junit.runner.Result" ); + public void testRunlistenerJunitCoreProvider() { + final OutputValidator outputValidator = unpack().addGoal("-Dprovider=surefire-junit47") + .setJUnitVersion("4.8.1") + .addGoal("-DjunitVersion=4.8.1") + .executeTest() + .verifyErrorFreeLog(); // Todo: Fix junitVesion + assertResults(outputValidator); + outputValidator.verifyTextInLog("testRunStarted null"); + outputValidator.verifyTextInLog("testFinished simpleTest"); + outputValidator.verifyTextInLog("testRunFinished org.junit.runner.Result"); } - private void assertResults( OutputValidator outputValidator ) - { - outputValidator.assertTestSuiteResults( 1, 0, 0, 0 ); - outputValidator.getTargetFile( "runlistener-output-1.txt" ).assertFileExists(); - outputValidator.getTargetFile( "runlistener-output-2.txt" ).assertFileExists(); + private void assertResults(OutputValidator outputValidator) { + outputValidator.assertTestSuiteResults(1, 0, 0, 0); + outputValidator.getTargetFile("runlistener-output-1.txt").assertFileExists(); + outputValidator.getTargetFile("runlistener-output-2.txt").assertFileExists(); } - - } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/JUnit4VersionsIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/JUnit4VersionsIT.java index f907152a4b..8e9be3ffa6 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/JUnit4VersionsIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/JUnit4VersionsIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its; /* @@ -55,51 +73,44 @@ * * @author Dan Fabulich */ -@RunWith( Parameterized.class ) -public class JUnit4VersionsIT - extends SurefireJUnit4IntegrationTestCase -{ +@RunWith(Parameterized.class) +public class JUnit4VersionsIT extends SurefireJUnit4IntegrationTestCase { - @Parameters( name = "{index}: JUnit {0}" ) - public static Collection junitVersions() - { - return asList( new Object[][] { - { JUNIT_4_0 }, - { JUNIT_4_1 }, - { JUNIT_4_2 }, - { JUNIT_4_3 }, - { JUNIT_4_3_1 }, - { JUNIT_4_4 }, - { JUNIT_4_5 }, - { JUNIT_4_6 }, - { JUNIT_4_7 }, - { JUNIT_4_8 }, - { JUNIT_4_8_1 }, - { JUNIT_4_8_2 }, - { JUNIT_4_9 }, - { JUNIT_4_10 }, - { JUNIT_4_11 }, - { JUNIT_4_12 }, - { JUNIT_4_13 }, - { JUNIT_4_13_1 }, - { JUNIT_4_13_2 } - } ); + @Parameters(name = "{index}: JUnit {0}") + public static Collection junitVersions() { + return asList(new Object[][] { + {JUNIT_4_0}, + {JUNIT_4_1}, + {JUNIT_4_2}, + {JUNIT_4_3}, + {JUNIT_4_3_1}, + {JUNIT_4_4}, + {JUNIT_4_5}, + {JUNIT_4_6}, + {JUNIT_4_7}, + {JUNIT_4_8}, + {JUNIT_4_8_1}, + {JUNIT_4_8_2}, + {JUNIT_4_9}, + {JUNIT_4_10}, + {JUNIT_4_11}, + {JUNIT_4_12}, + {JUNIT_4_13}, + {JUNIT_4_13_1}, + {JUNIT_4_13_2} + }); } @Parameter - @SuppressWarnings( "checkstyle:visibilitymodifier" ) + @SuppressWarnings("checkstyle:visibilitymodifier") public JUnitVersion version; @Test - public void testJunit() - { - version.configure( unpack() ) - .executeTest() - .verifyErrorFree( 1 ); + public void testJunit() { + version.configure(unpack()).executeTest().verifyErrorFree(1); } - private SurefireLauncher unpack() - { - return unpack( "/junit4", version.toString() ); + private SurefireLauncher unpack() { + return unpack("/junit4", version.toString()); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/JUnitDepIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/JUnitDepIT.java index 11590fbb2f..f26fa9f1fd 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/JUnitDepIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/JUnitDepIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its; /* @@ -28,38 +46,44 @@ * * @author Dan Fabulich */ -public class JUnitDepIT extends SurefireJUnit4IntegrationTestCase -{ - public SurefireLauncher unpack() - { - return unpack( "/junit44-dep" ); +public class JUnitDepIT extends SurefireJUnit4IntegrationTestCase { + public SurefireLauncher unpack() { + return unpack("/junit44-dep"); } @Test - public void testJUnit44Dep() - { - unpack().debugLogging().sysProp( "junit-dep.version", "4.4" ).executeTest().verifyErrorFree( - 1 ).verifyTextInLog( "surefire-junit4" ); // Ahem. Will match on the 4.7 provider too + public void testJUnit44Dep() { + unpack().debugLogging() + .sysProp("junit-dep.version", "4.4") + .executeTest() + .verifyErrorFree(1) + .verifyTextInLog("surefire-junit4"); // Ahem. Will match on the 4.7 provider too } @Test - public void testJUnit44DepWithSneaky381() - { - unpack().debugLogging().sysProp( "junit-dep.version", "4.4" ).activateProfile( - "provided381" ).executeTest().verifyErrorFree( 1 ); + public void testJUnit44DepWithSneaky381() { + unpack().debugLogging() + .sysProp("junit-dep.version", "4.4") + .activateProfile("provided381") + .executeTest() + .verifyErrorFree(1); } @Test - public void testJUnit47Dep() - { - unpack().debugLogging().sysProp( "junit-dep.version", "4.7" ).executeTest().verifyErrorFree( - 1 ).verifyTextInLog( "surefire-junit47" ); + public void testJUnit47Dep() { + unpack().debugLogging() + .sysProp("junit-dep.version", "4.7") + .executeTest() + .verifyErrorFree(1) + .verifyTextInLog("surefire-junit47"); } @Test - public void testJUnit48Dep() - { - unpack().debugLogging().sysProp( "junit-dep.version", "4.8" ).executeTest().verifyErrorFree( - 1 ).verifyTextInLog( "surefire-junit47" ); + public void testJUnit48Dep() { + unpack().debugLogging() + .sysProp("junit-dep.version", "4.8") + .executeTest() + .verifyErrorFree(1) + .verifyTextInLog("surefire-junit47"); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/JUnitPlatformEnginesIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/JUnitPlatformEnginesIT.java index 96803e5684..911ae8a52d 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/JUnitPlatformEnginesIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/JUnitPlatformEnginesIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its; /* @@ -46,399 +64,400 @@ /** * */ -@RunWith( Parameterized.class ) -@SuppressWarnings( "checkstyle:magicnumber" ) -public class JUnitPlatformEnginesIT extends SurefireJUnit4IntegrationTestCase -{ +@RunWith(Parameterized.class) +@SuppressWarnings("checkstyle:magicnumber") +public class JUnitPlatformEnginesIT extends SurefireJUnit4IntegrationTestCase { private static final String XML_TESTSUITE_FRAGMENT = " artifactVersions() - { + @Parameters(name = "{0}") + public static Iterable artifactVersions() { List args = new ArrayList<>(); - args.add( new Object[] {"1.2.0", "5.2.0", "1.1.0", "1.0.0"} ); - args.add( new Object[] {"1.3.2", "5.3.2", "1.1.1", "1.0.0"} ); - args.add( new Object[] {"1.4.2", "5.4.2", "1.1.1", "1.0.0"} ); - args.add( new Object[] {"1.5.2", "5.5.2", "1.2.0", "1.1.0"} ); - args.add( new Object[] {"1.6.3", "5.6.3", "1.2.0", "1.1.0"} ); - args.add( new Object[] {"1.7.2", "5.7.2", "1.2.0", "1.1.0" } ); - args.add( new Object[] {"1.8.2", "5.8.2", "1.2.0", "1.1.2" } ); - args.add( new Object[] {"1.9.1", "5.9.1", "1.2.0", "1.1.2" } ); + args.add(new Object[] {"1.2.0", "5.2.0", "1.1.0", "1.0.0"}); + args.add(new Object[] {"1.3.2", "5.3.2", "1.1.1", "1.0.0"}); + args.add(new Object[] {"1.4.2", "5.4.2", "1.1.1", "1.0.0"}); + args.add(new Object[] {"1.5.2", "5.5.2", "1.2.0", "1.1.0"}); + args.add(new Object[] {"1.6.3", "5.6.3", "1.2.0", "1.1.0"}); + args.add(new Object[] {"1.7.2", "5.7.2", "1.2.0", "1.1.0"}); + args.add(new Object[] {"1.8.2", "5.8.2", "1.2.0", "1.1.2"}); + args.add(new Object[] {"1.9.1", "5.9.1", "1.2.0", "1.1.2"}); return args; } @Test - public void testToRegex() - { - String regex = toRegex( ".[]()*" ); - assertThat( regex ).isEqualTo( "\\.\\[\\]\\(\\).*" ); + public void testToRegex() { + String regex = toRegex(".[]()*"); + assertThat(regex).isEqualTo("\\.\\[\\]\\(\\).*"); } @Test - public void platform() throws VerificationException - { - OutputValidator validator = unpack( "junit-platform", '-' + platform ) - .sysProp( "jupiter.version", jupiter ) + public void platform() throws VerificationException { + OutputValidator validator = unpack("junit-platform", '-' + platform) + .sysProp("jupiter.version", jupiter) .debugLogging() .executeTest() - .verifyErrorFree( 1 ); - - List lines = validator.loadLogLines( startsWith( "[DEBUG] test(compact) classpath" ) ); - - assertThat( lines ).hasSize( 1 ); - - String line = lines.get( 0 ); - - assertThat( set( line ), allOf( - regex( toRegex( "*[DEBUG] test(compact) classpath:*" ) ), - regex( toRegex( "* test-classes*" ) ), - regex( toRegex( "* classes*" ) ), - regex( toRegex( "*junit-jupiter-engine-" + jupiter + ".jar*" ) ), - regex( toRegex( "*apiguardian-api-" + apiguardian + ".jar*" ) ), - regex( toRegex( "*junit-platform-engine-" + platform + ".jar*" ) ), - regex( toRegex( "*junit-platform-commons-" + platform + ".jar*" ) ), - regex( toRegex( "*opentest4j-" + opentest + ".jar*" ) ), - regex( toRegex( "*junit-jupiter-api-" + jupiter + ".jar*" ) ) - ) ); - - lines = validator.loadLogLines( startsWith( "[DEBUG] provider(compact) classpath" ) ); - - assertThat( lines ).hasSize( 1 ); - - line = lines.get( 0 ); - - assertThat( set( line ), allOf( - regex( toRegex( "*[DEBUG] provider(compact) classpath:*" ) ), - regex( toRegex( "*surefire-junit-platform-*.jar*" ) ), - regex( toRegex( "*surefire-api-*.jar*" ) ), - regex( toRegex( "*surefire-logger-api-*.jar*" ) ), - regex( toRegex( "*common-java5-*.jar*" ) ), - regex( toRegex( "*junit-platform-launcher-" + platform + ".jar*" ) ) - ) ); - - lines = validator.loadLogLines( startsWith( "[DEBUG] boot(compact) classpath" ) ); - - assertThat( lines ).hasSize( 1 ); - - line = lines.get( 0 ); - - assertThat( set( line ), allOf( - regex( toRegex( "*[DEBUG] boot(compact) classpath:*" ) ), - regex( toRegex( "*surefire-booter-*.jar*" ) ), - regex( toRegex( "*surefire-api-*.jar*" ) ), - regex( toRegex( "*surefire-logger-api-*.jar*" ) ), - regex( toRegex( "* test-classes*" ) ), - regex( toRegex( "* classes*" ) ), - regex( toRegex( "*junit-jupiter-engine-" + jupiter + ".jar*" ) ), - regex( toRegex( "*apiguardian-api-" + apiguardian + ".jar*" ) ), - regex( toRegex( "*junit-platform-engine-" + platform + ".jar*" ) ), - regex( toRegex( "*junit-platform-commons-" + platform + ".jar*" ) ), - regex( toRegex( "*opentest4j-" + opentest + ".jar*" ) ), - regex( toRegex( "*junit-jupiter-api-" + jupiter + ".jar*" ) ), - regex( toRegex( "*surefire-junit-platform-*.jar*" ) ), - regex( toRegex( "*junit-platform-launcher-" + platform + ".jar*" ) ) ) ); + .verifyErrorFree(1); + + List lines = validator.loadLogLines(startsWith("[DEBUG] test(compact) classpath")); + + assertThat(lines).hasSize(1); + + String line = lines.get(0); + + assertThat( + set(line), + allOf( + regex(toRegex("*[DEBUG] test(compact) classpath:*")), + regex(toRegex("* test-classes*")), + regex(toRegex("* classes*")), + regex(toRegex("*junit-jupiter-engine-" + jupiter + ".jar*")), + regex(toRegex("*apiguardian-api-" + apiguardian + ".jar*")), + regex(toRegex("*junit-platform-engine-" + platform + ".jar*")), + regex(toRegex("*junit-platform-commons-" + platform + ".jar*")), + regex(toRegex("*opentest4j-" + opentest + ".jar*")), + regex(toRegex("*junit-jupiter-api-" + jupiter + ".jar*")))); + + lines = validator.loadLogLines(startsWith("[DEBUG] provider(compact) classpath")); + + assertThat(lines).hasSize(1); + + line = lines.get(0); + + assertThat( + set(line), + allOf( + regex(toRegex("*[DEBUG] provider(compact) classpath:*")), + regex(toRegex("*surefire-junit-platform-*.jar*")), + regex(toRegex("*surefire-api-*.jar*")), + regex(toRegex("*surefire-logger-api-*.jar*")), + regex(toRegex("*common-java5-*.jar*")), + regex(toRegex("*junit-platform-launcher-" + platform + ".jar*")))); + + lines = validator.loadLogLines(startsWith("[DEBUG] boot(compact) classpath")); + + assertThat(lines).hasSize(1); + + line = lines.get(0); + + assertThat( + set(line), + allOf( + regex(toRegex("*[DEBUG] boot(compact) classpath:*")), + regex(toRegex("*surefire-booter-*.jar*")), + regex(toRegex("*surefire-api-*.jar*")), + regex(toRegex("*surefire-logger-api-*.jar*")), + regex(toRegex("* test-classes*")), + regex(toRegex("* classes*")), + regex(toRegex("*junit-jupiter-engine-" + jupiter + ".jar*")), + regex(toRegex("*apiguardian-api-" + apiguardian + ".jar*")), + regex(toRegex("*junit-platform-engine-" + platform + ".jar*")), + regex(toRegex("*junit-platform-commons-" + platform + ".jar*")), + regex(toRegex("*opentest4j-" + opentest + ".jar*")), + regex(toRegex("*junit-jupiter-api-" + jupiter + ".jar*")), + regex(toRegex("*surefire-junit-platform-*.jar*")), + regex(toRegex("*junit-platform-launcher-" + platform + ".jar*")))); } @Test - public void testJupiterEngine() - { - unpack( "junit-platform-engine-jupiter", "-" + jupiter ) - .setTestToRun( "Basic*Test" ) - .sysProp( "junit5.version", jupiter ) + public void testJupiterEngine() { + unpack("junit-platform-engine-jupiter", "-" + jupiter) + .setTestToRun("Basic*Test") + .sysProp("junit5.version", jupiter) .executeTest() - .verifyErrorFree( 5 ); + .verifyErrorFree(5); } @Test - public void failingBeforeAllMethod() - { - OutputValidator validator = unpack( "surefire-1688", "-" + jupiter ) - .setTestToRun( "FailingBeforeAllJupiterTest" ) - .sysProp( "junit5.version", jupiter ) + public void failingBeforeAllMethod() { + OutputValidator validator = unpack("surefire-1688", "-" + jupiter) + .setTestToRun("FailingBeforeAllJupiterTest") + .sysProp("junit5.version", jupiter) .maven() .withFailure() .executeTest() - .verifyTextInLog( "oneTimeSetUp() failed" ) - .assertTestSuiteResults( 1, 0, 1, 0 ); + .verifyTextInLog("oneTimeSetUp() failed") + .assertTestSuiteResults(1, 0, 1, 0); - validator.getSurefireReportsFile( "jira1688.FailingBeforeAllJupiterTest.txt", UTF_8 ) - .assertContainsText( "oneTimeSetUp() failed" ); + validator + .getSurefireReportsFile("jira1688.FailingBeforeAllJupiterTest.txt", UTF_8) + .assertContainsText("oneTimeSetUp() failed"); } @Test - public void errorInBeforeAllMethod() - { - OutputValidator validator = unpack( "surefire-1741", "-" + jupiter ) - .setTestToRun( "ErrorInBeforeAllJupiterTest" ) - .sysProp( "junit5.version", jupiter ) + public void errorInBeforeAllMethod() { + OutputValidator validator = unpack("surefire-1741", "-" + jupiter) + .setTestToRun("ErrorInBeforeAllJupiterTest") + .sysProp("junit5.version", jupiter) .maven() .withFailure() .executeTest() - .verifyTextInLog( "oneTimeSetUp() encountered an error" ) - .assertTestSuiteResults( 1, 1, 0, 0 ); + .verifyTextInLog("oneTimeSetUp() encountered an error") + .assertTestSuiteResults(1, 1, 0, 0); - validator.getSurefireReportsFile( "jira1741.ErrorInBeforeAllJupiterTest.txt", UTF_8 ) - .assertContainsText( "oneTimeSetUp() encountered an error" ); + validator + .getSurefireReportsFile("jira1741.ErrorInBeforeAllJupiterTest.txt", UTF_8) + .assertContainsText("oneTimeSetUp() encountered an error"); } @Test - public void testJupiterEngineWithErrorInParameterizedSource() - { - OutputValidator validator = unpack( "surefire-1741", "-" + jupiter ) - .setTestToRun( "ErrorInParameterizedSourceJupiterTest" ) - .sysProp( "junit5.version", jupiter ) + public void testJupiterEngineWithErrorInParameterizedSource() { + OutputValidator validator = unpack("surefire-1741", "-" + jupiter) + .setTestToRun("ErrorInParameterizedSourceJupiterTest") + .sysProp("junit5.version", jupiter) .maven() .withFailure() .executeTest() - .verifyTextInLog( "args() method source encountered an error" ) - .assertTestSuiteResults( 1, 1, 0, 0 ); + .verifyTextInLog("args() method source encountered an error") + .assertTestSuiteResults(1, 1, 0, 0); - validator.getSurefireReportsFile( "jira1741.ErrorInParameterizedSourceJupiterTest.txt", UTF_8 ) - .assertContainsText( "args() method source encountered an error" ); + validator + .getSurefireReportsFile("jira1741.ErrorInParameterizedSourceJupiterTest.txt", UTF_8) + .assertContainsText("args() method source encountered an error"); } @Test - public void testJupiterEngineWithFailureInParameterizedSource() - { - OutputValidator validator = unpack( "surefire-1741", "-" + jupiter ) - .setTestToRun( "FailureInParameterizedSourceJupiterTest" ) - .sysProp( "junit5.version", jupiter ) + public void testJupiterEngineWithFailureInParameterizedSource() { + OutputValidator validator = unpack("surefire-1741", "-" + jupiter) + .setTestToRun("FailureInParameterizedSourceJupiterTest") + .sysProp("junit5.version", jupiter) .maven() .withFailure() .executeTest() - .verifyTextInLog( "args() method source failed" ) - .assertTestSuiteResults( 1, 0, 1, 0 ); + .verifyTextInLog("args() method source failed") + .assertTestSuiteResults(1, 0, 1, 0); - validator.getSurefireReportsFile( "jira1741.FailureInParameterizedSourceJupiterTest.txt", UTF_8 ) - .assertContainsText( "args() method source failed" ); + validator + .getSurefireReportsFile("jira1741.FailureInParameterizedSourceJupiterTest.txt", UTF_8) + .assertContainsText("args() method source failed"); } @Test - public void testJupiterEngineWithErrorInTestFactory() - { - OutputValidator validator = unpack( "surefire-1727", "-" + jupiter ) - .setTestToRun( "ErrorInTestFactoryJupiterTest" ) - .sysProp( "junit5.version", jupiter ) + public void testJupiterEngineWithErrorInTestFactory() { + OutputValidator validator = unpack("surefire-1727", "-" + jupiter) + .setTestToRun("ErrorInTestFactoryJupiterTest") + .sysProp("junit5.version", jupiter) .maven() .withFailure() .executeTest() - .verifyTextInLog( "Encountered error in TestFactory testFactory()" ) - .assertTestSuiteResults( 1, 1, 0, 0 ); + .verifyTextInLog("Encountered error in TestFactory testFactory()") + .assertTestSuiteResults(1, 1, 0, 0); - validator.getSurefireReportsFile( "jira1727.ErrorInTestFactoryJupiterTest.txt", UTF_8 ) - .assertContainsText( "Encountered error in TestFactory testFactory()" ); + validator + .getSurefireReportsFile("jira1727.ErrorInTestFactoryJupiterTest.txt", UTF_8) + .assertContainsText("Encountered error in TestFactory testFactory()"); } @Test - public void testJupiterEngineWithFailureInTestFactory() - { - OutputValidator validator = unpack( "surefire-1727", "-" + jupiter ) - .setTestToRun( "FailureInTestFactoryJupiterTest" ) - .sysProp( "junit5.version", jupiter ) + public void testJupiterEngineWithFailureInTestFactory() { + OutputValidator validator = unpack("surefire-1727", "-" + jupiter) + .setTestToRun("FailureInTestFactoryJupiterTest") + .sysProp("junit5.version", jupiter) .maven() .withFailure() .executeTest() - .verifyTextInLog( "Encountered failure in TestFactory testFactory()" ) - .assertTestSuiteResults( 1, 0, 1, 0 ); + .verifyTextInLog("Encountered failure in TestFactory testFactory()") + .assertTestSuiteResults(1, 0, 1, 0); - validator.getSurefireReportsFile( "jira1727.FailureInTestFactoryJupiterTest.txt", UTF_8 ) - .assertContainsText( "Encountered failure in TestFactory testFactory()" ); + validator + .getSurefireReportsFile("jira1727.FailureInTestFactoryJupiterTest.txt", UTF_8) + .assertContainsText("Encountered failure in TestFactory testFactory()"); } @Test - public void testJupiterEngineWithErrorInTestTemplateProvider() - { - OutputValidator validator = unpack( "surefire-1727", "-" + jupiter ) - .setTestToRun( "ErrorInTestTemplateProviderTest" ) - .sysProp( "junit5.version", jupiter ) + public void testJupiterEngineWithErrorInTestTemplateProvider() { + OutputValidator validator = unpack("surefire-1727", "-" + jupiter) + .setTestToRun("ErrorInTestTemplateProviderTest") + .sysProp("junit5.version", jupiter) .maven() .withFailure() .executeTest() - .verifyTextInLog( "Encountered error in TestTemplate provideTestTemplateInvocationContexts()" ) - .assertTestSuiteResults( 1, 1, 0, 0 ); + .verifyTextInLog("Encountered error in TestTemplate provideTestTemplateInvocationContexts()") + .assertTestSuiteResults(1, 1, 0, 0); - validator.getSurefireReportsFile( "jira1727.ErrorInTestTemplateProviderTest.txt", UTF_8 ) - .assertContainsText( "Encountered error in TestTemplate provideTestTemplateInvocationContexts()" ); + validator + .getSurefireReportsFile("jira1727.ErrorInTestTemplateProviderTest.txt", UTF_8) + .assertContainsText("Encountered error in TestTemplate provideTestTemplateInvocationContexts()"); } @Test - public void testJupiterEngineWithFailureInTestTemplateProvider() - { - OutputValidator validator = unpack( "surefire-1727", "-" + jupiter ) - .setTestToRun( "FailureInTestTemplateProviderTest" ) - .sysProp( "junit5.version", jupiter ) + public void testJupiterEngineWithFailureInTestTemplateProvider() { + OutputValidator validator = unpack("surefire-1727", "-" + jupiter) + .setTestToRun("FailureInTestTemplateProviderTest") + .sysProp("junit5.version", jupiter) .maven() .withFailure() .executeTest() - .verifyTextInLog( "Encountered failure in TestTemplate provideTestTemplateInvocationContexts()" ) - .assertTestSuiteResults( 1, 0, 1, 0 ); + .verifyTextInLog("Encountered failure in TestTemplate provideTestTemplateInvocationContexts()") + .assertTestSuiteResults(1, 0, 1, 0); - validator.getSurefireReportsFile( "jira1727.FailureInTestTemplateProviderTest.txt", UTF_8 ) - .assertContainsText( "Encountered failure in TestTemplate provideTestTemplateInvocationContexts()" ); + validator + .getSurefireReportsFile("jira1727.FailureInTestTemplateProviderTest.txt", UTF_8) + .assertContainsText("Encountered failure in TestTemplate provideTestTemplateInvocationContexts()"); } @Test - public void testJupiterEngineWithAssertionsFailNoParameters() - { + public void testJupiterEngineWithAssertionsFailNoParameters() { // `Assertions.fail()` not supported until 5.2.0 - assumeThat( jupiter, is( not( "5.0.3" ) ) ); - assumeThat( jupiter, is( not( "5.1.1" ) ) ); + assumeThat(jupiter, is(not("5.0.3"))); + assumeThat(jupiter, is(not("5.1.1"))); - OutputValidator validator = unpack( "surefire-1748-fail-no-parameters", "-" + jupiter ) - .setTestToRun( "AssertionsFailNoParametersJupiterTest" ) - .sysProp( "junit5.version", jupiter ) + OutputValidator validator = unpack("surefire-1748-fail-no-parameters", "-" + jupiter) + .setTestToRun("AssertionsFailNoParametersJupiterTest") + .sysProp("junit5.version", jupiter) .maven() .withFailure() .executeTest() - .verifyTextInLog( "AssertionsFailNoParametersJupiterTest.doTest:31" ) - .assertTestSuiteResults( 1, 0, 1, 0 ); + .verifyTextInLog("AssertionsFailNoParametersJupiterTest.doTest") + .assertTestSuiteResults(1, 0, 1, 0); - validator.getSurefireReportsFile( "jira1748.AssertionsFailNoParametersJupiterTest.txt", UTF_8 ) - .assertContainsText( "AssertionsFailNoParametersJupiterTest.doTest" - + "(AssertionsFailNoParametersJupiterTest.java:31)" ); + validator + .getSurefireReportsFile("jira1748.AssertionsFailNoParametersJupiterTest.txt", UTF_8) + .assertContainsText( + "jira1748.AssertionsFailNoParametersJupiterTest.doTest(AssertionsFailNoParametersJupiterTest.java"); } @Test - public void testJupiterEngineWithAssertionsFailEmptyStringParameters() - { - OutputValidator validator = unpack( "surefire-1748", "-" + jupiter ) - .setTestToRun( "AssertionsFailEmptyStringParameterJupiterTest" ) - .sysProp( "junit5.version", jupiter ) + public void testJupiterEngineWithAssertionsFailEmptyStringParameters() { + OutputValidator validator = unpack("surefire-1748", "-" + jupiter) + .setTestToRun("AssertionsFailEmptyStringParameterJupiterTest") + .sysProp("junit5.version", jupiter) .maven() .withFailure() .executeTest() - .verifyTextInLog( "AssertionsFailEmptyStringParameterJupiterTest.doTest:31" ) - .assertTestSuiteResults( 1, 0, 1, 0 ); + .verifyTextInLog("AssertionsFailEmptyStringParameterJupiterTest.doTest") + .assertTestSuiteResults(1, 0, 1, 0); - validator.getSurefireReportsFile( "jira1748.AssertionsFailEmptyStringParameterJupiterTest.txt", UTF_8 ) - .assertContainsText( "AssertionsFailEmptyStringParameterJupiterTest.doTest" - + "(AssertionsFailEmptyStringParameterJupiterTest.java:31)" ); + validator + .getSurefireReportsFile("jira1748.AssertionsFailEmptyStringParameterJupiterTest.txt", UTF_8) + .assertContainsText( + "AssertionsFailEmptyStringParameterJupiterTest.doTest(AssertionsFailEmptyStringParameterJupiterTest"); } @Test - public void testJupiterEngineWithAssertionsFailMessage() - { - OutputValidator validator = unpack( "surefire-1857-assertion-message", "-" + jupiter ) - .setTestToRun( "AssertionFailureMessageTest" ) - .sysProp( "junit5.version", jupiter ) + public void testJupiterEngineWithAssertionsFailMessage() { + OutputValidator validator = unpack("surefire-1857-assertion-message", "-" + jupiter) + .setTestToRun("AssertionFailureMessageTest") + .sysProp("junit5.version", jupiter) .maven() .withFailure() .executeTest() - .verifyTextInLog( "AssertionFailureMessageTest.failedTest:31" ) - .assertTestSuiteResults( 1, 0, 1, 0 ); + .verifyTextInLog("AssertionFailureMessageTest.failedTest") + .assertTestSuiteResults(1, 0, 1, 0); - validator.getSurefireReportsFile( "TEST-jira1857.AssertionFailureMessageTest.xml", UTF_8 ) - .assertContainsText( "message=\"fail_message\"" ); + validator + .getSurefireReportsFile("TEST-jira1857.AssertionFailureMessageTest.xml", UTF_8) + .assertContainsText("message=\"fail_message\""); } @Test - public void testJupiterEngineWithExceptionMessage() - { - OutputValidator validator = unpack( "surefire-1857-exception-message", "-" + jupiter ) - .setTestToRun( "ExceptionMessageTest" ) - .sysProp( "junit5.version", jupiter ) + public void testJupiterEngineWithExceptionMessage() { + OutputValidator validator = unpack("surefire-1857-exception-message", "-" + jupiter) + .setTestToRun("ExceptionMessageTest") + .sysProp("junit5.version", jupiter) .maven() .withFailure() .executeTest() - .verifyTextInLog( "ExceptionMessageTest.errorTest:28" ) - .assertTestSuiteResults( 1, 1, 0, 0 ); + .verifyTextInLog("ExceptionMessageTest.errorTest") + .assertTestSuiteResults(1, 1, 0, 0); - validator.getSurefireReportsFile( "TEST-jira1857.ExceptionMessageTest.xml", UTF_8 ) - .assertContainsText( "message=\"error_message\"" ); + validator + .getSurefireReportsFile("TEST-jira1857.ExceptionMessageTest.xml", UTF_8) + .assertContainsText("message=\"error_message\""); } @Test - public void testJupiterEngineWithDisplayNames() throws VerificationException - { - OutputValidator validator = unpack( "junit-platform-engine-jupiter", "-" + jupiter ) - .sysProp( "junit5.version", jupiter ) + public void testJupiterEngineWithDisplayNames() throws VerificationException { + OutputValidator validator = unpack("junit-platform-engine-jupiter", "-" + jupiter) + .sysProp("junit5.version", jupiter) .executeTest() - .verifyErrorFree( 7 ); - - validator.getSurefireReportsFile( "junitplatformenginejupiter.DisplayNameTest.txt", UTF_8 ) - .assertContainsText( "<< ✨ >>" ); - - validator.getSurefireReportsFile( "junitplatformenginejupiter.DisplayNameTest.txt", UTF_8 ) - .assertContainsText( "Test set: << ✨ >>" ); - - validator.getSurefireReportsFile( "junitplatformenginejupiter.DisplayNameTest.txt", UTF_8 ) - .assertContainsText( " - in << ✨ >>" ); + .verifyErrorFree(7); + validator + .getSurefireReportsFile("junitplatformenginejupiter.DisplayNameTest.txt", UTF_8) + .assertContainsText("<< ✨ >>"); - validator.getSurefireReportsFile( "junitplatformenginejupiter.DisplayNameTest-output.txt", UTF_8 ) - .assertContainsText( "<< ✨ >>" ); + validator + .getSurefireReportsFile("junitplatformenginejupiter.DisplayNameTest.txt", UTF_8) + .assertContainsText("Test set: << ✨ >>"); - validator.getSurefireReportsFile( "junitplatformenginejupiter.DisplayNameTest-output.txt", UTF_8 ) - .assertContainsText( "73$71 ✔" ); + validator + .getSurefireReportsFile("junitplatformenginejupiter.DisplayNameTest.txt", UTF_8) + .assertContainsText(" - in << ✨ >>"); - validator.getSurefireReportsFile( "junitplatformenginejupiter.DisplayNameTest-output.txt", UTF_8 ) - .assertContainsText( "73$72 ✔" ); + validator + .getSurefireReportsFile("junitplatformenginejupiter.DisplayNameTest-output.txt", UTF_8) + .assertContainsText("<< ✨ >>"); + validator + .getSurefireReportsFile("junitplatformenginejupiter.DisplayNameTest-output.txt", UTF_8) + .assertContainsText("73$71 ✔"); - validator.getSurefireReportsFile( "TEST-junitplatformenginejupiter.DisplayNameTest.xml", UTF_8 ) - .assertContainsText( "testcase name=\"73$71 ✔\" classname=\"<< ✨ >>\"" ) - .assertContainsText( "testcase name=\"73$72 ✔\" classname=\"<< ✨ >>\"" ) - .assertContainsText( XML_TESTSUITE_FRAGMENT ); + validator + .getSurefireReportsFile("junitplatformenginejupiter.DisplayNameTest-output.txt", UTF_8) + .assertContainsText("73$72 ✔"); + validator + .getSurefireReportsFile("TEST-junitplatformenginejupiter.DisplayNameTest.xml", UTF_8) + .assertContainsText("testcase name=\"73$71 ✔\" classname=\"<< ✨ >>\"") + .assertContainsText("testcase name=\"73$72 ✔\" classname=\"<< ✨ >>\"") + .assertContainsText(XML_TESTSUITE_FRAGMENT); - validator.getSurefireReportsFile( "TEST-junitplatformenginejupiter.BasicJupiterTest.xml", UTF_8 ) - .assertContainsText( ">$" ), is( 1 ) ) - .assertThatLogLine( matchesRegex( ".*Tests run.* << . >>$" ), is( 1 ) ); + .assertThatLogLine(matchesRegex(".*Running junitplatformenginejupiter.BasicJupiterTest$"), is(1)) + .assertThatLogLine(matchesRegex(".*Tests run.* junitplatformenginejupiter.BasicJupiterTest$"), is(1)) + .assertThatLogLine(matchesRegex(".*Running << . >>$"), is(1)) + .assertThatLogLine(matchesRegex(".*Tests run.* << . >>$"), is(1)); } @Test - public void testTags() - { + public void testTags() { // [don't & !forced] not supported in 5.0.3 as it seems // PreconditionViolationException: Tag name [don't & !forced] must be syntactically valid - assumeThat( jupiter, is( not( "5.0.3" ) ) ); + assumeThat(jupiter, is(not("5.0.3"))); - unpack( "junit-platform-tags", "-" + jupiter ) - .sysProp( "junit5.version", jupiter ) + unpack("junit-platform-tags", "-" + jupiter) + .sysProp("junit5.version", jupiter) .executeTest() - .verifyErrorFree( 2 ); + .verifyErrorFree(2); } - private static String toRegex( String text ) - { - return text.replaceAll( "\\.", "\\\\." ) - .replaceAll( "\\[", "\\\\[" ) - .replaceAll( "]", "\\\\]" ) - .replaceAll( "\\(", "\\\\(" ) - .replaceAll( "\\)", "\\\\)" ) - .replaceAll( "\\*", ".*" ); + private static String toRegex(String text) { + return text.replaceAll("\\.", "\\\\.") + .replaceAll("\\[", "\\\\[") + .replaceAll("]", "\\\\]") + .replaceAll("\\(", "\\\\(") + .replaceAll("\\)", "\\\\)") + .replaceAll("\\*", ".*"); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/JUnitPlatformIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/JUnitPlatformIT.java index 22fb24dc2a..50523cec87 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/JUnitPlatformIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/JUnitPlatformIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its; /* @@ -35,75 +53,68 @@ /** * */ -@RunWith( Parameterized.class ) -@SuppressWarnings( "checkstyle:magicnumber" ) -public class JUnitPlatformIT - extends SurefireJUnit4IntegrationTestCase -{ +@RunWith(Parameterized.class) +@SuppressWarnings("checkstyle:magicnumber") +public class JUnitPlatformIT extends SurefireJUnit4IntegrationTestCase { @Parameter - @SuppressWarnings( "checkstyle:visibilitymodifier" ) + @SuppressWarnings("checkstyle:visibilitymodifier") public String junit5Version; - @Parameter( 1 ) - @SuppressWarnings( "checkstyle:visibilitymodifier" ) + @Parameter(1) + @SuppressWarnings("checkstyle:visibilitymodifier") public String jqwikVersion; - @Parameters( name = "{0}" ) - public static Iterable artifactVersions() - { + @Parameters(name = "{0}") + public static Iterable artifactVersions() { List args = new ArrayList<>(); - args.add( new Object[] { "5.2.0", "0.8.0" } ); - args.add( new Object[] { "5.3.2", "0.9.0" } ); - args.add( new Object[] { "5.4.2", "1.0.0" } ); - args.add( new Object[] { "5.5.2", "0.8.15" } ); - args.add( new Object[] { "5.6.2", "1.3.5" } ); - args.add( new Object[] { "5.7.2", "1.5.5" } ); - args.add( new Object[] { "5.8.2", "1.6.5" } ); - args.add( new Object[] { "5.9.1", "1.7.1" } ); + args.add(new Object[] {"5.2.0", "0.8.0"}); + args.add(new Object[] {"5.3.2", "0.9.0"}); + args.add(new Object[] {"5.4.2", "1.0.0"}); + args.add(new Object[] {"5.5.2", "0.8.15"}); + args.add(new Object[] {"5.6.2", "1.3.5"}); + args.add(new Object[] {"5.7.2", "1.5.5"}); + args.add(new Object[] {"5.8.2", "1.6.5"}); + args.add(new Object[] {"5.9.1", "1.7.1"}); return args; } @Test - public void testVintageEngine() - { - unpack( "junit-platform-engine-vintage", "-" + junit5Version + "-" + jqwikVersion ) - .sysProp( "junit5.version", junit5Version ) - .sysProp( "jqwik.version", jqwikVersion ) + public void testVintageEngine() { + unpack("junit-platform-engine-vintage", "-" + junit5Version + "-" + jqwikVersion) + .sysProp("junit5.version", junit5Version) + .sysProp("jqwik.version", jqwikVersion) .executeTest() - .assertTestSuiteResults( 1, 0, 0, 0 ); + .assertTestSuiteResults(1, 0, 0, 0); } @Test - public void testJQwikEngine() - { - unpack( "junit-platform-engine-jqwik", "-" + junit5Version + "-" + jqwikVersion ) - .sysProp( "junit5.version", junit5Version ) - .sysProp( "jqwik.version", jqwikVersion ) + public void testJQwikEngine() { + unpack("junit-platform-engine-jqwik", "-" + junit5Version + "-" + jqwikVersion) + .sysProp("junit5.version", junit5Version) + .sysProp("jqwik.version", jqwikVersion) .executeTest() - .assertTestSuiteResults( 1, 0, 0, 0 ); + .assertTestSuiteResults(1, 0, 0, 0); } @Test - public void testMultipleEngines() - { - OutputValidator validator = - unpack( "junit-platform-multiple-engines", "-" + junit5Version + "-" + jqwikVersion ) - .sysProp( "junit5.version", junit5Version ) - .sysProp( "jqwik.version", jqwikVersion ) + public void testMultipleEngines() { + OutputValidator validator = unpack("junit-platform-multiple-engines", "-" + junit5Version + "-" + jqwikVersion) + .sysProp("junit5.version", junit5Version) + .sysProp("jqwik.version", jqwikVersion) .executeTest() - .assertTestSuiteResults( 7, 0, 0, 0 ); - + .assertTestSuiteResults(7, 0, 0, 0); - validator.getSurefireReportsFile( "TEST-junitplatformenginejupiter.BasicJupiterTest.xml", UTF_8 ) - .assertContainsText( "Qingzhou Luo * @author Matt Coley */ -@SuppressWarnings( "checkstyle:magicnumber" ) -public class JUnitPlatformRerunFailingTestsIT extends SurefireJUnit4IntegrationTestCase -{ +@SuppressWarnings("checkstyle:magicnumber") +public class JUnitPlatformRerunFailingTestsIT extends SurefireJUnit4IntegrationTestCase { private static final String VERSION = "5.9.1"; - private SurefireLauncher unpack() - { - return unpack( "/junit-platform-rerun-failing-tests" ); + private SurefireLauncher unpack() { + return unpack("/junit-platform-rerun-failing-tests"); } @Test - public void testRerunFailingErrorTestsWithOneRetry() - { - OutputValidator outputValidator = unpack().setJUnitVersion( VERSION ).maven().addGoal( - "-Dsurefire.rerunFailingTestsCount=1" ) + public void testRerunFailingErrorTestsWithOneRetry() { + OutputValidator outputValidator = unpack().setJUnitVersion(VERSION) + .maven() + .addGoal("-Dsurefire.rerunFailingTestsCount=1") + .withFailure() + .debugLogging() + .executeTest() + .assertTestSuiteResults(5, 1, 1, 0, 0); + verifyFailuresOneRetryAllClasses(outputValidator); + + outputValidator = unpack().setJUnitVersion(VERSION) + .maven() + .debugLogging() + .addGoal("-Dsurefire.rerunFailingTestsCount=1") + .addGoal("-DforkCount=2") + .withFailure() + .executeTest() + .assertTestSuiteResults(5, 1, 1, 0, 0); + verifyFailuresOneRetryAllClasses(outputValidator); + + outputValidator = unpack().setJUnitVersion(VERSION) + .maven() + .debugLogging() + .addGoal("-Dsurefire.rerunFailingTestsCount=1") + .addGoal("-Dparallel=methods") + .addGoal("-DuseUnlimitedThreads=true") .withFailure() + .executeTest() + .assertTestSuiteResults(5, 1, 1, 0, 0); + verifyFailuresOneRetryAllClasses(outputValidator); + + outputValidator = unpack().setJUnitVersion(VERSION) + .maven() .debugLogging() + .addGoal("-Dsurefire.rerunFailingTestsCount=1") + .addGoal("-Dparallel=classes") + .addGoal("-DuseUnlimitedThreads=true") + .withFailure() .executeTest() - .assertTestSuiteResults( 5, 1, 1, 0, 0 ); - verifyFailuresOneRetryAllClasses( outputValidator ); - - outputValidator = unpack().setJUnitVersion( VERSION ).maven().debugLogging().addGoal( - "-Dsurefire.rerunFailingTestsCount=1" ).addGoal( - "-DforkCount=2" ).withFailure().executeTest().assertTestSuiteResults( 5, 1, 1, 0, 0 ); - verifyFailuresOneRetryAllClasses( outputValidator ); - - outputValidator = unpack().setJUnitVersion( VERSION ).maven().debugLogging().addGoal( - "-Dsurefire.rerunFailingTestsCount=1" ).addGoal( "-Dparallel=methods" ).addGoal( - "-DuseUnlimitedThreads=true" ).withFailure().executeTest().assertTestSuiteResults( 5, 1, 1, 0, 0 ); - verifyFailuresOneRetryAllClasses( outputValidator ); - - outputValidator = unpack().setJUnitVersion( VERSION ).maven().debugLogging().addGoal( - "-Dsurefire.rerunFailingTestsCount=1" ).addGoal( "-Dparallel=classes" ).addGoal( - "-DuseUnlimitedThreads=true" ).withFailure().executeTest().assertTestSuiteResults( 5, 1, 1, 0, 0 ); - verifyFailuresOneRetryAllClasses( outputValidator ); + .assertTestSuiteResults(5, 1, 1, 0, 0); + verifyFailuresOneRetryAllClasses(outputValidator); } @Test - public void testRerunFailingErrorTestsTwoRetry() - { + public void testRerunFailingErrorTestsTwoRetry() { // Four flakes, both tests have been re-run twice - OutputValidator outputValidator = unpack().setJUnitVersion( VERSION ).maven().debugLogging().addGoal( - "-Dsurefire.rerunFailingTestsCount=2" ).executeTest().assertTestSuiteResults( 5, 0, 0, 0, 4 ); + OutputValidator outputValidator = unpack().setJUnitVersion(VERSION) + .maven() + .debugLogging() + .addGoal("-Dsurefire.rerunFailingTestsCount=2") + .executeTest() + .assertTestSuiteResults(5, 0, 0, 0, 4); - verifyFailuresTwoRetryAllClasses( outputValidator ); + verifyFailuresTwoRetryAllClasses(outputValidator); - outputValidator = unpack().setJUnitVersion( VERSION ).maven().debugLogging().addGoal( - "-Dsurefire.rerunFailingTestsCount=2" ).addGoal( "-DforkCount=3" ).executeTest().assertTestSuiteResults( - 5, 0, 0, 0, 4 ); + outputValidator = unpack().setJUnitVersion(VERSION) + .maven() + .debugLogging() + .addGoal("-Dsurefire.rerunFailingTestsCount=2") + .addGoal("-DforkCount=3") + .executeTest() + .assertTestSuiteResults(5, 0, 0, 0, 4); - verifyFailuresTwoRetryAllClasses( outputValidator ); + verifyFailuresTwoRetryAllClasses(outputValidator); - outputValidator = unpack().setJUnitVersion( VERSION ).maven().debugLogging().addGoal( - "-Dsurefire.rerunFailingTestsCount=2" ).addGoal( "-Dparallel=methods" ).addGoal( - "-DuseUnlimitedThreads=true" ).executeTest().assertTestSuiteResults( 5, 0, 0, 0, 4 ); + outputValidator = unpack().setJUnitVersion(VERSION) + .maven() + .debugLogging() + .addGoal("-Dsurefire.rerunFailingTestsCount=2") + .addGoal("-Dparallel=methods") + .addGoal("-DuseUnlimitedThreads=true") + .executeTest() + .assertTestSuiteResults(5, 0, 0, 0, 4); - verifyFailuresTwoRetryAllClasses( outputValidator ); + verifyFailuresTwoRetryAllClasses(outputValidator); - outputValidator = unpack().setJUnitVersion( VERSION ).maven().debugLogging().addGoal( - "-Dsurefire.rerunFailingTestsCount=2" ).addGoal( "-Dparallel=classes" ).addGoal( - "-DuseUnlimitedThreads=true" ).executeTest().assertTestSuiteResults( 5, 0, 0, 0, 4 ); + outputValidator = unpack().setJUnitVersion(VERSION) + .maven() + .debugLogging() + .addGoal("-Dsurefire.rerunFailingTestsCount=2") + .addGoal("-Dparallel=classes") + .addGoal("-DuseUnlimitedThreads=true") + .executeTest() + .assertTestSuiteResults(5, 0, 0, 0, 4); - verifyFailuresTwoRetryAllClasses( outputValidator ); + verifyFailuresTwoRetryAllClasses(outputValidator); } @Test - public void testRerunFailingErrorTestsFalse() - { - OutputValidator outputValidator = unpack().setJUnitVersion( - VERSION ).maven().withFailure().debugLogging().executeTest().assertTestSuiteResults( 5, 1, 1, 0, 0 ); + public void testRerunFailingErrorTestsFalse() { + OutputValidator outputValidator = unpack().setJUnitVersion(VERSION) + .maven() + .withFailure() + .debugLogging() + .executeTest() + .assertTestSuiteResults(5, 1, 1, 0, 0); - verifyFailuresNoRetryAllClasses( outputValidator ); + verifyFailuresNoRetryAllClasses(outputValidator); - outputValidator = unpack().setJUnitVersion( VERSION ).maven().addGoal( - "-DforkCount=3" ).withFailure().debugLogging().executeTest().assertTestSuiteResults( 5, 1, 1, 0, 0 ); + outputValidator = unpack().setJUnitVersion(VERSION) + .maven() + .addGoal("-DforkCount=3") + .withFailure() + .debugLogging() + .executeTest() + .assertTestSuiteResults(5, 1, 1, 0, 0); - verifyFailuresNoRetryAllClasses( outputValidator ); + verifyFailuresNoRetryAllClasses(outputValidator); - outputValidator = unpack().setJUnitVersion( VERSION ).maven().addGoal( "-Dparallel=methods" ).addGoal( - "-DuseUnlimitedThreads=true" ).withFailure().debugLogging().executeTest().assertTestSuiteResults( 5, 1, - 1, 0, 0 ); + outputValidator = unpack().setJUnitVersion(VERSION) + .maven() + .addGoal("-Dparallel=methods") + .addGoal("-DuseUnlimitedThreads=true") + .withFailure() + .debugLogging() + .executeTest() + .assertTestSuiteResults(5, 1, 1, 0, 0); - verifyFailuresNoRetryAllClasses( outputValidator ); + verifyFailuresNoRetryAllClasses(outputValidator); - outputValidator = unpack().setJUnitVersion( VERSION ).maven().addGoal( "-Dparallel=classes" ).addGoal( - "-DuseUnlimitedThreads=true" ).withFailure().debugLogging().executeTest().assertTestSuiteResults( 5, 1, - 1, 0, 0 ); + outputValidator = unpack().setJUnitVersion(VERSION) + .maven() + .addGoal("-Dparallel=classes") + .addGoal("-DuseUnlimitedThreads=true") + .withFailure() + .debugLogging() + .executeTest() + .assertTestSuiteResults(5, 1, 1, 0, 0); - verifyFailuresNoRetryAllClasses( outputValidator ); + verifyFailuresNoRetryAllClasses(outputValidator); } @Test - public void testRerunOneTestClass() - { - OutputValidator outputValidator = unpack().setJUnitVersion( VERSION ).maven().debugLogging().addGoal( - "-Dsurefire.rerunFailingTestsCount=1" ).addGoal( - "-Dtest=FlakyFirstTimeTest" ).withFailure().executeTest().assertTestSuiteResults( 3, 1, 1, 0, 0 ); + public void testRerunOneTestClass() { + OutputValidator outputValidator = unpack().setJUnitVersion(VERSION) + .maven() + .debugLogging() + .addGoal("-Dsurefire.rerunFailingTestsCount=1") + .addGoal("-Dtest=FlakyFirstTimeTest") + .withFailure() + .executeTest() + .assertTestSuiteResults(3, 1, 1, 0, 0); - verifyFailuresOneRetryOneClass( outputValidator ); + verifyFailuresOneRetryOneClass(outputValidator); - outputValidator = unpack().setJUnitVersion( VERSION ).maven().addGoal( - "-Dsurefire.rerunFailingTestsCount=1" ).addGoal( "-DforkCount=3" ).addGoal( - "-Dtest=FlakyFirstTimeTest" ).withFailure().debugLogging().executeTest().assertTestSuiteResults( 3, 1, - 1, 0, 0 ); + outputValidator = unpack().setJUnitVersion(VERSION) + .maven() + .addGoal("-Dsurefire.rerunFailingTestsCount=1") + .addGoal("-DforkCount=3") + .addGoal("-Dtest=FlakyFirstTimeTest") + .withFailure() + .debugLogging() + .executeTest() + .assertTestSuiteResults(3, 1, 1, 0, 0); - verifyFailuresOneRetryOneClass( outputValidator ); + verifyFailuresOneRetryOneClass(outputValidator); - outputValidator = unpack().setJUnitVersion( VERSION ).maven().addGoal( - "-Dsurefire.rerunFailingTestsCount=1" ).addGoal( "-Dparallel=methods" ).addGoal( - "-DuseUnlimitedThreads=true" ).addGoal( - "-Dtest=FlakyFirstTimeTest" ).withFailure().debugLogging().executeTest().assertTestSuiteResults( 3, 1, - 1, 0, 0 ); + outputValidator = unpack().setJUnitVersion(VERSION) + .maven() + .addGoal("-Dsurefire.rerunFailingTestsCount=1") + .addGoal("-Dparallel=methods") + .addGoal("-DuseUnlimitedThreads=true") + .addGoal("-Dtest=FlakyFirstTimeTest") + .withFailure() + .debugLogging() + .executeTest() + .assertTestSuiteResults(3, 1, 1, 0, 0); - verifyFailuresOneRetryOneClass( outputValidator ); + verifyFailuresOneRetryOneClass(outputValidator); - outputValidator = unpack().setJUnitVersion( VERSION ).maven().addGoal( - "-Dsurefire.rerunFailingTestsCount=1" ).addGoal( "-Dparallel=classes" ).addGoal( - "-DuseUnlimitedThreads=true" ).addGoal( - "-Dtest=FlakyFirstTimeTest" ).withFailure().debugLogging().executeTest().assertTestSuiteResults( 3, 1, - 1, 0, 0 ); + outputValidator = unpack().setJUnitVersion(VERSION) + .maven() + .addGoal("-Dsurefire.rerunFailingTestsCount=1") + .addGoal("-Dparallel=classes") + .addGoal("-DuseUnlimitedThreads=true") + .addGoal("-Dtest=FlakyFirstTimeTest") + .withFailure() + .debugLogging() + .executeTest() + .assertTestSuiteResults(3, 1, 1, 0, 0); - verifyFailuresOneRetryOneClass( outputValidator ); + verifyFailuresOneRetryOneClass(outputValidator); } @Test - public void testRerunOneTestMethod() - { - OutputValidator outputValidator = unpack().setJUnitVersion( VERSION ).maven().addGoal( - "-Dsurefire.rerunFailingTestsCount=1" ).addGoal( - "-Dtest=FlakyFirstTimeTest#testFailing*" ).withFailure().debugLogging().executeTest() - .assertTestSuiteResults( 1, 0, 1, 0, 0 ); - - verifyFailuresOneRetryOneMethod( outputValidator ); - - outputValidator = unpack().setJUnitVersion( VERSION ).maven().addGoal( - "-Dsurefire.rerunFailingTestsCount=1" ).addGoal( "-DforkCount=3" ).addGoal( - "-Dtest=FlakyFirstTimeTest#testFailing*" ).withFailure().debugLogging().executeTest() - .assertTestSuiteResults( 1, 0, 1, 0, 0 ); - - verifyFailuresOneRetryOneMethod( outputValidator ); - - outputValidator = unpack().setJUnitVersion( VERSION ).maven().addGoal( - "-Dsurefire.rerunFailingTestsCount=1" ).addGoal( "-Dparallel=methods" ).addGoal( - "-DuseUnlimitedThreads=true" ).addGoal( - "-Dtest=FlakyFirstTimeTest#testFailing*" ) + public void testRerunOneTestMethod() { + OutputValidator outputValidator = unpack().setJUnitVersion(VERSION) + .maven() + .addGoal("-Dsurefire.rerunFailingTestsCount=1") + .addGoal("-Dtest=FlakyFirstTimeTest#testFailing*") + .withFailure() + .debugLogging() + .executeTest() + .assertTestSuiteResults(1, 0, 1, 0, 0); + + verifyFailuresOneRetryOneMethod(outputValidator); + + outputValidator = unpack().setJUnitVersion(VERSION) + .maven() + .addGoal("-Dsurefire.rerunFailingTestsCount=1") + .addGoal("-DforkCount=3") + .addGoal("-Dtest=FlakyFirstTimeTest#testFailing*") + .withFailure() + .debugLogging() + .executeTest() + .assertTestSuiteResults(1, 0, 1, 0, 0); + + verifyFailuresOneRetryOneMethod(outputValidator); + + outputValidator = unpack().setJUnitVersion(VERSION) + .maven() + .addGoal("-Dsurefire.rerunFailingTestsCount=1") + .addGoal("-Dparallel=methods") + .addGoal("-DuseUnlimitedThreads=true") + .addGoal("-Dtest=FlakyFirstTimeTest#testFailing*") .withFailure() .debugLogging() .executeTest() - .assertTestSuiteResults( 1, 0, 1, 0, 0 ); + .assertTestSuiteResults(1, 0, 1, 0, 0); - verifyFailuresOneRetryOneMethod( outputValidator ); + verifyFailuresOneRetryOneMethod(outputValidator); - outputValidator = unpack().setJUnitVersion( VERSION ).maven().addGoal( - "-Dsurefire.rerunFailingTestsCount=1" ).addGoal( "-Dparallel=classes" ).addGoal( - "-DuseUnlimitedThreads=true" ).addGoal( - "-Dtest=FlakyFirstTimeTest#testFailing*" ) + outputValidator = unpack().setJUnitVersion(VERSION) + .maven() + .addGoal("-Dsurefire.rerunFailingTestsCount=1") + .addGoal("-Dparallel=classes") + .addGoal("-DuseUnlimitedThreads=true") + .addGoal("-Dtest=FlakyFirstTimeTest#testFailing*") .withFailure() .debugLogging() .executeTest() - .assertTestSuiteResults( 1, 0, 1, 0, 0 ); + .assertTestSuiteResults(1, 0, 1, 0, 0); - verifyFailuresOneRetryOneMethod( outputValidator ); + verifyFailuresOneRetryOneMethod(outputValidator); } @Test - public void testFailOnTooManyFlakes() - { - OutputValidator outputValidator = unpack().setJUnitVersion( VERSION ).maven().debugLogging() - .addGoal( "-Dsurefire.rerunFailingTestsCount=2" ) - .addGoal( "-Dsurefire.failOnFlakeCount=1" ) - .withFailure() - .executeTest() - .assertTestSuiteResults( 5, 0, 0, 0, 4 ); - - outputValidator.verifyTextInLog( "There are 2 flakes and failOnFlakeCount is set to 1" ); + public void testFailOnTooManyFlakes() { + OutputValidator outputValidator = unpack().setJUnitVersion(VERSION) + .maven() + .debugLogging() + .addGoal("-Dsurefire.rerunFailingTestsCount=2") + .addGoal("-Dsurefire.failOnFlakeCount=1") + .withFailure() + .executeTest() + .assertTestSuiteResults(5, 0, 0, 0, 4); + + outputValidator.verifyTextInLog("There are 2 flakes and failOnFlakeCount is set to 1"); } @Test - public void testParameterizedTest() - { - unpack() - .setJUnitVersion( VERSION ) - .maven() - .activateProfile( "parameters" ) - .withFailure() - .debugLogging() - .executeTest() - .assertTestSuiteResults( 6, 0, 1, 1, 0 ) - .getSurefireReportsXmlFile( "TEST-junitplatform.ParametersTest.xml" ) - .assertContainsText( "testOneFailingPassingTest(ConnectionPoolFactory)[1]" ) - .assertContainsText( "testOneFailingPassingTest(ConnectionPoolFactory)[2]" ) - .assertContainsText( "testOneFailingPassingTest(ConnectionPoolFactory)[3]" ) - .assertContainsText( "testAllPassingTest(ConnectionPoolFactory)[1]" ) - .assertContainsText( "testAllPassingTest(ConnectionPoolFactory)[2]" ) - .assertContainsText( "testAllPassingTest(ConnectionPoolFactory)[3]" ); + public void testParameterizedTest() { + unpack().setJUnitVersion(VERSION) + .maven() + .activateProfile("parameters") + .withFailure() + .debugLogging() + .executeTest() + .assertTestSuiteResults(6, 0, 1, 1, 0) + .getSurefireReportsXmlFile("TEST-junitplatform.ParametersTest.xml") + .assertContainsText("testOneFailingPassingTest(ConnectionPoolFactory)[1]") + .assertContainsText("testOneFailingPassingTest(ConnectionPoolFactory)[2]") + .assertContainsText("testOneFailingPassingTest(ConnectionPoolFactory)[3]") + .assertContainsText("testAllPassingTest(ConnectionPoolFactory)[1]") + .assertContainsText("testAllPassingTest(ConnectionPoolFactory)[2]") + .assertContainsText("testAllPassingTest(ConnectionPoolFactory)[3]"); } - private void verifyFailuresOneRetryAllClasses( OutputValidator outputValidator ) - { - verifyFailuresOneRetry( outputValidator, 5, 1, 1, 0 ); + private void verifyFailuresOneRetryAllClasses(OutputValidator outputValidator) { + verifyFailuresOneRetry(outputValidator, 5, 1, 1, 0); } - private void verifyFailuresTwoRetryAllClasses( OutputValidator outputValidator ) - { - verifyFailuresTwoRetry( outputValidator, 5, 0, 0, 2 ); + private void verifyFailuresTwoRetryAllClasses(OutputValidator outputValidator) { + verifyFailuresTwoRetry(outputValidator, 5, 0, 0, 2); } - private void verifyFailuresNoRetryAllClasses( OutputValidator outputValidator ) - { - verifyFailuresNoRetry( outputValidator, 5, 1, 1, 0 ); + private void verifyFailuresNoRetryAllClasses(OutputValidator outputValidator) { + verifyFailuresNoRetry(outputValidator, 5, 1, 1, 0); } - private void verifyFailuresOneRetryOneClass( OutputValidator outputValidator ) - { - verifyFailuresOneRetry( outputValidator, 3, 1, 1, 0 ); + private void verifyFailuresOneRetryOneClass(OutputValidator outputValidator) { + verifyFailuresOneRetry(outputValidator, 3, 1, 1, 0); } - private void verifyFailuresOneRetryOneMethod( OutputValidator outputValidator ) - { - verifyOnlyFailuresOneRetry( outputValidator, 1, 1, 0, 0 ); + private void verifyFailuresOneRetryOneMethod(OutputValidator outputValidator) { + verifyOnlyFailuresOneRetry(outputValidator, 1, 1, 0, 0); } - private void verifyFailuresOneRetry( OutputValidator outputValidator, int run, int failures, int errors, - int flakes ) - { - outputValidator.verifyTextInLog( "Failures:" ); - outputValidator.verifyTextInLog( "Run 1: FlakyFirstTimeTest.testFailingTestOne" ); - outputValidator.verifyTextInLog( "Run 2: FlakyFirstTimeTest.testFailingTestOne" ); + private void verifyFailuresOneRetry( + OutputValidator outputValidator, int run, int failures, int errors, int flakes) { + outputValidator.verifyTextInLog("Failures:"); + outputValidator.verifyTextInLog("Run 1: FlakyFirstTimeTest.testFailingTestOne"); + outputValidator.verifyTextInLog("Run 2: FlakyFirstTimeTest.testFailingTestOne"); - outputValidator.verifyTextInLog( "Errors:" ); - outputValidator.verifyTextInLog( "Run 1: FlakyFirstTimeTest.testErrorTestOne" ); - outputValidator.verifyTextInLog( "Run 2: FlakyFirstTimeTest.testErrorTestOne" ); + outputValidator.verifyTextInLog("Errors:"); + outputValidator.verifyTextInLog("Run 1: FlakyFirstTimeTest.testErrorTestOne"); + outputValidator.verifyTextInLog("Run 2: FlakyFirstTimeTest.testErrorTestOne"); - verifyStatistics( outputValidator, run, failures, errors, flakes ); + verifyStatistics(outputValidator, run, failures, errors, flakes); } - private void verifyOnlyFailuresOneRetry( OutputValidator outputValidator, int run, int failures, int errors, - int flakes ) - { - outputValidator.verifyTextInLog( "Failures:" ); - outputValidator.verifyTextInLog( "Run 1: FlakyFirstTimeTest.testFailingTestOne" ); - outputValidator.verifyTextInLog( "Run 2: FlakyFirstTimeTest.testFailingTestOne" ); + private void verifyOnlyFailuresOneRetry( + OutputValidator outputValidator, int run, int failures, int errors, int flakes) { + outputValidator.verifyTextInLog("Failures:"); + outputValidator.verifyTextInLog("Run 1: FlakyFirstTimeTest.testFailingTestOne"); + outputValidator.verifyTextInLog("Run 2: FlakyFirstTimeTest.testFailingTestOne"); - verifyStatistics( outputValidator, run, failures, errors, flakes ); + verifyStatistics(outputValidator, run, failures, errors, flakes); } - private void verifyFailuresTwoRetry( OutputValidator outputValidator, int run, int failures, int errors, - int flakes ) - { - outputValidator.verifyTextInLog( "Flakes:" ); - outputValidator.verifyTextInLog( "Run 1: FlakyFirstTimeTest.testFailingTestOne" ); - outputValidator.verifyTextInLog( "Run 2: FlakyFirstTimeTest.testFailingTestOne" ); - outputValidator.verifyTextInLog( "Run 3: PASS" ); + private void verifyFailuresTwoRetry( + OutputValidator outputValidator, int run, int failures, int errors, int flakes) { + outputValidator.verifyTextInLog("Flakes:"); + outputValidator.verifyTextInLog("Run 1: FlakyFirstTimeTest.testFailingTestOne"); + outputValidator.verifyTextInLog("Run 2: FlakyFirstTimeTest.testFailingTestOne"); + outputValidator.verifyTextInLog("Run 3: PASS"); - outputValidator.verifyTextInLog( "Run 1: FlakyFirstTimeTest.testErrorTestOne" ); - outputValidator.verifyTextInLog( "Run 2: FlakyFirstTimeTest.testErrorTestOne" ); + outputValidator.verifyTextInLog("Run 1: FlakyFirstTimeTest.testErrorTestOne"); + outputValidator.verifyTextInLog("Run 2: FlakyFirstTimeTest.testErrorTestOne"); - verifyStatistics( outputValidator, run, failures, errors, flakes ); + verifyStatistics(outputValidator, run, failures, errors, flakes); } - private void verifyFailuresNoRetry( OutputValidator outputValidator, int run, int failures, int errors, int flakes ) - { - outputValidator.verifyTextInLog( "Failures:" ); - outputValidator.verifyTextInLog( "junitplatform.FlakyFirstTimeTest.testFailingTestOne" ); - outputValidator.verifyTextInLog( "ERROR" ); - outputValidator.verifyTextInLog( "junitplatform.FlakyFirstTimeTest.testErrorTestOne" ); + private void verifyFailuresNoRetry(OutputValidator outputValidator, int run, int failures, int errors, int flakes) { + outputValidator.verifyTextInLog("Failures:"); + outputValidator.verifyTextInLog("junitplatform.FlakyFirstTimeTest.testFailingTestOne"); + outputValidator.verifyTextInLog("ERROR"); + outputValidator.verifyTextInLog("junitplatform.FlakyFirstTimeTest.testErrorTestOne"); - verifyStatistics( outputValidator, run, failures, errors, flakes ); + verifyStatistics(outputValidator, run, failures, errors, flakes); } - private void verifyStatistics( OutputValidator outputValidator, int run, int failures, int errors, int flakes ) - { - if ( flakes > 0 ) - { - outputValidator.verifyTextInLog( - "Tests run: " + run + ", Failures: " + failures + ", Errors: " + errors + ", Skipped: 0, Flakes: " - + flakes ); - } - else - { + private void verifyStatistics(OutputValidator outputValidator, int run, int failures, int errors, int flakes) { + if (flakes > 0) { + outputValidator.verifyTextInLog("Tests run: " + run + ", Failures: " + failures + ", Errors: " + errors + + ", Skipped: 0, Flakes: " + flakes); + } else { outputValidator.verifyTextInLog( - "Tests run: " + run + ", Failures: " + failures + ", Errors: " + errors + ", Skipped: 0" ); + "Tests run: " + run + ", Failures: " + failures + ", Errors: " + errors + ", Skipped: 0"); } } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/JUnitPlatformStreamCorruptionIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/JUnitPlatformStreamCorruptionIT.java index 90810487f6..15787846f1 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/JUnitPlatformStreamCorruptionIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/JUnitPlatformStreamCorruptionIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its; /* @@ -19,67 +37,58 @@ * under the License. */ +import java.util.List; + import org.apache.maven.it.VerificationException; import org.apache.maven.surefire.its.fixture.OutputValidator; import org.apache.maven.surefire.its.fixture.SurefireJUnit4IntegrationTestCase; import org.junit.Ignore; import org.junit.Test; -import java.util.List; - import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.CoreMatchers.startsWith; /** * */ -@SuppressWarnings( "checkstyle:magicnumber" ) -public class JUnitPlatformStreamCorruptionIT - extends SurefireJUnit4IntegrationTestCase -{ +@SuppressWarnings("checkstyle:magicnumber") +public class JUnitPlatformStreamCorruptionIT extends SurefireJUnit4IntegrationTestCase { @Test - public void warningIsNotEmitted() throws VerificationException - { - OutputValidator validator = unpack( "/surefire-1614-stream-corruption" ) - .executeTest() - .verifyErrorFree( 1 ); + public void warningIsNotEmitted() throws VerificationException { + OutputValidator validator = + unpack("/surefire-1614-stream-corruption").executeTest().verifyErrorFree(1); List lines = validator.loadLogLines( - startsWith( "[WARNING] Corrupted channel by directly writing to native stream in forked JVM" ) ); + startsWith("[WARNING] Corrupted channel by directly writing to native stream in forked JVM")); - assertThat( lines ) - .isEmpty(); + assertThat(lines).isEmpty(); } @Test - public void warningIsNotEmittedWithJulToSlf4j() throws VerificationException - { - OutputValidator validator = unpack( "/surefire-1659-stream-corruption" ) - .activateProfile( "junit-platform-with-jul-to-slf4j" ) + public void warningIsNotEmittedWithJulToSlf4j() throws VerificationException { + OutputValidator validator = unpack("/surefire-1659-stream-corruption") + .activateProfile("junit-platform-with-jul-to-slf4j") .executeTest() - .verifyErrorFree( 1 ); + .verifyErrorFree(1); List lines = validator.loadLogLines( - startsWith( "[WARNING] Corrupted channel by directly writing to native stream in forked JVM" ) ); + startsWith("[WARNING] Corrupted channel by directly writing to native stream in forked JVM")); - assertThat( lines ) - .isEmpty(); + assertThat(lines).isEmpty(); } @Test - @Ignore( "https://issues.apache.org/jira/browse/SUREFIRE-1659?focusedCommentId=17374005&page=" - + "com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-17374005" ) - public void warningIsNotEmittedWithJulToLog4j() throws VerificationException - { - OutputValidator validator = unpack( "/surefire-1659-stream-corruption" ) - .activateProfile( "junit-platform-with-jul-to-log4j" ) + @Ignore("https://issues.apache.org/jira/browse/SUREFIRE-1659?focusedCommentId=17374005&page=" + + "com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-17374005") + public void warningIsNotEmittedWithJulToLog4j() throws VerificationException { + OutputValidator validator = unpack("/surefire-1659-stream-corruption") + .activateProfile("junit-platform-with-jul-to-log4j") .executeTest() - .verifyErrorFree( 1 ); + .verifyErrorFree(1); List lines = validator.loadLogLines( - startsWith( "[WARNING] Corrupted channel by directly writing to native stream in forked JVM" ) ); + startsWith("[WARNING] Corrupted channel by directly writing to native stream in forked JVM")); - assertThat( lines ) - .isEmpty(); + assertThat(lines).isEmpty(); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/JUnitVersion.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/JUnitVersion.java index e63b5c11e0..eb6f95850e 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/JUnitVersion.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/JUnitVersion.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its; /* @@ -24,43 +42,38 @@ /** * Enum listing all the JUnit version. */ -public enum JUnitVersion -{ - - JUNIT_4_0( "4.0" ), - JUNIT_4_1( "4.1" ), - JUNIT_4_2( "4.2" ), - JUNIT_4_3( "4.3" ), - JUNIT_4_3_1( "4.3.1" ), - JUNIT_4_4( "4.4" ), - JUNIT_4_5( "4.5" ), - JUNIT_4_6( "4.6" ), - JUNIT_4_7( "4.7" ), - JUNIT_4_8( "4.8" ), - JUNIT_4_8_1( "4.8.1" ), - JUNIT_4_8_2( "4.8.2" ), - JUNIT_4_9( "4.9" ), - JUNIT_4_10( "4.10" ), - JUNIT_4_11( "4.11" ), - JUNIT_4_12( "4.12" ), - JUNIT_4_13( "4.13" ), - JUNIT_4_13_1( "4.13.1" ), - JUNIT_4_13_2( "4.13.2" ); +public enum JUnitVersion { + JUNIT_4_0("4.0"), + JUNIT_4_1("4.1"), + JUNIT_4_2("4.2"), + JUNIT_4_3("4.3"), + JUNIT_4_3_1("4.3.1"), + JUNIT_4_4("4.4"), + JUNIT_4_5("4.5"), + JUNIT_4_6("4.6"), + JUNIT_4_7("4.7"), + JUNIT_4_8("4.8"), + JUNIT_4_8_1("4.8.1"), + JUNIT_4_8_2("4.8.2"), + JUNIT_4_9("4.9"), + JUNIT_4_10("4.10"), + JUNIT_4_11("4.11"), + JUNIT_4_12("4.12"), + JUNIT_4_13("4.13"), + JUNIT_4_13_1("4.13.1"), + JUNIT_4_13_2("4.13.2"); private final String version; - JUnitVersion( String version ) - { + JUnitVersion(String version) { this.version = version; } - public SurefireLauncher configure( SurefireLauncher launcher ) - { - return launcher.setJUnitVersion( version ); + public SurefireLauncher configure(SurefireLauncher launcher) { + return launcher.setJUnitVersion(version); } - public String toString() - { + public String toString() { return version; } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/Java9FullApiIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/Java9FullApiIT.java index f326e1dba7..dbb3ed7400 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/Java9FullApiIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/Java9FullApiIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its; /* @@ -33,71 +51,59 @@ * @author Tibor Digana (tibor17) * @since 2.20.1 */ -public class Java9FullApiIT - extends AbstractJava9PlusIT -{ +public class Java9FullApiIT extends AbstractJava9PlusIT { @Test - @SuppressWarnings( "checkstyle:methodname" ) - public void shouldLoadMultipleJavaModules_JavaHome() throws Exception - { - OutputValidator validator = assumeJava9() - .setForkJvm() - .debugLogging() - .execute( "verify" ) - .verifyErrorFree( 1 ); + @SuppressWarnings("checkstyle:methodname") + public void shouldLoadMultipleJavaModules_JavaHome() throws Exception { + OutputValidator validator = + assumeJava9().setForkJvm().debugLogging().execute("verify").verifyErrorFree(1); - validator.verifyTextInLog( "loaded class java.sql.SQLException" ) - .verifyTextInLog( "loaded class javax.xml.ws.Holder" ) - .verifyTextInLog( "loaded class javax.xml.bind.JAXBException" ) - .verifyTextInLog( "loaded class javax.transaction.TransactionManager" ) - .verifyTextInLog( "loaded class javax.transaction.InvalidTransactionException" ) - .assertThatLogLine( is( "java.specification.version=" + (int) JAVA_VERSION ), - greaterThanOrEqualTo( 1 ) ); + validator + .verifyTextInLog("loaded class java.sql.SQLException") + .verifyTextInLog("loaded class javax.xml.ws.Holder") + .verifyTextInLog("loaded class javax.xml.bind.JAXBException") + .verifyTextInLog("loaded class javax.transaction.TransactionManager") + .verifyTextInLog("loaded class javax.transaction.InvalidTransactionException") + .assertThatLogLine(is("java.specification.version=" + (int) JAVA_VERSION), greaterThanOrEqualTo(1)); } @Test - @SuppressWarnings( "checkstyle:methodname" ) - public void shouldLoadMultipleJavaModules_JvmParameter() throws Exception - { - OutputValidator validator = assumeJava9() - .setForkJvm() - .debugLogging() - .execute( "verify" ) - .verifyErrorFree( 1 ); + @SuppressWarnings("checkstyle:methodname") + public void shouldLoadMultipleJavaModules_JvmParameter() throws Exception { + OutputValidator validator = + assumeJava9().setForkJvm().debugLogging().execute("verify").verifyErrorFree(1); - validator.verifyTextInLog( "loaded class java.sql.SQLException" ) - .verifyTextInLog( "loaded class javax.xml.ws.Holder" ) - .verifyTextInLog( "loaded class javax.xml.bind.JAXBException" ) - .verifyTextInLog( "loaded class javax.transaction.TransactionManager" ) - .verifyTextInLog( "loaded class javax.transaction.InvalidTransactionException" ) - .assertThatLogLine( is( "java.specification.version=" + (int) JAVA_VERSION ), - greaterThanOrEqualTo( 1 ) ); + validator + .verifyTextInLog("loaded class java.sql.SQLException") + .verifyTextInLog("loaded class javax.xml.ws.Holder") + .verifyTextInLog("loaded class javax.xml.bind.JAXBException") + .verifyTextInLog("loaded class javax.transaction.TransactionManager") + .verifyTextInLog("loaded class javax.transaction.InvalidTransactionException") + .assertThatLogLine(is("java.specification.version=" + (int) JAVA_VERSION), greaterThanOrEqualTo(1)); } @Test - @SuppressWarnings( "checkstyle:methodname" ) - public void shouldLoadMultipleJavaModules_ToolchainsXML() throws Exception - { + @SuppressWarnings("checkstyle:methodname") + public void shouldLoadMultipleJavaModules_ToolchainsXML() throws Exception { OutputValidator validator = assumeJava9() - .setForkJvm() - .activateProfile( "use-toolchains" ) - .addGoal( "--toolchains" ) - .addGoal( System.getProperty( "maven.toolchains.file" ) ) - .execute( "verify" ) - .verifyErrorFree( 1 ); + .setForkJvm() + .activateProfile("use-toolchains") + .addGoal("--toolchains") + .addGoal(System.getProperty("maven.toolchains.file")) + .execute("verify") + .verifyErrorFree(1); - validator.verifyTextInLog( "loaded class java.sql.SQLException" ) - .verifyTextInLog( "loaded class javax.xml.ws.Holder" ) - .verifyTextInLog( "loaded class javax.xml.bind.JAXBException" ) - .verifyTextInLog( "loaded class javax.transaction.TransactionManager" ) - .verifyTextInLog( "loaded class javax.transaction.InvalidTransactionException" ) - .assertThatLogLine( is( "java.specification.version=" + (int) JAVA_VERSION ), - greaterThanOrEqualTo( 1 ) ); + validator + .verifyTextInLog("loaded class java.sql.SQLException") + .verifyTextInLog("loaded class javax.xml.ws.Holder") + .verifyTextInLog("loaded class javax.xml.bind.JAXBException") + .verifyTextInLog("loaded class javax.transaction.TransactionManager") + .verifyTextInLog("loaded class javax.transaction.InvalidTransactionException") + .assertThatLogLine(is("java.specification.version=" + (int) JAVA_VERSION), greaterThanOrEqualTo(1)); } @Override - protected String getProjectDirectoryName() - { + protected String getProjectDirectoryName() { return "java9-full-api"; } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/Junit5ModulePathIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/Junit5ModulePathIT.java index 08991326cb..2bba7e21a5 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/Junit5ModulePathIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/Junit5ModulePathIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its; /* @@ -25,41 +43,27 @@ /** * */ -public class Junit5ModulePathIT - extends AbstractJava9PlusIT -{ +public class Junit5ModulePathIT extends AbstractJava9PlusIT { private String suffix; @Test - public void testModulePath() - { - assumeJava9() - .debugLogging() - .executeTest() - .verifyErrorFreeLog() - .assertTestSuiteResults( 2 ); + public void testModulePath() { + assumeJava9().debugLogging().executeTest().verifyErrorFreeLog().assertTestSuiteResults(2); } @Test - public void testModulePathWithSpaces() - { + public void testModulePathWithSpaces() { suffix = " with spaces"; - assumeJava9() - .debugLogging() - .executeTest() - .verifyErrorFreeLog() - .assertTestSuiteResults( 2 ); + assumeJava9().debugLogging().executeTest().verifyErrorFreeLog().assertTestSuiteResults(2); } @Override - protected String getProjectDirectoryName() - { + protected String getProjectDirectoryName() { return "junit5-modulepath"; } @Override - protected String getSuffix() - { + protected String getSuffix() { return suffix; } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/LongWindowsPathIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/LongWindowsPathIT.java index 362128740c..2cb561cd13 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/LongWindowsPathIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/LongWindowsPathIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its; /* @@ -19,13 +37,13 @@ * under the License. */ +import java.io.File; + import org.apache.maven.surefire.its.fixture.OutputValidator; import org.apache.maven.surefire.its.fixture.SurefireJUnit4IntegrationTestCase; import org.apache.maven.surefire.its.fixture.SurefireLauncher; import org.junit.Test; -import java.io.File; - import static org.apache.commons.lang3.SystemUtils.IS_OS_WINDOWS; import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.CoreMatchers.containsString; @@ -40,44 +58,33 @@ * @author Tibor Digana (tibor17) * @since 2.20.1 */ -public class LongWindowsPathIT - extends SurefireJUnit4IntegrationTestCase -{ +public class LongWindowsPathIT extends SurefireJUnit4IntegrationTestCase { private static final String PROJECT_DIR = "long-windows-path"; @Test - public void shouldRunInSystemTmp() throws Exception - { - assumeTrue( IS_OS_WINDOWS ); + public void shouldRunInSystemTmp() throws Exception { + assumeTrue(IS_OS_WINDOWS); - OutputValidator validator = unpack().setForkJvm() - .showErrorStackTraces() - .executeTest() - .verifyErrorFreeLog(); + OutputValidator validator = + unpack().setForkJvm().showErrorStackTraces().executeTest().verifyErrorFreeLog(); - validator.assertThatLogLine( containsString( "SUREFIRE-1400 user.dir=" ), is( 1 ) ) - .assertThatLogLine( containsString( "SUREFIRE-1400 surefire.real.class.path=" ), is( 1 ) ); + validator + .assertThatLogLine(containsString("SUREFIRE-1400 user.dir="), is(1)) + .assertThatLogLine(containsString("SUREFIRE-1400 surefire.real.class.path="), is(1)); - for ( String line : validator.loadLogLines() ) - { - if ( line.contains( "SUREFIRE-1400 user.dir=" ) ) - { - File buildDir = new File( System.getProperty( "user.dir" ), "target" ); - File itBaseDir = new File( buildDir, "LongWindowsPathIT_shouldRunInSystemTmp" ); + for (String line : validator.loadLogLines()) { + if (line.contains("SUREFIRE-1400 user.dir=")) { + File buildDir = new File(System.getProperty("user.dir"), "target"); + File itBaseDir = new File(buildDir, "LongWindowsPathIT_shouldRunInSystemTmp"); - assertThat( line ) - .contains( itBaseDir.getAbsolutePath() ); - } - else if ( line.contains( "SUREFIRE-1400 surefire.real.class.path=" ) ) - { - assertThat( line ) - .contains( new File( System.getProperty( "java.io.tmpdir" ) ).getCanonicalPath() ); + assertThat(line).contains(itBaseDir.getAbsolutePath()); + } else if (line.contains("SUREFIRE-1400 surefire.real.class.path=")) { + assertThat(line).contains(new File(System.getProperty("java.io.tmpdir")).getCanonicalPath()); } } } - private SurefireLauncher unpack() - { - return unpack( PROJECT_DIR ); + private SurefireLauncher unpack() { + return unpack(PROJECT_DIR); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/ModulePathIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/ModulePathIT.java index 92d6431492..46e90d1d3a 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/ModulePathIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/ModulePathIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its; /* @@ -25,41 +43,27 @@ /** * */ -public class ModulePathIT - extends AbstractJava9PlusIT -{ +public class ModulePathIT extends AbstractJava9PlusIT { private String suffix; @Test - public void testModulePath() - { - assumeJava9() - .debugLogging() - .executeTest() - .verifyErrorFreeLog() - .assertTestSuiteResults( 2 ); + public void testModulePath() { + assumeJava9().debugLogging().executeTest().verifyErrorFreeLog().assertTestSuiteResults(2); } @Test - public void testModulePathWithSpaces() - { + public void testModulePathWithSpaces() { suffix = " with spaces"; - assumeJava9() - .debugLogging() - .executeTest() - .verifyErrorFreeLog() - .assertTestSuiteResults( 2 ); + assumeJava9().debugLogging().executeTest().verifyErrorFreeLog().assertTestSuiteResults(2); } @Override - protected String getProjectDirectoryName() - { + protected String getProjectDirectoryName() { return "modulepath"; } @Override - protected String getSuffix() - { + protected String getSuffix() { return suffix; } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/MultiModuleProjectWithJPMSIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/MultiModuleProjectWithJPMSIT.java index b5d780603b..36e6fe9253 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/MultiModuleProjectWithJPMSIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/MultiModuleProjectWithJPMSIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its; /* @@ -19,13 +37,13 @@ * under the License. */ +import java.util.List; + import org.apache.maven.it.VerificationException; import org.apache.maven.surefire.its.fixture.AbstractJava9PlusIT; import org.apache.maven.surefire.its.fixture.OutputValidator; import org.junit.Test; -import java.util.List; - import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.is; @@ -33,40 +51,35 @@ /** * Integration test for SUREFIRE-1733. */ -public class MultiModuleProjectWithJPMSIT extends AbstractJava9PlusIT -{ +public class MultiModuleProjectWithJPMSIT extends AbstractJava9PlusIT { @Test - public void test() throws VerificationException - { + public void test() throws VerificationException { OutputValidator validator = assumeJava9() - .debugLogging() - .executeVerify() - .verifyErrorFreeLog() - .assertThatLogLine( containsString( "Lets see JDKModulePath" ), is( 2 ) ) - .assertThatLogLine( containsString( "Lets see JDKModulePath: null" ), is( 0 ) ); + .debugLogging() + .executeVerify() + .verifyErrorFreeLog() + .assertThatLogLine(containsString("Lets see JDKModulePath"), is(2)) + .assertThatLogLine(containsString("Lets see JDKModulePath: null"), is(0)); - List lines = validator.loadLogLines( containsString( "Lets see JDKModulePath" ) ); + List lines = validator.loadLogLines(containsString("Lets see JDKModulePath")); int i = 0; - for ( String line : lines ) - { - assertThat( line ) - .contains( "com.foo.api" ) - .contains( "junit-jupiter-api" ) - .contains( "junit-jupiter-engine" ) - .contains( "slf4j-simple" ) - .contains( "slf4j-api" ) - .contains( "jakarta.xml.bind-api" ) - .contains( "jakarta.ws.rs-api" ) - .contains( "jakarta.persistence-api" ); + for (String line : lines) { + assertThat(line) + .contains("com.foo.api") + .contains("junit-jupiter-api") + .contains("junit-jupiter-engine") + .contains("slf4j-simple") + .contains("slf4j-api") + .contains("jakarta.xml.bind-api") + .contains("jakarta.ws.rs-api") + .contains("jakarta.persistence-api"); - assertThat( line ) - .contains( i++ == 0 ? "test-classes" : "com.foo.impl" ); + assertThat(line).contains(i++ == 0 ? "test-classes" : "com.foo.impl"); } } @Override - protected String getProjectDirectoryName() - { + protected String getProjectDirectoryName() { return "maven-multimodule-project-with-jpms"; } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/NoRunnableTestsInClassIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/NoRunnableTestsInClassIT.java index 1be88b7319..d1c1ea40c1 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/NoRunnableTestsInClassIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/NoRunnableTestsInClassIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its; /* @@ -27,13 +45,12 @@ * * @author Kristian Rosenvold */ -public class NoRunnableTestsInClassIT - extends SurefireJUnit4IntegrationTestCase -{ +public class NoRunnableTestsInClassIT extends SurefireJUnit4IntegrationTestCase { @Test - public void testJunit3ParallelBuildResultCount() - { - unpack( "norunnableTests" ).failNever().executeTest().verifyTextInLog( - "No tests found in junit.norunnabletests.BasicTest" ); + public void testJunit3ParallelBuildResultCount() { + unpack("norunnableTests") + .failNever() + .executeTest() + .verifyTextInLog("No tests found in junit.norunnabletests.BasicTest"); } -} \ No newline at end of file +} diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/PlainOldJavaClasspathIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/PlainOldJavaClasspathIT.java index 71bccd62c8..5170285b98 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/PlainOldJavaClasspathIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/PlainOldJavaClasspathIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its; /* @@ -27,12 +45,9 @@ * * @author Dan Fabulich */ -public class PlainOldJavaClasspathIT - extends SurefireJUnit4IntegrationTestCase -{ +public class PlainOldJavaClasspathIT extends SurefireJUnit4IntegrationTestCase { @Test - public void testPlainOldJavaClasspath() - { - executeErrorFreeTest( "plain-old-java-classpath", 1 ); + public void testPlainOldJavaClasspath() { + executeErrorFreeTest("plain-old-java-classpath", 1); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/PlexusConflictIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/PlexusConflictIT.java index 1df2e7eeb3..05c6806313 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/PlexusConflictIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/PlexusConflictIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its; /* @@ -28,23 +46,18 @@ * * @author Dan Fabulich */ -public class PlexusConflictIT - extends SurefireJUnit4IntegrationTestCase -{ +public class PlexusConflictIT extends SurefireJUnit4IntegrationTestCase { @Test - public void testPlexusConflict() - { - unpack().executeTest().verifyErrorFree( 1 ); + public void testPlexusConflict() { + unpack().executeTest().verifyErrorFree(1); } @Test - public void testPlexusConflictIsolatedClassLoader() - { - unpack().useSystemClassLoader( false ).executeTest().verifyErrorFree( 1 ); + public void testPlexusConflictIsolatedClassLoader() { + unpack().useSystemClassLoader(false).executeTest().verifyErrorFree(1); } - private SurefireLauncher unpack() - { - return unpack( "/plexus-conflict" ); + private SurefireLauncher unpack() { + return unpack("/plexus-conflict"); } -} \ No newline at end of file +} diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/PojoSimpleIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/PojoSimpleIT.java index 6905730903..16f1b803e7 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/PojoSimpleIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/PojoSimpleIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its; /* @@ -31,18 +49,15 @@ * * @author Benjamin Bentmann */ -public class PojoSimpleIT - extends SurefireJUnit4IntegrationTestCase -{ +public class PojoSimpleIT extends SurefireJUnit4IntegrationTestCase { @Test - public void twoTestsWithFixtures() throws VerificationException - { - unpack( "pojo-simple" ) + public void twoTestsWithFixtures() throws VerificationException { + unpack("pojo-simple") .executeTest() - .assertTestSuiteResults( 2, 0, 1, 0 ) - .assertThatLogLine( containsString( "setUp called 1" ), is( 1 ) ) - .assertThatLogLine( containsString( "setUp called 2" ), is( 1 ) ) - .assertThatLogLine( containsString( "tearDown called 1" ), is( 1 ) ) - .assertThatLogLine( containsString( "tearDown called 2" ), is( 1 ) ); + .assertTestSuiteResults(2, 0, 1, 0) + .assertThatLogLine(containsString("setUp called 1"), is(1)) + .assertThatLogLine(containsString("setUp called 2"), is(1)) + .assertThatLogLine(containsString("tearDown called 1"), is(1)) + .assertThatLogLine(containsString("tearDown called 2"), is(1)); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/ReportersIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/ReportersIT.java index b1c68f05b9..287778eb5e 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/ReportersIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/ReportersIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its; /* @@ -29,17 +47,14 @@ * * @author Kristian Rosenvold */ -public class ReportersIT - extends SurefireJUnit4IntegrationTestCase -{ +public class ReportersIT extends SurefireJUnit4IntegrationTestCase { @Test - public void testRedirectOutputTestNg() - { - OutputValidator reporters = unpack( "reporters" ).redirectToFile( true ).printSummary( true ).executeTest(); + public void testRedirectOutputTestNg() { + OutputValidator reporters = + unpack("reporters").redirectToFile(true).printSummary(true).executeTest(); - reporters.getSurefireReportsFile( "TestSuite-output.txt" ).assertFileExists(); - reporters.getSurefireReportsXmlFile( "TEST-TestSuite.xml" ).assertFileExists(); - reporters.getSurefireReportsFile( "TestSuite.txt" ).assertFileExists(); + reporters.getSurefireReportsFile("TestSuite-output.txt").assertFileExists(); + reporters.getSurefireReportsXmlFile("TEST-TestSuite.xml").assertFileExists(); + reporters.getSurefireReportsFile("TestSuite.txt").assertFileExists(); } } - diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/ResultCountingIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/ResultCountingIT.java index 7f4a53fdd7..6f135df328 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/ResultCountingIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/ResultCountingIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its; /* @@ -29,33 +47,30 @@ * * @author Kristian Rosenvold */ -@SuppressWarnings( "checkstyle:magicnumber" ) -public class ResultCountingIT - extends SurefireJUnit4IntegrationTestCase -{ +@SuppressWarnings("checkstyle:magicnumber") +public class ResultCountingIT extends SurefireJUnit4IntegrationTestCase { @Test - public void testCountingWithJunit481ForkNever() - { - assertForkCount( 0, true ); + public void testCountingWithJunit481ForkNever() { + assertForkCount(0, true); } @Test - public void testCountingWithJunit481ForkOnce() - { - assertForkCount( 1, true ); + public void testCountingWithJunit481ForkOnce() { + assertForkCount(1, true); } @Test - public void testCountingWithJunit481ForkAlways() - { - assertForkCount( 1, false ); + public void testCountingWithJunit481ForkAlways() { + assertForkCount(1, false); } - private void assertForkCount( int forkCount, boolean reuseForks ) - { - OutputValidator outputValidator = unpack( "result-counting" ).failNever().forkCount( forkCount ) - .reuseForks( reuseForks ).executeTest(); - outputValidator.assertTestSuiteResults( 36, 23, 4, 2 ); - outputValidator.verifyTextInLog( "Tests run: 36, Failures: 4, Errors: 23, Skipped: 2" ); + private void assertForkCount(int forkCount, boolean reuseForks) { + OutputValidator outputValidator = unpack("result-counting") + .failNever() + .forkCount(forkCount) + .reuseForks(reuseForks) + .executeTest(); + outputValidator.assertTestSuiteResults(36, 23, 4, 2); + outputValidator.verifyTextInLog("Tests run: 36, Failures: 4, Errors: 23, Skipped: 2"); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/RunOrderIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/RunOrderIT.java index acb5096f86..119180ecdd 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/RunOrderIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/RunOrderIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its; /* @@ -21,6 +39,7 @@ import java.util.Arrays; import java.util.Calendar; + import org.apache.maven.it.VerificationException; import org.apache.maven.surefire.its.fixture.OutputValidator; import org.apache.maven.surefire.its.fixture.SurefireJUnit4IntegrationTestCase; @@ -32,211 +51,169 @@ * * @author Kristian Rosenvold */ -@SuppressWarnings( "checkstyle:magicnumber" ) -public class RunOrderIT - extends SurefireJUnit4IntegrationTestCase -{ - private static final String[] TESTS_IN_ALPHABETICAL_ORDER = { "TA", "TB", "TC" }; +@SuppressWarnings("checkstyle:magicnumber") +public class RunOrderIT extends SurefireJUnit4IntegrationTestCase { + private static final String[] TESTS_IN_ALPHABETICAL_ORDER = {"TA", "TB", "TC"}; - private static final String[] TESTS_IN_REVERSE_ALPHABETICAL_ORDER = { "TC", "TB", "TA" }; + private static final String[] TESTS_IN_REVERSE_ALPHABETICAL_ORDER = {"TC", "TB", "TA"}; // testing random is left as an exercise to the reader. Patches welcome @Test - public void testAlphabeticalJUnit4() - throws VerificationException - { - OutputValidator validator = executeWithRunOrder( "alphabetical", "junit4" ); - assertTestnamesAppearInSpecificOrder( validator, TESTS_IN_ALPHABETICAL_ORDER ); + public void testAlphabeticalJUnit4() throws VerificationException { + OutputValidator validator = executeWithRunOrder("alphabetical", "junit4"); + assertTestnamesAppearInSpecificOrder(validator, TESTS_IN_ALPHABETICAL_ORDER); } @Test - public void testAlphabeticalJUnit5() - throws VerificationException - { - OutputValidator validator = executeWithRunOrder( "alphabetical", "junit5" ); - assertTestnamesAppearInSpecificOrder( validator, TESTS_IN_ALPHABETICAL_ORDER ); + public void testAlphabeticalJUnit5() throws VerificationException { + OutputValidator validator = executeWithRunOrder("alphabetical", "junit5"); + assertTestnamesAppearInSpecificOrder(validator, TESTS_IN_ALPHABETICAL_ORDER); } @Test - public void testRandomJUnit4DifferentSeed() - throws VerificationException - { + public void testRandomJUnit4DifferentSeed() throws VerificationException { long seed = 0L; - OutputValidator validator = executeWithRandomOrder( "junit4", seed ); - String[] expected = validator.getStringsOrderInLog( TESTS_IN_ALPHABETICAL_ORDER ); - for ( long i = seed; i < 5 + seed; i++ ) - { - OutputValidator validator2 = executeWithRandomOrder( "junit4", i ); - String[] observed = validator2.getStringsOrderInLog( TESTS_IN_ALPHABETICAL_ORDER ); - if ( ! Arrays.equals( expected, observed ) ) - { + OutputValidator validator = executeWithRandomOrder("junit4", seed); + String[] expected = validator.getStringsOrderInLog(TESTS_IN_ALPHABETICAL_ORDER); + for (long i = seed; i < 5 + seed; i++) { + OutputValidator validator2 = executeWithRandomOrder("junit4", i); + String[] observed = validator2.getStringsOrderInLog(TESTS_IN_ALPHABETICAL_ORDER); + if (!Arrays.equals(expected, observed)) { return; } } - throw new VerificationException( "All random orders with the different seeds produced the same orders" ); + throw new VerificationException("All random orders with the different seeds produced the same orders"); } @Test - public void testRandomJUnit4SameSeed() - throws VerificationException - { + public void testRandomJUnit4SameSeed() throws VerificationException { long seed = 0L; - OutputValidator validator = executeWithRandomOrder( "junit4", seed ); - String[] expected = validator.getStringsOrderInLog( TESTS_IN_ALPHABETICAL_ORDER ); - for ( long i = 0; i < 5; i++ ) - { - OutputValidator validator2 = executeWithRandomOrder( "junit4", seed ); - String[] observed = validator2.getStringsOrderInLog( TESTS_IN_ALPHABETICAL_ORDER ); - if ( ! Arrays.equals( expected, observed ) ) - { - throw new VerificationException( "Random orders with the same seed produced different orders" ); + OutputValidator validator = executeWithRandomOrder("junit4", seed); + String[] expected = validator.getStringsOrderInLog(TESTS_IN_ALPHABETICAL_ORDER); + for (long i = 0; i < 5; i++) { + OutputValidator validator2 = executeWithRandomOrder("junit4", seed); + String[] observed = validator2.getStringsOrderInLog(TESTS_IN_ALPHABETICAL_ORDER); + if (!Arrays.equals(expected, observed)) { + throw new VerificationException("Random orders with the same seed produced different orders"); } } } @Test - public void testRandomJUnit4PrintSeedWithGivenSeed() - { - OutputValidator validator = executeWithRandomOrder( "junit4", 0L ); - validator.verifyTextInLog( "To reproduce ordering use flag" ); + public void testRandomJUnit4PrintSeedWithGivenSeed() { + OutputValidator validator = executeWithRandomOrder("junit4", 0L); + validator.verifyTextInLog("To reproduce ordering use flag"); } @Test - public void testRandomJUnit4PrintSeedWithNoGivenSeed() - { - OutputValidator validator = executeWithRandomOrder( "junit4" ); - validator.verifyTextInLog( "To reproduce ordering use flag" ); + public void testRandomJUnit4PrintSeedWithNoGivenSeed() { + OutputValidator validator = executeWithRandomOrder("junit4"); + validator.verifyTextInLog("To reproduce ordering use flag"); } @Test - public void testReverseAlphabeticalJUnit4() - throws VerificationException - { - OutputValidator validator = executeWithRunOrder( "reversealphabetical", "junit4" ); - assertTestnamesAppearInSpecificOrder( validator, TESTS_IN_REVERSE_ALPHABETICAL_ORDER ); + public void testReverseAlphabeticalJUnit4() throws VerificationException { + OutputValidator validator = executeWithRunOrder("reversealphabetical", "junit4"); + assertTestnamesAppearInSpecificOrder(validator, TESTS_IN_REVERSE_ALPHABETICAL_ORDER); } @Test - public void testReverseAlphabeticalJUnit5() - throws VerificationException - { - OutputValidator validator = executeWithRunOrder( "reversealphabetical", "junit5" ); - assertTestnamesAppearInSpecificOrder( validator, TESTS_IN_REVERSE_ALPHABETICAL_ORDER ); + public void testReverseAlphabeticalJUnit5() throws VerificationException { + OutputValidator validator = executeWithRunOrder("reversealphabetical", "junit5"); + assertTestnamesAppearInSpecificOrder(validator, TESTS_IN_REVERSE_ALPHABETICAL_ORDER); } @Test - public void testHourlyJUnit4() - throws VerificationException - { - int startHour = Calendar.getInstance().get( Calendar.HOUR_OF_DAY ); - OutputValidator validator = executeWithRunOrder( "hourly", "junit4" ); - int endHour = Calendar.getInstance().get( Calendar.HOUR_OF_DAY ); - if ( startHour != endHour ) - { + public void testHourlyJUnit4() throws VerificationException { + int startHour = Calendar.getInstance().get(Calendar.HOUR_OF_DAY); + OutputValidator validator = executeWithRunOrder("hourly", "junit4"); + int endHour = Calendar.getInstance().get(Calendar.HOUR_OF_DAY); + if (startHour != endHour) { return; // Race condition, cannot test when hour changed mid-run } - String[] testnames = - ( ( startHour % 2 ) == 0 ) ? TESTS_IN_ALPHABETICAL_ORDER : TESTS_IN_REVERSE_ALPHABETICAL_ORDER; - assertTestnamesAppearInSpecificOrder( validator, testnames ); + String[] testnames = ((startHour % 2) == 0) ? TESTS_IN_ALPHABETICAL_ORDER : TESTS_IN_REVERSE_ALPHABETICAL_ORDER; + assertTestnamesAppearInSpecificOrder(validator, testnames); } @Test - public void testHourlyJUnit5() - throws VerificationException - { - int startHour = Calendar.getInstance().get( Calendar.HOUR_OF_DAY ); - OutputValidator validator = executeWithRunOrder( "hourly", "junit5" ); - int endHour = Calendar.getInstance().get( Calendar.HOUR_OF_DAY ); - if ( startHour != endHour ) - { + public void testHourlyJUnit5() throws VerificationException { + int startHour = Calendar.getInstance().get(Calendar.HOUR_OF_DAY); + OutputValidator validator = executeWithRunOrder("hourly", "junit5"); + int endHour = Calendar.getInstance().get(Calendar.HOUR_OF_DAY); + if (startHour != endHour) { return; // Race condition, cannot test when hour changed mid-run } - String[] testnames = - ( ( startHour % 2 ) == 0 ) ? TESTS_IN_ALPHABETICAL_ORDER : TESTS_IN_REVERSE_ALPHABETICAL_ORDER; - assertTestnamesAppearInSpecificOrder( validator, testnames ); + String[] testnames = ((startHour % 2) == 0) ? TESTS_IN_ALPHABETICAL_ORDER : TESTS_IN_REVERSE_ALPHABETICAL_ORDER; + assertTestnamesAppearInSpecificOrder(validator, testnames); } @Test - public void testNonExistingRunOrderJUnit4() - { - unpack() - .activateProfile( "junit4" ) - .forkCount( 1 ) - .reuseForks( reuseForks() ) - .runOrder( "nonExistingRunOrder" ) - .maven() - .withFailure() - .executeTest() - .verifyTextInLog( "There's no RunOrder with the name nonExistingRunOrder." ); + public void testNonExistingRunOrderJUnit4() { + unpack().activateProfile("junit4") + .forkCount(1) + .reuseForks(reuseForks()) + .runOrder("nonExistingRunOrder") + .maven() + .withFailure() + .executeTest() + .verifyTextInLog("There's no RunOrder with the name nonExistingRunOrder."); } @Test - public void testNonExistingRunOrderJUnit5() - { - unpack() - .activateProfile( "junit5" ) - .forkCount( 1 ) - .reuseForks( reuseForks() ) - .runOrder( "nonExistingRunOrder" ) - .maven() - .withFailure() - .executeTest() - .verifyTextInLog( "There's no RunOrder with the name nonExistingRunOrder." ); - } - - private OutputValidator executeWithRunOrder( String runOrder, String profile ) - { - return unpack() - .activateProfile( profile ) - .forkCount( 1 ) - .reuseForks( reuseForks() ) - .runOrder( runOrder ) - .executeTest() - .verifyErrorFree( 3 ); - } - - private OutputValidator executeWithRandomOrder( String profile ) - { - return unpack() - .activateProfile( profile ) - .forkCount( 1 ) - .reuseForks( reuseForks() ) - .runOrder( "random" ) - .executeTest() - .verifyErrorFree( 3 ); - } - - private OutputValidator executeWithRandomOrder( String profile, long seed ) - { - return unpack() - .activateProfile( profile ) - .forkCount( 1 ) - .reuseForks( reuseForks() ) - .runOrder( "random" ) - .runOrderRandomSeed( String.valueOf( seed ) ) - .executeTest() - .verifyErrorFree( 3 ); - } - - protected boolean reuseForks() - { + public void testNonExistingRunOrderJUnit5() { + unpack().activateProfile("junit5") + .forkCount(1) + .reuseForks(reuseForks()) + .runOrder("nonExistingRunOrder") + .maven() + .withFailure() + .executeTest() + .verifyTextInLog("There's no RunOrder with the name nonExistingRunOrder."); + } + + private OutputValidator executeWithRunOrder(String runOrder, String profile) { + return unpack().activateProfile(profile) + .forkCount(1) + .reuseForks(reuseForks()) + .runOrder(runOrder) + .executeTest() + .verifyErrorFree(3); + } + + private OutputValidator executeWithRandomOrder(String profile) { + return unpack().activateProfile(profile) + .forkCount(1) + .reuseForks(reuseForks()) + .runOrder("random") + .executeTest() + .verifyErrorFree(3); + } + + private OutputValidator executeWithRandomOrder(String profile, long seed) { + return unpack().activateProfile(profile) + .forkCount(1) + .reuseForks(reuseForks()) + .runOrder("random") + .runOrderRandomSeed(String.valueOf(seed)) + .executeTest() + .verifyErrorFree(3); + } + + protected boolean reuseForks() { return true; } - private SurefireLauncher unpack() - { - return unpack( "runOrder" ); + private SurefireLauncher unpack() { + return unpack("runOrder"); } - private void assertTestnamesAppearInSpecificOrder( OutputValidator validator, String[] testnames ) - throws VerificationException - { - if ( !validator.stringsAppearInSpecificOrderInLog( testnames ) ) - { - throw new VerificationException( "Response does not contain expected item" ); + private void assertTestnamesAppearInSpecificOrder(OutputValidator validator, String[] testnames) + throws VerificationException { + if (!validator.stringsAppearInSpecificOrderInLog(testnames)) { + throw new VerificationException("Response does not contain expected item"); } } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/RunOrderParallelForksIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/RunOrderParallelForksIT.java index fa0292a31b..a397f38c4d 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/RunOrderParallelForksIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/RunOrderParallelForksIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its; /* @@ -22,13 +40,10 @@ /** * */ -public class RunOrderParallelForksIT - extends RunOrderIT -{ +public class RunOrderParallelForksIT extends RunOrderIT { @Override - protected boolean reuseForks() - { + protected boolean reuseForks() { return false; } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/SiblingAggregatorIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/SiblingAggregatorIT.java index 69c9e4c157..373c9c8c9a 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/SiblingAggregatorIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/SiblingAggregatorIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its; /* @@ -30,18 +48,14 @@ * @author Dan Fabulich * @author Kristian Rosenvold */ -public class SiblingAggregatorIT - extends SurefireJUnit4IntegrationTestCase -{ +public class SiblingAggregatorIT extends SurefireJUnit4IntegrationTestCase { @Test - public void testSiblingAggregator() - throws Exception - { - final SurefireLauncher unpack = unpack( "sibling-aggregator" ); - SurefireLauncher aggregator = unpack.getSubProjectLauncher( "aggregator" ); + public void testSiblingAggregator() throws Exception { + final SurefireLauncher unpack = unpack("sibling-aggregator"); + SurefireLauncher aggregator = unpack.getSubProjectLauncher("aggregator"); aggregator.executeTest().verifyErrorFreeLog(); - OutputValidator child2 = unpack.getSubProjectValidator( "child2" ); - child2.assertTestSuiteResults( 1, 0, 0, 0 ); + OutputValidator child2 = unpack.getSubProjectValidator("child2"); + child2.assertTestSuiteResults(1, 0, 0, 0); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/SmartStackTraceIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/SmartStackTraceIT.java index ee9da9a663..06b701bf1a 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/SmartStackTraceIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/SmartStackTraceIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its; /* @@ -28,18 +46,14 @@ * * @author Kristian Rosenvold */ -public class SmartStackTraceIT - extends SurefireJUnit4IntegrationTestCase -{ +public class SmartStackTraceIT extends SurefireJUnit4IntegrationTestCase { @Test - public void misg() - { - OutputValidator outputValidator = unpack( "/junit48-smartStackTrace" ).maven().withFailure().executeTest(); + public void misg() { + OutputValidator outputValidator = + unpack("/junit48-smartStackTrace").maven().withFailure().executeTest(); outputValidator.verifyTextInLog( - "SmartStackTraceTest.shouldFailInMethodButDoesnt Expected exception: java.lang.RuntimeException" ); - outputValidator.verifyTextInLog( - "SmartStackTraceTest.shortName Expected exception: java.io.IOException" ); - + "SmartStackTraceTest.shouldFailInMethodButDoesnt Expected exception: java.lang.RuntimeException"); + outputValidator.verifyTextInLog("SmartStackTraceTest.shortName Expected exception: java.io.IOException"); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/Surefire1602IT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/Surefire1602IT.java index 5438d2311e..fb4f97715f 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/Surefire1602IT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/Surefire1602IT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its; /* @@ -29,18 +47,12 @@ * * @author Enrico Olivelli */ -public class Surefire1602IT - extends SurefireJUnit4IntegrationTestCase -{ +public class Surefire1602IT extends SurefireJUnit4IntegrationTestCase { @Test - public void nonCanonicalPath() throws VerificationException - { - SurefireLauncher launcher = unpack( "/surefire-1602" ); + public void nonCanonicalPath() throws VerificationException { + SurefireLauncher launcher = unpack("/surefire-1602"); launcher.executeInstall(); - launcher.addGoal( "--file" ) - .addGoal( "./integration-tests/pom.xml" ) - .executeTest(); - launcher.getSubProjectValidator( "integration-tests" ) - .assertTestSuiteResults( 1, 0, 0, 0 ); + launcher.addGoal("--file").addGoal("./integration-tests/pom.xml").executeTest(); + launcher.getSubProjectValidator("integration-tests").assertTestSuiteResults(1, 0, 0, 0); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/SystemPropertiesTestIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/SystemPropertiesTestIT.java index 121b8fcac6..d22cf0b4ac 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/SystemPropertiesTestIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/SystemPropertiesTestIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its; /* @@ -28,28 +46,29 @@ * * @author Dan Fabulich */ -public class SystemPropertiesTestIT - extends SurefireJUnit4IntegrationTestCase -{ +public class SystemPropertiesTestIT extends SurefireJUnit4IntegrationTestCase { @Test - public void testSystemProperties() - { - unpack().addGoal( "-DsetOnMavenCommandLine=baz" ).addGoal( - "-DsetOnArgLineWorkAround=baz" ).executeTest().verifyErrorFree( 8 ); + public void testSystemProperties() { + unpack().addGoal("-DsetOnMavenCommandLine=baz") + .addGoal("-DsetOnArgLineWorkAround=baz") + .executeTest() + .verifyErrorFree(8); } @Test - public void testSystemPropertiesNoFork() - { + public void testSystemPropertiesNoFork() { - unpack().forkNever().addGoal( "-DsetOnMavenCommandLine=baz" ).addGoal( "-DsetOnArgLineWorkAround=baz" ) - // DGF fake the argLine, since we're not forking - .addGoal( "-DsetOnArgLine=bar" ).executeTest().verifyErrorFree( 8 ); + unpack().forkNever() + .addGoal("-DsetOnMavenCommandLine=baz") + .addGoal("-DsetOnArgLineWorkAround=baz") + // DGF fake the argLine, since we're not forking + .addGoal("-DsetOnArgLine=bar") + .executeTest() + .verifyErrorFree(8); } - public SurefireLauncher unpack() - { - return unpack( "/system-properties" ); + public SurefireLauncher unpack() { + return unpack("/system-properties"); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/TestMethodPatternIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/TestMethodPatternIT.java index 124422f8e2..5b85e12af0 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/TestMethodPatternIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/TestMethodPatternIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its; /* @@ -42,140 +60,112 @@ * * @author Olivier Lamy */ -@RunWith( Parameterized.class ) -public class TestMethodPatternIT - extends SurefireJUnit4IntegrationTestCase -{ +@RunWith(Parameterized.class) +public class TestMethodPatternIT extends SurefireJUnit4IntegrationTestCase { private static final String RUNNING_WITH_PROVIDER47 = "parallel='none', perCoreThreadCount=true, threadCount=0"; - private static final String LEGACY_FORK_NODE = - "org.apache.maven.plugin.surefire.extensions.LegacyForkNodeFactory"; + private static final String LEGACY_FORK_NODE = "org.apache.maven.plugin.surefire.extensions.LegacyForkNodeFactory"; private static final String SUREFIRE_FORK_NODE = - "org.apache.maven.plugin.surefire.extensions.SurefireForkNodeFactory"; + "org.apache.maven.plugin.surefire.extensions.SurefireForkNodeFactory"; @Parameters - public static Iterable data() - { + public static Iterable data() { ArrayList args = new ArrayList<>(); - args.add( new Object[] { "tcp" } ); - args.add( new Object[] { null } ); + args.add(new Object[] {"tcp"}); + args.add(new Object[] {null}); return args; } @Parameter - @SuppressWarnings( "checkstyle:visibilitymodifier" ) + @SuppressWarnings("checkstyle:visibilitymodifier") public String profileId; - private OutputValidator runMethodPattern( String projectName, Map props, String... goals ) - throws Exception - { - SurefireLauncher launcher = unpack( projectName, profileId == null ? "" : "-" + profileId ); + private OutputValidator runMethodPattern(String projectName, Map props, String... goals) + throws Exception { + SurefireLauncher launcher = unpack(projectName, profileId == null ? "" : "-" + profileId); - if ( profileId != null ) - { - launcher.activateProfile( profileId ); + if (profileId != null) { + launcher.activateProfile(profileId); } - for ( Entry entry : props.entrySet() ) - { - launcher.sysProp( entry.getKey(), entry.getValue() ); + for (Entry entry : props.entrySet()) { + launcher.sysProp(entry.getKey(), entry.getValue()); } - for ( String goal : goals ) - { - launcher.addGoal( goal ); + for (String goal : goals) { + launcher.addGoal(goal); } String cls = profileId == null ? LEGACY_FORK_NODE : SUREFIRE_FORK_NODE; - return launcher.showErrorStackTraces().debugLogging() - .executeTest() - .assertTestSuiteResults( 2, 0, 0, 0 ) - .assertThatLogLine( - containsString( "Found implementation of fork node factory: " + cls ), - equalTo( 1 ) ); + return launcher.showErrorStackTraces() + .debugLogging() + .executeTest() + .assertTestSuiteResults(2, 0, 0, 0) + .assertThatLogLine(containsString("Found implementation of fork node factory: " + cls), equalTo(1)); } @Test - public void testJUnit44() - throws Exception - { - runMethodPattern( "junit44-method-pattern", Collections.emptyMap() ); + public void testJUnit44() throws Exception { + runMethodPattern("junit44-method-pattern", Collections.emptyMap()); } @Test - public void testJUnit48Provider4() - throws Exception - { - runMethodPattern( "junit48-method-pattern", Collections.emptyMap(), "-P surefire-junit4" ); + public void testJUnit48Provider4() throws Exception { + runMethodPattern("junit48-method-pattern", Collections.emptyMap(), "-P surefire-junit4"); } @Test - public void testJUnit48Provider47() - throws Exception - { - runMethodPattern( "junit48-method-pattern", Collections.emptyMap(), "-P surefire-junit47" ) - .verifyTextInLog( RUNNING_WITH_PROVIDER47 ); + public void testJUnit48Provider47() throws Exception { + runMethodPattern("junit48-method-pattern", Collections.emptyMap(), "-P surefire-junit47") + .verifyTextInLog(RUNNING_WITH_PROVIDER47); } @Test - public void testJUnit48WithCategoryFilter() throws Exception - { + public void testJUnit48WithCategoryFilter() throws Exception { String cls = profileId == null ? LEGACY_FORK_NODE : SUREFIRE_FORK_NODE; - SurefireLauncher launcher = unpack( "junit48-method-pattern", profileId == null ? "" : "-" + profileId ); + SurefireLauncher launcher = unpack("junit48-method-pattern", profileId == null ? "" : "-" + profileId); - if ( profileId != null ) - { - launcher.activateProfile( profileId ); + if (profileId != null) { + launcher.activateProfile(profileId); } launcher.debugLogging() - .addGoal( "-Dgroups=junit4.SampleCategory" ) - .executeTest() - .assertTestSuiteResults( 1, 0, 0, 0 ) - .assertThatLogLine( - containsString( "Found implementation of fork node factory: " + cls ), - equalTo( 1 ) ); + .addGoal("-Dgroups=junit4.SampleCategory") + .executeTest() + .assertTestSuiteResults(1, 0, 0, 0) + .assertThatLogLine(containsString("Found implementation of fork node factory: " + cls), equalTo(1)); } @Test - public void testTestNgMethodBefore() - throws Exception - { + public void testTestNgMethodBefore() throws Exception { Map props = new HashMap<>(); - props.put( "testNgVersion", "5.7" ); - props.put( "testNgClassifier", "jdk15" ); - runMethodPattern( "testng-method-pattern-before", props ); + props.put("testNgVersion", "5.7"); + props.put("testNgClassifier", "jdk15"); + runMethodPattern("testng-method-pattern-before", props); } @Test - public void testTestNGMethodPattern() - throws Exception - { + public void testTestNGMethodPattern() throws Exception { Map props = new HashMap<>(); - props.put( "testNgVersion", "5.7" ); - props.put( "testNgClassifier", "jdk15" ); - runMethodPattern( "/testng-method-pattern", props ); + props.put("testNgVersion", "5.7"); + props.put("testNgClassifier", "jdk15"); + runMethodPattern("/testng-method-pattern", props); } @Test - public void testMethodPatternAfter() throws Exception - { + public void testMethodPatternAfter() throws Exception { String cls = profileId == null ? LEGACY_FORK_NODE : SUREFIRE_FORK_NODE; - SurefireLauncher launcher = unpack( "testng-method-pattern-after", profileId == null ? "" : "-" + profileId ); + SurefireLauncher launcher = unpack("testng-method-pattern-after", profileId == null ? "" : "-" + profileId); - if ( profileId != null ) - { - launcher.activateProfile( profileId ); + if (profileId != null) { + launcher.activateProfile(profileId); } launcher.debugLogging() - .sysProp( "testNgVersion", "5.7" ) - .sysProp( "testNgClassifier", "jdk15" ) + .sysProp("testNgVersion", "5.7") + .sysProp("testNgClassifier", "jdk15") .executeTest() - .verifyErrorFree( 2 ) - .verifyTextInLog( "Called tearDown" ) - .assertThatLogLine( - containsString( "Found implementation of fork node factory: " + cls ), - equalTo( 1 ) ); + .verifyErrorFree(2) + .verifyTextInLog("Called tearDown") + .assertThatLogLine(containsString("Found implementation of fork node factory: " + cls), equalTo(1)); } - } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/TestMultipleMethodPatternsIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/TestMultipleMethodPatternsIT.java index 4eea90bb79..6cc445c24d 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/TestMultipleMethodPatternsIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/TestMultipleMethodPatternsIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its; /* @@ -30,39 +48,33 @@ /** * JUnit test project using multiple method patterns, including wildcards in class and method names. */ -@RunWith( Parameterized.class ) -public class TestMultipleMethodPatternsIT - extends AbstractTestMultipleMethodPatterns -{ +@RunWith(Parameterized.class) +public class TestMultipleMethodPatternsIT extends AbstractTestMultipleMethodPatterns { private final Settings settings; - public TestMultipleMethodPatternsIT( Settings settings ) - { + public TestMultipleMethodPatternsIT(Settings settings) { this.settings = settings; } @Parameters - public static Iterable data() - { - return Arrays.asList( new Object[][]{ - { Settings.JUNIT4_TEST }, - { Settings.JUNIT47_TEST }, - { Settings.JUNIT4_INCLUDES }, - { Settings.JUNIT47_INCLUDES }, - { Settings.JUNIT4_INCLUDES_EXCLUDES }, - { Settings.JUNIT47_INCLUDES_EXCLUDES } - } ); + public static Iterable data() { + return Arrays.asList(new Object[][] { + {Settings.JUNIT4_TEST}, + {Settings.JUNIT47_TEST}, + {Settings.JUNIT4_INCLUDES}, + {Settings.JUNIT47_INCLUDES}, + {Settings.JUNIT4_INCLUDES_EXCLUDES}, + {Settings.JUNIT47_INCLUDES_EXCLUDES} + }); } @Override - protected Settings getSettings() - { + protected Settings getSettings() { return settings; } @Override - protected SurefireLauncher unpack() - { - return unpack( "junit48-multiple-method-patterns", "_" + settings.path() ); + protected SurefireLauncher unpack() { + return unpack("junit48-multiple-method-patterns", "_" + settings.path()); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/TestMultipleMethodPatternsTestNGIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/TestMultipleMethodPatternsTestNGIT.java index 7ae86e99fc..d6cacec830 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/TestMultipleMethodPatternsTestNGIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/TestMultipleMethodPatternsTestNGIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its; /* @@ -30,36 +48,28 @@ /** * TestNG test project using multiple method patterns, including wildcards in class and method names. */ -@RunWith( Parameterized.class ) -public class TestMultipleMethodPatternsTestNGIT - extends AbstractTestMultipleMethodPatterns -{ +@RunWith(Parameterized.class) +public class TestMultipleMethodPatternsTestNGIT extends AbstractTestMultipleMethodPatterns { private final Settings settings; - public TestMultipleMethodPatternsTestNGIT( Settings settings ) - { + public TestMultipleMethodPatternsTestNGIT(Settings settings) { this.settings = settings; } @Parameters - public static Iterable data() - { - return Arrays.asList( new Object[][]{ - { Settings.TestNG_TEST }, - { Settings.TestNG_INCLUDES }, - { Settings.TestNG_INCLUDES_EXCLUDES } - } ); + public static Iterable data() { + return Arrays.asList( + new Object[][] {{Settings.TestNG_TEST}, {Settings.TestNG_INCLUDES}, {Settings.TestNG_INCLUDES_EXCLUDES} + }); } @Override - protected Settings getSettings() - { + protected Settings getSettings() { return settings; } @Override - protected SurefireLauncher unpack() - { - return unpack( "testng-multiple-method-patterns", "_" + settings.path() ); + protected SurefireLauncher unpack() { + return unpack("testng-multiple-method-patterns", "_" + settings.path()); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/TestMultipleMethodsIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/TestMultipleMethodsIT.java index 65dc604fb6..8d118d35bd 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/TestMultipleMethodsIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/TestMultipleMethodsIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its; /* @@ -24,47 +42,39 @@ import org.apache.maven.surefire.its.fixture.SurefireLauncher; import org.junit.Test; - /** * Test project using -Dtest=mtClass#myMethod+myMethod2,secondClass#testMethod * * @author rainLee */ -public class TestMultipleMethodsIT - extends SurefireJUnit4IntegrationTestCase -{ +public class TestMultipleMethodsIT extends SurefireJUnit4IntegrationTestCase { private static final String RUNNING_WITH_PROVIDER47 = "parallel='none', perCoreThreadCount=true, threadCount=0"; - public OutputValidator multipleMethod( String projectName, String... goals ) - { - SurefireLauncher launcher = unpack( projectName ); - for ( String goal : goals ) - { - launcher.addGoal( goal ); + public OutputValidator multipleMethod(String projectName, String... goals) { + SurefireLauncher launcher = unpack(projectName); + for (String goal : goals) { + launcher.addGoal(goal); } - return launcher.showErrorStackTraces().debugLogging() - .executeTest() - .verifyErrorFreeLog().assertTestSuiteResults( 3, 0, 0, 0 ); + return launcher.showErrorStackTraces() + .debugLogging() + .executeTest() + .verifyErrorFreeLog() + .assertTestSuiteResults(3, 0, 0, 0); } @Test - public void testJunit44() - { - multipleMethod( "junit44-multiple-methods" ); + public void testJunit44() { + multipleMethod("junit44-multiple-methods"); } @Test - public void testJunit48Provider4() - { - multipleMethod( "junit48-multiple-methods", "-P surefire-junit4" ); + public void testJunit48Provider4() { + multipleMethod("junit48-multiple-methods", "-P surefire-junit4"); } @Test - public void testJunit48Provider47() - { - multipleMethod( "junit48-multiple-methods", "-P surefire-junit47" ) - .verifyTextInLog( RUNNING_WITH_PROVIDER47 ); + public void testJunit48Provider47() { + multipleMethod("junit48-multiple-methods", "-P surefire-junit47").verifyTextInLog(RUNNING_WITH_PROVIDER47); } - } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/TestNgGroupsIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/TestNgGroupsIT.java index 74771c8598..9635c1b46d 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/TestNgGroupsIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/TestNgGroupsIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its; /* @@ -21,49 +39,42 @@ import org.apache.maven.surefire.its.fixture.SurefireJUnit4IntegrationTestCase; import org.apache.maven.surefire.its.fixture.SurefireLauncher; - import org.junit.Test; /** * Test the group filter for TestNG * */ -public class TestNgGroupsIT - extends SurefireJUnit4IntegrationTestCase -{ +public class TestNgGroupsIT extends SurefireJUnit4IntegrationTestCase { @Test - public void testExclusion() - { - unpack().setExcludedGroups( "notincluded" ).executeTest().verifyErrorFree( 5 ); + public void testExclusion() { + unpack().setExcludedGroups("notincluded").executeTest().verifyErrorFree(5); } @Test - public void testOnlyGroups() - { - unpack().setGroups( "functional" ).executeTest().verifyErrorFree( 2 ); + public void testOnlyGroups() { + unpack().setGroups("functional").executeTest().verifyErrorFree(2); } @Test - public void testGroupsAndExclusion() - { - unpack().setGroups( "functional" ).setExcludedGroups( "notincluded" ).executeTest().verifyErrorFree( 1 ); + public void testGroupsAndExclusion() { + unpack().setGroups("functional") + .setExcludedGroups("notincluded") + .executeTest() + .verifyErrorFree(1); } @Test - public void groupsWithDash() - { - unpack().setGroups( "abc-def" ).executeTest().verifyErrorFree( 1 ); + public void groupsWithDash() { + unpack().setGroups("abc-def").executeTest().verifyErrorFree(1); } @Test - public void groupsBySimpleRegex() - { - unpack().setGroups( "foo\\..*" ).executeTest().verifyErrorFree( 2 ); + public void groupsBySimpleRegex() { + unpack().setGroups("foo\\..*").executeTest().verifyErrorFree(2); } - public SurefireLauncher unpack() - { - return unpack( "/testng-groups" ); + public SurefireLauncher unpack() { + return unpack("/testng-groups"); } - } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/TestNgParallelWithAnnotationsIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/TestNgParallelWithAnnotationsIT.java index 1e6044e283..fea707e514 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/TestNgParallelWithAnnotationsIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/TestNgParallelWithAnnotationsIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its; /* @@ -27,12 +45,9 @@ * * @author Haikal Saadh */ -public class TestNgParallelWithAnnotationsIT - extends SurefireJUnit4IntegrationTestCase -{ +public class TestNgParallelWithAnnotationsIT extends SurefireJUnit4IntegrationTestCase { @Test - public void testTestNgGroupThreadParallel() - { - executeErrorFreeTest( "/testng-parallel-with-annotations", 3 ); + public void testTestNgGroupThreadParallel() { + executeErrorFreeTest("/testng-parallel-with-annotations", 3); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/TestNgSuccessPercentageIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/TestNgSuccessPercentageIT.java index 1be72f4b07..8bf15a6b1a 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/TestNgSuccessPercentageIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/TestNgSuccessPercentageIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its; /* @@ -30,17 +48,14 @@ * @author Jon Todd * @author Andreas Gudian */ -public class TestNgSuccessPercentageIT extends SurefireJUnit4IntegrationTestCase -{ +public class TestNgSuccessPercentageIT extends SurefireJUnit4IntegrationTestCase { @Test - public void testPassesWhenFailuresLessThanSuccessPercentage() - { - OutputValidator validator = unpack( "/testng-succes-percentage" ) - .sysProp( "testNgVersion", "5.7" ) - .sysProp( "testNgClassifier", "jdk15" ) - .mavenTestFailureIgnore( true ) - .executeTest(); - validator.assertTestSuiteResults( 8, 0, 1, 0 ); + public void testPassesWhenFailuresLessThanSuccessPercentage() { + OutputValidator validator = unpack("/testng-succes-percentage") + .sysProp("testNgVersion", "5.7") + .sysProp("testNgClassifier", "jdk15") + .mavenTestFailureIgnore(true) + .executeTest(); + validator.assertTestSuiteResults(8, 0, 1, 0); } - -} \ No newline at end of file +} diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/TestSingleMethodIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/TestSingleMethodIT.java index a5d08cf6ec..2b60974302 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/TestSingleMethodIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/TestSingleMethodIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its; /* @@ -19,113 +37,101 @@ * under the License. */ +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; + import org.apache.maven.surefire.its.fixture.OutputValidator; import org.apache.maven.surefire.its.fixture.SurefireJUnit4IntegrationTestCase; import org.apache.maven.surefire.its.fixture.SurefireLauncher; import org.junit.Test; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; - /** * Test project using -Dtest=mtClass#myMethod * * @author Olivier Lamy */ -public class TestSingleMethodIT - extends SurefireJUnit4IntegrationTestCase -{ +public class TestSingleMethodIT extends SurefireJUnit4IntegrationTestCase { private static final String RUNNING_WITH_PROVIDER47 = "parallel='none', perCoreThreadCount=true, threadCount=0"; - public OutputValidator singleMethod( String projectName, Map props, String testToRun, - String... goals ) - { - SurefireLauncher launcher = unpack( projectName ); - for ( Map.Entry entry : props.entrySet() ) - { - launcher.sysProp( entry.getKey(), entry.getValue() ); + public OutputValidator singleMethod( + String projectName, Map props, String testToRun, String... goals) { + SurefireLauncher launcher = unpack(projectName); + for (Map.Entry entry : props.entrySet()) { + launcher.sysProp(entry.getKey(), entry.getValue()); } - for ( String goal : goals ) - { - launcher.addGoal( goal ); + for (String goal : goals) { + launcher.addGoal(goal); } launcher.showErrorStackTraces().debugLogging(); - if ( testToRun != null ) - { - launcher.setTestToRun( testToRun ); + if (testToRun != null) { + launcher.setTestToRun(testToRun); } - return launcher.executeTest() - .verifyErrorFreeLog() - .assertTestSuiteResults( 1, 0, 0, 0 ); + return launcher.executeTest().verifyErrorFreeLog().assertTestSuiteResults(1, 0, 0, 0); } @Test - public void testJunit44() - { - singleMethod( "junit44-single-method", Collections.emptyMap(), null ); + public void testJunit44() { + singleMethod("junit44-single-method", Collections.emptyMap(), null); } @Test - public void testJunit48Provider4() - { - singleMethod( "junit48-single-method", Collections.emptyMap(), null, "-P surefire-junit4" ); + public void testJunit48Provider4() { + singleMethod("junit48-single-method", Collections.emptyMap(), null, "-P surefire-junit4"); } @Test - public void testJunit48Provider47() - { - singleMethod( "junit48-single-method", Collections.emptyMap(), null, "-P surefire-junit47" ) - .verifyTextInLog( RUNNING_WITH_PROVIDER47 ); + public void testJunit48Provider47() { + singleMethod("junit48-single-method", Collections.emptyMap(), null, "-P surefire-junit47") + .verifyTextInLog(RUNNING_WITH_PROVIDER47); } @Test - public void testJunit48parallel() - { - unpack( "junit48-single-method" ) - .parallel( "all" ) - .useUnlimitedThreads() - .executeTest() - .verifyErrorFreeLog() - .assertTestSuiteResults( 1, 0, 0, 0 ); + public void testJunit48parallel() { + unpack("junit48-single-method") + .parallel("all") + .useUnlimitedThreads() + .executeTest() + .verifyErrorFreeLog() + .assertTestSuiteResults(1, 0, 0, 0); } @Test - public void testTestNg() - { + public void testTestNg() { Map props = new HashMap<>(); - props.put( "testNgVersion", "5.7" ); - props.put( "testNgClassifier", "jdk15" ); - singleMethod( "testng-single-method", props, null ); + props.put("testNgVersion", "5.7"); + props.put("testNgClassifier", "jdk15"); + singleMethod("testng-single-method", props, null); } @Test - public void testTestNg5149() - { - singleMethod( "/testng-single-method-5-14-9", Collections.emptyMap(), null ); + public void testTestNg5149() { + singleMethod("/testng-single-method-5-14-9", Collections.emptyMap(), null); } @Test - public void fullyQualifiedJunit48Provider4() - { - singleMethod( "junit48-single-method", Collections.emptyMap(), - "junit4.BasicTest#testSuccessOne", "-P surefire-junit4" ); + public void fullyQualifiedJunit48Provider4() { + singleMethod( + "junit48-single-method", + Collections.emptyMap(), + "junit4.BasicTest#testSuccessOne", + "-P surefire-junit4"); } @Test - public void fullyQualifiedJunit48Provider47() - { - singleMethod( "junit48-single-method", Collections.emptyMap(), - "junit4.BasicTest#testSuccessOne", "-P surefire-junit47" ); + public void fullyQualifiedJunit48Provider47() { + singleMethod( + "junit48-single-method", + Collections.emptyMap(), + "junit4.BasicTest#testSuccessOne", + "-P surefire-junit47"); } @Test - public void fullyQualifiedTestNg() - { + public void fullyQualifiedTestNg() { Map props = new HashMap<>(); - props.put( "testNgVersion", "5.7" ); - props.put( "testNgClassifier", "jdk15" ); - singleMethod( "testng-single-method", props, "testng.BasicTest#testSuccessOne" ); + props.put("testNgVersion", "5.7"); + props.put("testNgClassifier", "jdk15"); + singleMethod("testng-single-method", props, "testng.BasicTest#testSuccessOne"); } - } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/TimeoutForkedTestIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/TimeoutForkedTestIT.java index f185960aaf..34d9c89d27 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/TimeoutForkedTestIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/TimeoutForkedTestIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its; /* @@ -27,14 +45,15 @@ * * @author Dan Fabulich */ -public class TimeoutForkedTestIT - extends SurefireJUnit4IntegrationTestCase -{ +public class TimeoutForkedTestIT extends SurefireJUnit4IntegrationTestCase { @Test - public void testTimeoutForked() - { - unpack( "/timeout-forked" ).addGoal( "-DsleepLength=10000" ).addGoal( - "-DforkTimeout=1" ).maven().withFailure().executeTest(); + public void testTimeoutForked() { + unpack("/timeout-forked") + .addGoal("-DsleepLength=10000") + .addGoal("-DforkTimeout=1") + .maven() + .withFailure() + .executeTest(); // SUREFIRE-468 test that had to be reverted due to SUREFIRE-705 // assertFalse( getSurefireReportsFile( "TEST-timeoutForked.BasicTest.xml" ).exists() ); // assertFalse( getSurefireReportsFile( "timeoutForked.BasicTest.txt" ).exists() ); diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/TwoTestCasesIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/TwoTestCasesIT.java index 03d9ee4cac..3758ff73d9 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/TwoTestCasesIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/TwoTestCasesIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its; /* @@ -22,6 +40,7 @@ import java.util.HashSet; import java.util.List; import java.util.Set; + import org.apache.maven.plugins.surefire.report.ReportTestSuite; import org.apache.maven.surefire.its.fixture.HelperAssertions; import org.apache.maven.surefire.its.fixture.IntegrationTestSuiteResults; @@ -37,93 +56,81 @@ * * @author Dan Fabulich */ -public class TwoTestCasesIT - extends SurefireJUnit4IntegrationTestCase -{ +public class TwoTestCasesIT extends SurefireJUnit4IntegrationTestCase { @Test - public void testTwoTestCases() - { - unpack( "junit-twoTestCases" ) - .sysProp( "testNgVersion", "5.7" ) - .sysProp( "testNgClassifier", "jdk15" ) + public void testTwoTestCases() { + unpack("junit-twoTestCases") + .sysProp("testNgVersion", "5.7") + .sysProp("testNgClassifier", "jdk15") .executeTest() .verifyErrorFreeLog() - .assertTestSuiteResults( 2, 0, 0, 0 ); + .assertTestSuiteResults(2, 0, 0, 0); } /** * Runs two tests encapsulated in a suite */ @Test - public void testTwoTestCaseSuite() - { - final OutputValidator outputValidator = unpack( "junit-twoTestCaseSuite" ) - .sysProp( "testNgVersion", "5.7" ) - .sysProp( "testNgClassifier", "jdk15" ) - .executeTest(); - outputValidator.verifyErrorFreeLog().assertTestSuiteResults( 2, 0, 0, 0 ); - List reports = HelperAssertions.extractReports( outputValidator.getBaseDir() ); - Set classNames = extractClassNames( reports ); - assertContains( classNames, "junit.twoTestCaseSuite.BasicTest" ); - assertContains( classNames, "junit.twoTestCaseSuite.TestTwo" ); - assertEquals( "wrong number of classes", 2, classNames.size() ); - IntegrationTestSuiteResults results = HelperAssertions.parseReportList( reports ); - HelperAssertions.assertTestSuiteResults( 2, 0, 0, 0, results ); + public void testTwoTestCaseSuite() { + final OutputValidator outputValidator = unpack("junit-twoTestCaseSuite") + .sysProp("testNgVersion", "5.7") + .sysProp("testNgClassifier", "jdk15") + .executeTest(); + outputValidator.verifyErrorFreeLog().assertTestSuiteResults(2, 0, 0, 0); + List reports = HelperAssertions.extractReports(outputValidator.getBaseDir()); + Set classNames = extractClassNames(reports); + assertContains(classNames, "junit.twoTestCaseSuite.BasicTest"); + assertContains(classNames, "junit.twoTestCaseSuite.TestTwo"); + assertEquals("wrong number of classes", 2, classNames.size()); + IntegrationTestSuiteResults results = HelperAssertions.parseReportList(reports); + HelperAssertions.assertTestSuiteResults(2, 0, 0, 0, results); } - private void assertContains( Set set, String expected ) - { - if ( set.contains( expected ) ) - { + private void assertContains(Set set, String expected) { + if (set.contains(expected)) { return; } - fail( "Set didn't contain " + expected ); + fail("Set didn't contain " + expected); } - private Set extractClassNames( List reports ) - { + private Set extractClassNames(List reports) { HashSet classNames = new HashSet<>(); - for ( ReportTestSuite suite : reports ) - { - classNames.add( suite.getFullClassName() ); + for (ReportTestSuite suite : reports) { + classNames.add(suite.getFullClassName()); } return classNames; } @Test - public void testJunit4Suite() - { - final OutputValidator outputValidator = unpack( "junit4-twoTestCaseSuite" ) - .sysProp( "testNgVersion", "5.7" ) - .sysProp( "testNgClassifier", "jdk15" ) - .executeTest(); - outputValidator.verifyErrorFreeLog().assertTestSuiteResults( 2, 0, 0, 0 ); + public void testJunit4Suite() { + final OutputValidator outputValidator = unpack("junit4-twoTestCaseSuite") + .sysProp("testNgVersion", "5.7") + .sysProp("testNgClassifier", "jdk15") + .executeTest(); + outputValidator.verifyErrorFreeLog().assertTestSuiteResults(2, 0, 0, 0); - List reports = - HelperAssertions.extractReports( outputValidator.getBaseDir() ); - Set classNames = extractClassNames( reports ); - assertContains( classNames, "twoTestCaseSuite.BasicTest" ); - assertContains( classNames, "twoTestCaseSuite.Junit4TestTwo" ); - assertEquals( "wrong number of classes", 2, classNames.size() ); - IntegrationTestSuiteResults results = HelperAssertions.parseReportList( reports ); - HelperAssertions.assertTestSuiteResults( 2, 0, 0, 0, results ); + List reports = HelperAssertions.extractReports(outputValidator.getBaseDir()); + Set classNames = extractClassNames(reports); + assertContains(classNames, "twoTestCaseSuite.BasicTest"); + assertContains(classNames, "twoTestCaseSuite.Junit4TestTwo"); + assertEquals("wrong number of classes", 2, classNames.size()); + IntegrationTestSuiteResults results = HelperAssertions.parseReportList(reports); + HelperAssertions.assertTestSuiteResults(2, 0, 0, 0, results); } @Test - public void testTestNGSuite() - { - final OutputValidator outputValidator = unpack( "testng-twoTestCaseSuite" ) - .sysProp( "testNgVersion", "5.7" ) - .sysProp( "testNgClassifier", "jdk15" ) - .executeTest(); - outputValidator.assertTestSuiteResults( 2, 0, 0, 0 ); - List reports = HelperAssertions.extractReports( outputValidator.getBaseDir() ); - Set classNames = extractClassNames( reports ); - assertContains( classNames, "testng.two.TestNGTestTwo" ); - assertContains( classNames, "testng.two.TestNGSuiteTest" ); - assertEquals( "wrong number of classes", 2, classNames.size() ); - IntegrationTestSuiteResults results = HelperAssertions.parseReportList( reports ); - HelperAssertions.assertTestSuiteResults( 2, 0, 0, 0, results ); + public void testTestNGSuite() { + final OutputValidator outputValidator = unpack("testng-twoTestCaseSuite") + .sysProp("testNgVersion", "5.7") + .sysProp("testNgClassifier", "jdk15") + .executeTest(); + outputValidator.assertTestSuiteResults(2, 0, 0, 0); + List reports = HelperAssertions.extractReports(outputValidator.getBaseDir()); + Set classNames = extractClassNames(reports); + assertContains(classNames, "testng.two.TestNGTestTwo"); + assertContains(classNames, "testng.two.TestNGSuiteTest"); + assertEquals("wrong number of classes", 2, classNames.size()); + IntegrationTestSuiteResults results = HelperAssertions.parseReportList(reports); + HelperAssertions.assertTestSuiteResults(2, 0, 0, 0, results); } - } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/UmlautDirIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/UmlautDirIT.java index 2be3fb9e89..b9a03a7172 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/UmlautDirIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/UmlautDirIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its; /* @@ -19,6 +37,12 @@ * under the License. */ +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; + import org.apache.maven.shared.utils.io.FileUtils; import org.apache.maven.surefire.its.fixture.MavenLauncher; import org.apache.maven.surefire.its.fixture.SurefireJUnit4IntegrationTestCase; @@ -27,19 +51,13 @@ import org.junit.Before; import org.junit.Test; -import java.io.File; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; - -import static org.apache.maven.surefire.its.fixture.HelperAssertions.assumeJavaVersionExcluded; import static java.nio.file.Files.copy; import static java.nio.file.Files.createDirectories; import static java.nio.file.Files.exists; import static java.nio.file.StandardCopyOption.REPLACE_EXISTING; import static java.util.Objects.requireNonNull; import static org.apache.commons.lang3.SystemUtils.IS_OS_LINUX; +import static org.apache.maven.surefire.its.fixture.HelperAssertions.assumeJavaVersionExcluded; import static org.junit.Assume.assumeTrue; /** @@ -47,180 +65,153 @@ * * @author Dan Fabulich */ -public class UmlautDirIT extends SurefireJUnit4IntegrationTestCase -{ +public class UmlautDirIT extends SurefireJUnit4IntegrationTestCase { private String localRepo; @Before - public void backupLocalRepo() - { + public void backupLocalRepo() { // We touched the Javac bug, see the discussion [1]. // The fix [2] will be in Java 17, not in Java 16. So we cannot use Java 16 then! // [1]: http://ant.1045680.n5.nabble.com/JDK-16-is-in-Rampdown-Phase-One-td5720549.html#a5720552 // [2]: https://bugs.openjdk.java.net/browse/JDK-8258246 - assumeJavaVersionExcluded( 16 ); + assumeJavaVersionExcluded(16); - localRepo = System.getProperty( "maven.repo.local" ); + localRepo = System.getProperty("maven.repo.local"); } @After - public void restoreLocalRepo() - { - if ( localRepo == null ) - { - System.clearProperty( "maven.repo.local" ); - } - else - { - System.setProperty( "maven.repo.local", localRepo ); + public void restoreLocalRepo() { + if (localRepo == null) { + System.clearProperty("maven.repo.local"); + } else { + System.setProperty("maven.repo.local", localRepo); } } @Test - public void surefire1617WithColonInLocalRepo() - throws Exception - { - assumeTrue( IS_OS_LINUX ); + public void surefire1617WithColonInLocalRepo() throws Exception { + assumeTrue(IS_OS_LINUX); - unpack( "junit-pathWithUmlaut", "_compiled" ) - .maven() - .execute( "compiler:testCompile" ); + unpack("junit-pathWithUmlaut", "_compiled").maven().execute("compiler:testCompile"); - String cwd = System.getProperty( "user.dir" ); + String cwd = System.getProperty("user.dir"); - Path from = Paths.get( cwd, "target", "UmlautDirIT_surefire1617WithColonInLocalRepo_compiled", "target", - "test-classes", "umlautTest" ); + Path from = Paths.get( + cwd, + "target", + "UmlautDirIT_surefire1617WithColonInLocalRepo_compiled", + "target", + "test-classes", + "umlautTest"); - Path to = Paths.get( cwd, "target", "UmlautDirIT_surefire1617WithColonInLocalRepo", "target", - "test-classes", "umlautTest" ); + Path to = Paths.get( + cwd, "target", "UmlautDirIT_surefire1617WithColonInLocalRepo", "target", "test-classes", "umlautTest"); Path localRepoDirWithColonInName = - Paths.get( System.getProperty( "user.dir" ), "target", "local repo for: SUREFIRE-1617" ); + Paths.get(System.getProperty("user.dir"), "target", "local repo for: SUREFIRE-1617"); - try - { - MavenLauncher mavenLauncher = unpackWithCustomLocalRepoDirectory( localRepoDirWithColonInName ).maven(); + try { + MavenLauncher mavenLauncher = unpackWithCustomLocalRepoDirectory(localRepoDirWithColonInName) + .maven(); - mavenLauncher.setForkJvm( true ); - mavenLauncher.setAutoclean( false ); + mavenLauncher.setForkJvm(true); + mavenLauncher.setAutoclean(false); - if ( !Files.exists( to ) ) - { - Files.createDirectories( to ); + if (!Files.exists(to)) { + Files.createDirectories(to); } - FileUtils.copyDirectory( from.toFile(), to.toFile() ); + FileUtils.copyDirectory(from.toFile(), to.toFile()); - mavenLauncher.sysProp( "skipCompiler", true ) - .debugLogging() - .executeTest() - .verifyErrorFreeLog() - .assertTestSuiteResults( 1, 0, 0, 0 ); - } - finally - { - if ( Files.exists( localRepoDirWithColonInName ) ) - { + mavenLauncher + .sysProp("skipCompiler", true) + .debugLogging() + .executeTest() + .verifyErrorFreeLog() + .assertTestSuiteResults(1, 0, 0, 0); + } finally { + if (Files.exists(localRepoDirWithColonInName)) { String dirNameWithoutColon = "surefire-1617-colon-in-local-repo_renamed-after-test"; - Path localRepoDirWithNoColonInName = localRepoDirWithColonInName.resolveSibling( dirNameWithoutColon ); - Files.move( localRepoDirWithColonInName, localRepoDirWithNoColonInName ); + Path localRepoDirWithNoColonInName = localRepoDirWithColonInName.resolveSibling(dirNameWithoutColon); + Files.move(localRepoDirWithColonInName, localRepoDirWithNoColonInName); } } } @Test - public void surefire1617WithColonInProjectDir() - throws Exception - { - assumeTrue( IS_OS_LINUX ); + public void surefire1617WithColonInProjectDir() throws Exception { + assumeTrue(IS_OS_LINUX); SurefireLauncher mavenLauncher = null; - try - { - mavenLauncher = unpackWithNewProjectDirectory( "this is: a test", "_surefire-1617" ); + try { + mavenLauncher = unpackWithNewProjectDirectory("this is: a test", "_surefire-1617"); mavenLauncher - .setForkJvm() - .sysProp( "argLine", "-Dpath.separator=;" ) - .executeTest() - .verifyErrorFreeLog() - .assertTestSuiteResults( 1, 0, 0, 0 ); - } - finally - { - if ( mavenLauncher != null ) - { + .setForkJvm() + .sysProp("argLine", "-Dpath.separator=;") + .executeTest() + .verifyErrorFreeLog() + .assertTestSuiteResults(1, 0, 0, 0); + } finally { + if (mavenLauncher != null) { String dirNameWithoutColon = "surefire-1617-colon-in-project-dir_renamed-after-test"; Path projectDirWithColonInName = mavenLauncher.getUnpackedAt().toPath(); - Path projectDirWithNoColonInName = projectDirWithColonInName.resolveSibling( dirNameWithoutColon ); - Files.move( projectDirWithColonInName, projectDirWithNoColonInName ); + Path projectDirWithNoColonInName = projectDirWithColonInName.resolveSibling(dirNameWithoutColon); + Files.move(projectDirWithColonInName, projectDirWithNoColonInName); } } } @Test - public void testUmlaut() - throws Exception - { - unpackWithNewProjectDirectory( "/junit-pathWith\u00DCmlaut_", "1" ) + public void testUmlaut() throws Exception { + unpackWithNewProjectDirectory("/junit-pathWith\u00DCmlaut_", "1") .executeTest() .verifyErrorFreeLog() - .assertTestSuiteResults( 1, 0, 0, 0 ); + .assertTestSuiteResults(1, 0, 0, 0); } @Test - public void testUmlautIsolatedClassLoader() - throws Exception - { - unpackWithNewProjectDirectory( "/junit-pathWith\u00DCmlaut_", "2" ) - .useSystemClassLoader( false ) + public void testUmlautIsolatedClassLoader() throws Exception { + unpackWithNewProjectDirectory("/junit-pathWith\u00DCmlaut_", "2") + .useSystemClassLoader(false) .executeTest() - .assertTestSuiteResults( 1, 0, 0, 0 ); + .assertTestSuiteResults(1, 0, 0, 0); } - private SurefireLauncher unpackWithNewProjectDirectory( String projectDirectory, String postfix ) - throws IOException - { - SurefireLauncher unpack = unpack( "junit-pathWithUmlaut" ); + private SurefireLauncher unpackWithNewProjectDirectory(String projectDirectory, String postfix) throws IOException { + SurefireLauncher unpack = unpack("junit-pathWithUmlaut"); MavenLauncher maven = unpack.maven(); - File dest = new File( maven.getUnpackedAt().getParentFile().getPath(), projectDirectory + postfix ); - maven.moveUnpackTo( dest ); + File dest = new File(maven.getUnpackedAt().getParentFile().getPath(), projectDirectory + postfix); + maven.moveUnpackTo(dest); return unpack; } - private SurefireLauncher unpackWithCustomLocalRepoDirectory( Path customLocalRepoPath ) - throws IOException - { + private SurefireLauncher unpackWithCustomLocalRepoDirectory(Path customLocalRepoPath) throws IOException { String newLocalRepo = customLocalRepoPath.toString(); - String defaultLocalRepo = new MavenLauncher( getClass(), "junit-pathWithUmlaut", null ).getLocalRepository(); + String defaultLocalRepo = new MavenLauncher(getClass(), "junit-pathWithUmlaut", null).getLocalRepository(); - copyFolder( Paths.get( defaultLocalRepo, "org", "apache", "maven", "surefire" ), - Paths.get( newLocalRepo, "org", "apache", "maven", "surefire" ) ); + copyFolder( + Paths.get(defaultLocalRepo, "org", "apache", "maven", "surefire"), + Paths.get(newLocalRepo, "org", "apache", "maven", "surefire")); - copyFolder( Paths.get( defaultLocalRepo, "org", "apache", "maven", "plugins", "maven-surefire-plugin" ), - Paths.get( newLocalRepo, "org", "apache", "maven", "plugins", "maven-surefire-plugin" ) ); + copyFolder( + Paths.get(defaultLocalRepo, "org", "apache", "maven", "plugins", "maven-surefire-plugin"), + Paths.get(newLocalRepo, "org", "apache", "maven", "plugins", "maven-surefire-plugin")); - System.setProperty( "maven.repo.local", newLocalRepo ); - return unpack( "junit-pathWithUmlaut" ); + System.setProperty("maven.repo.local", newLocalRepo); + return unpack("junit-pathWithUmlaut"); } - private static void copyFolder( Path src, Path dest ) - throws IOException - { - if ( !exists( dest ) ) - { - createDirectories( dest ); + private static void copyFolder(Path src, Path dest) throws IOException { + if (!exists(dest)) { + createDirectories(dest); } - for ( File from : requireNonNull( src.toFile().listFiles() ) ) - { - Path to = dest.resolve( from.getName() ); - if ( from.isDirectory() ) - { - copyFolder( from.toPath(), to ); - } - else if ( from.isFile() ) - { - copy( from.toPath(), to, REPLACE_EXISTING ); + for (File from : requireNonNull(src.toFile().listFiles())) { + Path to = dest.resolve(from.getName()); + if (from.isDirectory()) { + copyFolder(from.toPath(), to); + } else if (from.isFile()) { + copy(from.toPath(), to, REPLACE_EXISTING); } } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/UnicodeTestNamesIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/UnicodeTestNamesIT.java index 57bc602d52..515619abd9 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/UnicodeTestNamesIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/UnicodeTestNamesIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its; /* @@ -19,14 +37,14 @@ * under the License. */ +import java.io.File; + import org.apache.maven.surefire.its.fixture.OutputValidator; import org.apache.maven.surefire.its.fixture.SurefireJUnit4IntegrationTestCase; import org.apache.maven.surefire.its.fixture.SurefireLauncher; import org.apache.maven.surefire.its.fixture.TestFile; import org.junit.Test; -import java.io.File; - import static org.apache.commons.io.Charsets.UTF_8; import static org.apache.maven.surefire.its.fixture.HelperAssertions.convertUnicodeToUTF8; import static org.junit.Assert.assertFalse; @@ -36,46 +54,41 @@ /** * Verifies unicode filenames pass through correctly. */ -public class UnicodeTestNamesIT - extends SurefireJUnit4IntegrationTestCase -{ +public class UnicodeTestNamesIT extends SurefireJUnit4IntegrationTestCase { private static final String REPORT_FILE_CONTENT = "junit.twoTestCases.\u800C\u7D22\u5176\u60C5Test"; private static final String TXT_REPORT = "junit.twoTestCases.\u800C\u7D22\u5176\u60C5Test.txt"; private static final String XML_REPORT = "TEST-junit.twoTestCases.\u800C\u7D22\u5176\u60C5Test.xml"; @Test - public void checkFileNamesWithUnicode() - { - SurefireLauncher unpacked = unpack( "unicode-testnames" ); + public void checkFileNamesWithUnicode() { + SurefireLauncher unpacked = unpack("unicode-testnames"); File basedir = unpacked.getUnpackedAt(); - unpacked.execute( "clean" ); + unpacked.execute("clean"); - File xxyz = new File( basedir, "src/test/java/junit/twoTestCases/XXYZTest.java" ); - File dest = new File( basedir, "src/test/java/junit/twoTestCases/\u800C\u7D22\u5176\u60C5Test.java" ); + File xxyz = new File(basedir, "src/test/java/junit/twoTestCases/XXYZTest.java"); + File dest = new File(basedir, "src/test/java/junit/twoTestCases/\u800C\u7D22\u5176\u60C5Test.java"); //noinspection ResultOfMethodCallIgnored dest.delete(); - assertTrue( xxyz.renameTo( dest ) ); + assertTrue(xxyz.renameTo(dest)); - assertTrue( dest.exists() ); - assumeFalse( new File( basedir, "src/test/java/junit/twoTestCases/????Test.java" ).exists() ); + assertTrue(dest.exists()); + assumeFalse(new File(basedir, "src/test/java/junit/twoTestCases/????Test.java").exists()); - OutputValidator outputValidator = - unpacked.executeTest() - .assertTestSuiteResults( 2, 0, 0, 0 ); + OutputValidator outputValidator = unpacked.executeTest().assertTestSuiteResults(2, 0, 0, 0); - TestFile surefireReportFile = outputValidator.getSurefireReportsFile( TXT_REPORT, UTF_8 ); - assertTrue( surefireReportFile.exists() ); + TestFile surefireReportFile = outputValidator.getSurefireReportsFile(TXT_REPORT, UTF_8); + assertTrue(surefireReportFile.exists()); // See src/test/resources/unicode-testnames/pom.xml and property project.build.sourceEncoding set to UTF-8. - surefireReportFile.assertContainsText( convertUnicodeToUTF8( REPORT_FILE_CONTENT ) ); + surefireReportFile.assertContainsText(convertUnicodeToUTF8(REPORT_FILE_CONTENT)); - TestFile surefireXmlReportFile = outputValidator.getSurefireReportsXmlFile( XML_REPORT ); - assertTrue( surefireXmlReportFile.exists() ); - assertFalse( surefireXmlReportFile.readFileToString().isEmpty() ); + TestFile surefireXmlReportFile = outputValidator.getSurefireReportsXmlFile(XML_REPORT); + assertTrue(surefireXmlReportFile.exists()); + assertFalse(surefireXmlReportFile.readFileToString().isEmpty()); // See src/test/resources/unicode-testnames/pom.xml and property project.build.sourceEncoding set to UTF-8. - surefireXmlReportFile.assertContainsText( convertUnicodeToUTF8( REPORT_FILE_CONTENT ) ); + surefireXmlReportFile.assertContainsText(convertUnicodeToUTF8(REPORT_FILE_CONTENT)); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/UseIsolatedClassLoaderIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/UseIsolatedClassLoaderIT.java index b87f6039bb..661ba5d339 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/UseIsolatedClassLoaderIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/UseIsolatedClassLoaderIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its; /* @@ -27,12 +45,9 @@ * * @author Dan Fabulich */ -public class UseIsolatedClassLoaderIT - extends SurefireJUnit4IntegrationTestCase -{ +public class UseIsolatedClassLoaderIT extends SurefireJUnit4IntegrationTestCase { @Test - public void testUseSystemClassLoader() - { - executeErrorFreeTest( "/isolated-classloader", 1 ); + public void testUseSystemClassLoader() { + executeErrorFreeTest("/isolated-classloader", 1); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/WorkingDirectoryIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/WorkingDirectoryIT.java index f381950a2b..be39287f9e 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/WorkingDirectoryIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/WorkingDirectoryIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its; /* @@ -23,6 +41,7 @@ import java.io.FileInputStream; import java.io.IOException; import java.util.Properties; + import org.apache.maven.it.VerificationException; import org.apache.maven.surefire.its.fixture.OutputValidator; import org.apache.maven.surefire.its.fixture.SurefireJUnit4IntegrationTestCase; @@ -40,98 +59,83 @@ * @author Dan Fabulich * @author Kristian Rosenvold */ -public class WorkingDirectoryIT - extends SurefireJUnit4IntegrationTestCase -{ +public class WorkingDirectoryIT extends SurefireJUnit4IntegrationTestCase { @Test - public void testWorkingDirectory() - throws Exception - { + public void testWorkingDirectory() throws Exception { final SurefireLauncher unpack = getUnpacked(); - final OutputValidator child = getPreparedChild( unpack ); - child.getTargetFile( "out.txt" ).delete(); + final OutputValidator child = getPreparedChild(unpack); + child.getTargetFile("out.txt").delete(); unpack.executeTest().verifyErrorFreeLog(); - child.assertTestSuiteResults( 1, 0, 0, 0 ); - verifyOutputDirectory( child ); + child.assertTestSuiteResults(1, 0, 0, 0); + verifyOutputDirectory(child); } @Test - public void testWorkingDirectoryNoFork() - throws Exception - { + public void testWorkingDirectoryNoFork() throws Exception { final SurefireLauncher unpack = getUnpacked(); - final OutputValidator child = getPreparedChild( unpack ); - child.getTargetFile( "out.txt" ).delete(); + final OutputValidator child = getPreparedChild(unpack); + child.getTargetFile("out.txt").delete(); unpack.forkNever().executeTest().verifyErrorFreeLog(); - child.assertTestSuiteResults( 1, 0, 0, 0 ); - verifyOutputDirectory( child ); + child.assertTestSuiteResults(1, 0, 0, 0); + verifyOutputDirectory(child); } @Test - public void testWorkingDirectoryChildOnly() - throws Exception - { + public void testWorkingDirectoryChildOnly() throws Exception { final SurefireLauncher unpack = getUnpacked(); - final SurefireLauncher child = unpack.getSubProjectLauncher( "child" ); - child.getSubProjectValidator( "child" ).getTargetFile( "out.txt" ).delete(); - final OutputValidator outputValidator = child.executeTest().assertTestSuiteResults( 1, 0, 0, 0 ); - verifyOutputDirectory( outputValidator ); + final SurefireLauncher child = unpack.getSubProjectLauncher("child"); + child.getSubProjectValidator("child").getTargetFile("out.txt").delete(); + final OutputValidator outputValidator = child.executeTest().assertTestSuiteResults(1, 0, 0, 0); + verifyOutputDirectory(outputValidator); } @Test - public void testWorkingDirectoryChildOnlyNoFork() - throws Exception - { + public void testWorkingDirectoryChildOnlyNoFork() throws Exception { final SurefireLauncher unpack = getUnpacked(); - final SurefireLauncher child = unpack.getSubProjectLauncher( "child" ); - child.getSubProjectValidator( "child" ).getTargetFile( "out.txt" ).delete(); - final OutputValidator outputValidator = child.forkNever().executeTest().assertTestSuiteResults( 1, 0, 0, 0 ); - verifyOutputDirectory( outputValidator ); + final SurefireLauncher child = unpack.getSubProjectLauncher("child"); + child.getSubProjectValidator("child").getTargetFile("out.txt").delete(); + final OutputValidator outputValidator = child.forkNever().executeTest().assertTestSuiteResults(1, 0, 0, 0); + verifyOutputDirectory(outputValidator); } - private SurefireLauncher getUnpacked() - { - return unpack( "working-directory" ); + private SurefireLauncher getUnpacked() { + return unpack("working-directory"); } - private OutputValidator getPreparedChild( SurefireLauncher unpack ) - throws VerificationException - { - final OutputValidator child = unpack.getSubProjectValidator( "child" ); - getOutFile( child ).delete(); + private OutputValidator getPreparedChild(SurefireLauncher unpack) throws VerificationException { + final OutputValidator child = unpack.getSubProjectValidator("child"); + getOutFile(child).delete(); return child; } - - private TestFile getOutFile( OutputValidator child ) - { - return child.getTargetFile( "out.txt" ); + private TestFile getOutFile(OutputValidator child) { + return child.getTargetFile("out.txt"); } - private void verifyOutputDirectory( OutputValidator childTestDir ) - throws IOException - { - final TestFile outFile = getOutFile( childTestDir ); - assertTrue( "out.txt doesn't exist: " + outFile.getAbsolutePath(), outFile.exists() ); + private void verifyOutputDirectory(OutputValidator childTestDir) throws IOException { + final TestFile outFile = getOutFile(childTestDir); + assertTrue("out.txt doesn't exist: " + outFile.getAbsolutePath(), outFile.exists()); Properties p = new Properties(); - try ( FileInputStream is = outFile.getFileInputStream() ) - { - p.load( is ); + try (FileInputStream is = outFile.getFileInputStream()) { + p.load(is); } - String userDirPath = p.getProperty( "user.dir" ); - assertNotNull( "user.dir was null in property file", userDirPath ); - File userDir = new File( userDirPath ); + String userDirPath = p.getProperty("user.dir"); + assertNotNull("user.dir was null in property file", userDirPath); + File userDir = new File(userDirPath); // test if not a symlink - if ( childTestDir.getBaseDir().getCanonicalFile().equals( childTestDir.getBaseDir().getAbsoluteFile() ) ) - { - assertTrue( "wrong user.dir ! symlink ", - childTestDir.getBaseDir().getAbsolutePath().equalsIgnoreCase( userDir.getAbsolutePath() ) ); - } - else - { - assertEquals( "wrong user.dir symlink ", childTestDir.getBaseDir().getCanonicalPath(), - userDir.getCanonicalPath() ); + if (childTestDir + .getBaseDir() + .getCanonicalFile() + .equals(childTestDir.getBaseDir().getAbsoluteFile())) { + assertTrue( + "wrong user.dir ! symlink ", + childTestDir.getBaseDir().getAbsolutePath().equalsIgnoreCase(userDir.getAbsolutePath())); + } else { + assertEquals( + "wrong user.dir symlink ", + childTestDir.getBaseDir().getCanonicalPath(), + userDir.getCanonicalPath()); } } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/WorkingDirectoryIsInvalidPropertyIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/WorkingDirectoryIsInvalidPropertyIT.java index 0785f5a4f8..2434714d6b 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/WorkingDirectoryIsInvalidPropertyIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/WorkingDirectoryIsInvalidPropertyIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its; /* @@ -27,13 +45,13 @@ * * @author Kristian Rosenvold */ -public class WorkingDirectoryIsInvalidPropertyIT - extends SurefireJUnit4IntegrationTestCase -{ +public class WorkingDirectoryIsInvalidPropertyIT extends SurefireJUnit4IntegrationTestCase { @Test - public void testWorkingDirectory() - { - unpack( "working-directory-is-invalid-property" ).maven().withFailure().executeTest().verifyTextInLog( - "workingDirectory cannot be null" ); + public void testWorkingDirectory() { + unpack("working-directory-is-invalid-property") + .maven() + .withFailure() + .executeTest() + .verifyTextInLog("workingDirectory cannot be null"); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/WorkingDirectoryMissingIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/WorkingDirectoryMissingIT.java index 5247160969..f573b86601 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/WorkingDirectoryMissingIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/WorkingDirectoryMissingIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its; /* @@ -27,13 +45,9 @@ * * @author Stephen Connolly */ -public class WorkingDirectoryMissingIT - extends SurefireJUnit4IntegrationTestCase -{ +public class WorkingDirectoryMissingIT extends SurefireJUnit4IntegrationTestCase { @Test - public void testWorkingDirectory() - { - unpack( "working-directory-missing" ).executeTest().verifyErrorFreeLog(); + public void testWorkingDirectory() { + unpack("working-directory-missing").executeTest().verifyErrorFreeLog(); } - } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/XmlReporterRunTimeIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/XmlReporterRunTimeIT.java index f4e55be773..319d05f1ec 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/XmlReporterRunTimeIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/XmlReporterRunTimeIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its; /* @@ -35,40 +53,32 @@ * * @author Kristian Rosenvold */ -@SuppressWarnings( { "checkstyle:magicnumber", "checkstyle:linelength" } ) -public class XmlReporterRunTimeIT - extends SurefireJUnit4IntegrationTestCase -{ +@SuppressWarnings({"checkstyle:magicnumber", "checkstyle:linelength"}) +public class XmlReporterRunTimeIT extends SurefireJUnit4IntegrationTestCase { @Test - public void testForkAlways() - { + public void testForkAlways() { // just generate .surefire- in order to apply runOrder - unpack( "/runorder-parallel" ) - .executeTest() - .verifyErrorFree( 9 ); + unpack("/runorder-parallel").executeTest().verifyErrorFree(9); // now assert test results match expected values - OutputValidator outputValidator = unpack( "/runorder-parallel" ) - .executeTest() - .verifyErrorFree( 9 ); + OutputValidator outputValidator = + unpack("/runorder-parallel").executeTest().verifyErrorFree(9); - for ( ReportTestSuite report : extractReports( outputValidator.getBaseDir() ) ) - { - if ( "runorder.parallel.Test1".equals( report.getFullClassName() ) ) - { + for (ReportTestSuite report : extractReports(outputValidator.getBaseDir())) { + if ("runorder.parallel.Test1".equals(report.getFullClassName())) { // should be 6f but because of having Windows sleep discrepancy it is 5.95f - assertThat( "runorder.parallel.Test1 report.getTimeElapsed found:" + report.getTimeElapsed(), - report.getTimeElapsed(), allOf( greaterThanOrEqualTo( 5.95f ), lessThan( 7f ) ) ); - } - else if ( "runorder.parallel.Test2".equals( report.getFullClassName() ) ) - { + assertThat( + "runorder.parallel.Test1 report.getTimeElapsed found:" + report.getTimeElapsed(), + report.getTimeElapsed(), + allOf(greaterThanOrEqualTo(5.95f), lessThan(7f))); + } else if ("runorder.parallel.Test2".equals(report.getFullClassName())) { // should be 5f but because of having Windows sleep discrepancy it is 4.95f - assertThat( "runorder.parallel.Test2 report.getTimeElapsed found:" + report.getTimeElapsed(), - report.getTimeElapsed(), allOf( greaterThanOrEqualTo( 4.95f ), lessThan( 6f ) ) ); - } - else - { - System.out.println( "report = " + report ); + assertThat( + "runorder.parallel.Test2 report.getTimeElapsed found:" + report.getTimeElapsed(), + report.getTimeElapsed(), + allOf(greaterThanOrEqualTo(4.95f), lessThan(6f))); + } else { + System.out.println("report = " + report); } } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/fixture/AbstractJava9PlusIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/fixture/AbstractJava9PlusIT.java index 42f10a00bb..583905732e 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/fixture/AbstractJava9PlusIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/fixture/AbstractJava9PlusIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its.fixture; /* @@ -27,36 +45,29 @@ * @author Tibor Digana (tibor17) * @since 2.20.1 */ -public abstract class AbstractJava9PlusIT - extends SurefireJUnit4IntegrationTestCase -{ +public abstract class AbstractJava9PlusIT extends SurefireJUnit4IntegrationTestCase { protected abstract String getProjectDirectoryName(); - protected SurefireLauncher assumeJava9() - { - assumeTrue( "There's no JDK 9 provided.", IS_JAVA9_PLUS ); + protected SurefireLauncher assumeJava9() { + assumeTrue("There's no JDK 9 provided.", IS_JAVA9_PLUS); return unpack(); } - protected String getSuffix() - { + protected String getSuffix() { return null; } @Override - public final SurefireLauncher unpack( String sourceName ) - { + public final SurefireLauncher unpack(String sourceName) { throw new UnsupportedOperationException(); } @Override - public final SurefireLauncher unpack( String sourceName, String suffix ) - { + public final SurefireLauncher unpack(String sourceName, String suffix) { throw new UnsupportedOperationException(); } - private SurefireLauncher unpack() - { - return unpack( getClass(), getProjectDirectoryName(), getSuffix() ); + private SurefireLauncher unpack() { + return unpack(getClass(), getProjectDirectoryName(), getSuffix()); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/fixture/Configuration.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/fixture/Configuration.java index dcd8184764..e5516bc1c2 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/fixture/Configuration.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/fixture/Configuration.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its.fixture; /* @@ -23,7 +41,10 @@ * @author Tibor Digana (tibor17) * @since 2.19 */ -public enum Configuration -{ - TEST, INCLUDES, INCLUDES_FILE, INCLUDES_EXCLUDES, INCLUDES_EXCLUDES_FILE +public enum Configuration { + TEST, + INCLUDES, + INCLUDES_FILE, + INCLUDES_EXCLUDES, + INCLUDES_EXCLUDES_FILE } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/fixture/FailsafeOutputValidator.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/fixture/FailsafeOutputValidator.java index 19e1089959..3c61c469c6 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/fixture/FailsafeOutputValidator.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/fixture/FailsafeOutputValidator.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its.fixture; /* @@ -24,27 +42,19 @@ /** * */ -public class FailsafeOutputValidator - extends OutputValidator -{ - public FailsafeOutputValidator( OutputValidator source ) - { - super( source.verifier ); +public class FailsafeOutputValidator extends OutputValidator { + public FailsafeOutputValidator(OutputValidator source) { + super(source.verifier); } @Override - public OutputValidator verifyErrorFree( int total ) - { - try - { + public OutputValidator verifyErrorFree(int total) { + try { verifier.verifyErrorFreeLog(); - this.assertIntegrationTestSuiteResults( total, 0, 0, 0 ); + this.assertIntegrationTestSuiteResults(total, 0, 0, 0); return this; - } - catch ( VerificationException e ) - { - throw new SurefireVerifierException( e ); + } catch (VerificationException e) { + throw new SurefireVerifierException(e); } } - } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/fixture/HelperAssertions.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/fixture/HelperAssertions.java index dbfa5ff840..38a5d682a9 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/fixture/HelperAssertions.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/fixture/HelperAssertions.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its.fixture; /* @@ -19,185 +37,157 @@ * under the License. */ -import org.apache.maven.plugin.surefire.log.api.ConsoleLogger; -import org.apache.maven.plugin.surefire.log.api.PrintStreamLogger; -import org.apache.maven.plugins.surefire.report.ReportTestSuite; -import org.apache.maven.plugins.surefire.report.SurefireReportParser; - import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.Locale; +import org.apache.maven.plugin.surefire.log.api.ConsoleLogger; +import org.apache.maven.plugin.surefire.log.api.PrintStreamLogger; +import org.apache.maven.plugins.surefire.report.ReportTestSuite; +import org.apache.maven.plugins.surefire.report.SurefireReportParser; + import static java.lang.Double.parseDouble; +import static java.nio.charset.StandardCharsets.UTF_8; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertFalse; import static junit.framework.Assert.assertTrue; -import static java.nio.charset.StandardCharsets.UTF_8; import static org.junit.Assume.assumeTrue; /** * */ -@SuppressWarnings( {"JavaDoc"} ) -public final class HelperAssertions -{ - private HelperAssertions() - { - throw new IllegalStateException( "no instantiable constructor" ); +@SuppressWarnings({"JavaDoc"}) +public final class HelperAssertions { + private HelperAssertions() { + throw new IllegalStateException("no instantiable constructor"); } /** * assert that the reports in the specified testDir have the right summary statistics */ - public static void assertTestSuiteResults( int total, int errors, int failures, int skipped, File testDir ) - { - IntegrationTestSuiteResults suite = parseTestResults( testDir ); - assertTestSuiteResults( total, errors, failures, skipped, suite ); + public static void assertTestSuiteResults(int total, int errors, int failures, int skipped, File testDir) { + IntegrationTestSuiteResults suite = parseTestResults(testDir); + assertTestSuiteResults(total, errors, failures, skipped, suite); } - public static void assertTestSuiteResults( int total, int errors, int failures, int skipped, int flakes, - File testDir ) - { - IntegrationTestSuiteResults suite = parseTestResults( testDir ); - assertTestSuiteResults( total, errors, failures, skipped, flakes, suite ); + public static void assertTestSuiteResults( + int total, int errors, int failures, int skipped, int flakes, File testDir) { + IntegrationTestSuiteResults suite = parseTestResults(testDir); + assertTestSuiteResults(total, errors, failures, skipped, flakes, suite); } - public static void assertTestSuiteResults( int total, File testDir ) - { - IntegrationTestSuiteResults suite = parseTestResults( testDir ); - assertTestSuiteResults( total, suite ); + public static void assertTestSuiteResults(int total, File testDir) { + IntegrationTestSuiteResults suite = parseTestResults(testDir); + assertTestSuiteResults(total, suite); } /** * assert that the reports in the specified testDir have the right summary statistics */ - public static void assertIntegrationTestSuiteResults( int total, int errors, int failures, int skipped, - File testDir ) - { - IntegrationTestSuiteResults suite = parseIntegrationTestResults( testDir ); - assertTestSuiteResults( total, errors, failures, skipped, suite ); + public static void assertIntegrationTestSuiteResults( + int total, int errors, int failures, int skipped, File testDir) { + IntegrationTestSuiteResults suite = parseIntegrationTestResults(testDir); + assertTestSuiteResults(total, errors, failures, skipped, suite); } - public static void assertIntegrationTestSuiteResults( int total, File testDir ) - { - IntegrationTestSuiteResults suite = parseIntegrationTestResults( testDir ); - assertTestSuiteResults( total, suite ); + public static void assertIntegrationTestSuiteResults(int total, File testDir) { + IntegrationTestSuiteResults suite = parseIntegrationTestResults(testDir); + assertTestSuiteResults(total, suite); } - public static void assertTestSuiteResults( int total, int errors, int failures, int skipped, - IntegrationTestSuiteResults actualSuite ) - { - assertEquals( "wrong number of tests", total, actualSuite.getTotal() ); - assertEquals( "wrong number of errors", errors, actualSuite.getErrors() ); - assertEquals( "wrong number of failures", failures, actualSuite.getFailures() ); - assertEquals( "wrong number of skipped", skipped, actualSuite.getSkipped() ); + public static void assertTestSuiteResults( + int total, int errors, int failures, int skipped, IntegrationTestSuiteResults actualSuite) { + assertEquals("wrong number of tests", total, actualSuite.getTotal()); + assertEquals("wrong number of errors", errors, actualSuite.getErrors()); + assertEquals("wrong number of failures", failures, actualSuite.getFailures()); + assertEquals("wrong number of skipped", skipped, actualSuite.getSkipped()); } - public static void assertTestSuiteResults( int total, IntegrationTestSuiteResults actualSuite ) - { - assertEquals( "wrong number of tests", total, actualSuite.getTotal() ); + public static void assertTestSuiteResults(int total, IntegrationTestSuiteResults actualSuite) { + assertEquals("wrong number of tests", total, actualSuite.getTotal()); } - public static void assertTestSuiteResults( int total, int errors, int failures, int skipped, int flakes, - IntegrationTestSuiteResults actualSuite ) - { - assertTestSuiteResults( total, errors, failures, skipped, actualSuite ); - assertEquals( "wrong number of flaky tests", flakes, actualSuite.getFlakes() ); + public static void assertTestSuiteResults( + int total, int errors, int failures, int skipped, int flakes, IntegrationTestSuiteResults actualSuite) { + assertTestSuiteResults(total, errors, failures, skipped, actualSuite); + assertEquals("wrong number of flaky tests", flakes, actualSuite.getFlakes()); } - public static IntegrationTestSuiteResults parseTestResults( File... testDirs ) - { - List reports = extractReports( testDirs ); - return parseReportList( reports ); + public static IntegrationTestSuiteResults parseTestResults(File... testDirs) { + List reports = extractReports(testDirs); + return parseReportList(reports); } - private static IntegrationTestSuiteResults parseIntegrationTestResults( File... testDirs ) - { - List reports = extractITReports( testDirs ); - return parseReportList( reports ); + private static IntegrationTestSuiteResults parseIntegrationTestResults(File... testDirs) { + List reports = extractITReports(testDirs); + return parseReportList(reports); } /** * Converts a list of ReportTestSuites into an IntegrationTestSuiteResults object, suitable for summary assertions */ - public static IntegrationTestSuiteResults parseReportList( List reports ) - { - assertFalse( "No reports!", reports.isEmpty() ); + public static IntegrationTestSuiteResults parseReportList(List reports) { + assertFalse("No reports!", reports.isEmpty()); int total = 0, errors = 0, failures = 0, skipped = 0, flakes = 0; - for ( ReportTestSuite report : reports ) - { + for (ReportTestSuite report : reports) { total += report.getNumberOfTests(); errors += report.getNumberOfErrors(); failures += report.getNumberOfFailures(); skipped += report.getNumberOfSkipped(); flakes += report.getNumberOfFlakes(); } - return new IntegrationTestSuiteResults( total, errors, failures, skipped, flakes ); + return new IntegrationTestSuiteResults(total, errors, failures, skipped, flakes); } - public static List extractReports( File... testDirs ) - { + public static List extractReports(File... testDirs) { List reportsDirs = new ArrayList<>(); - for ( File testDir : testDirs ) - { - File reportsDir = new File( testDir, "target/surefire-reports" ); - assertTrue( "Reports directory is missing: " + reportsDir.getAbsolutePath(), reportsDir.exists() ); - reportsDirs.add( reportsDir ); + for (File testDir : testDirs) { + File reportsDir = new File(testDir, "target/surefire-reports"); + assertTrue("Reports directory is missing: " + reportsDir.getAbsolutePath(), reportsDir.exists()); + reportsDirs.add(reportsDir); } - ConsoleLogger logger = new PrintStreamLogger( System.out ); - SurefireReportParser parser = new SurefireReportParser( reportsDirs, Locale.ROOT, logger ); - try - { + ConsoleLogger logger = new PrintStreamLogger(System.out); + SurefireReportParser parser = new SurefireReportParser(reportsDirs, Locale.ROOT, logger); + try { return parser.parseXMLReportFiles(); - } - catch ( Exception e ) - { - throw new RuntimeException( "Couldn't parse XML reports", e ); + } catch (Exception e) { + throw new RuntimeException("Couldn't parse XML reports", e); } } - private static List extractITReports( File... testDirs ) - { + private static List extractITReports(File... testDirs) { List reportsDirs = new ArrayList<>(); - for ( File testDir : testDirs ) - { - File reportsDir = new File( testDir, "target/failsafe-reports" ); - assertTrue( "Reports directory is missing: " + reportsDir.getAbsolutePath(), reportsDir.exists() ); - reportsDirs.add( reportsDir ); + for (File testDir : testDirs) { + File reportsDir = new File(testDir, "target/failsafe-reports"); + assertTrue("Reports directory is missing: " + reportsDir.getAbsolutePath(), reportsDir.exists()); + reportsDirs.add(reportsDir); } - ConsoleLogger logger = new PrintStreamLogger( System.out ); - SurefireReportParser parser = new SurefireReportParser( reportsDirs, Locale.ROOT, logger ); - try - { + ConsoleLogger logger = new PrintStreamLogger(System.out); + SurefireReportParser parser = new SurefireReportParser(reportsDirs, Locale.ROOT, logger); + try { return parser.parseXMLReportFiles(); - } - catch ( Exception e ) - { - throw new RuntimeException( "Couldn't parse XML reports", e ); + } catch (Exception e) { + throw new RuntimeException("Couldn't parse XML reports", e); } } - public static void assumeJavaVersion( double expectedVersion ) - { - String thisVersion = System.getProperty( "java.specification.version" ); - assumeTrue( "java.specification.version: " + thisVersion, parseDouble( thisVersion ) >= expectedVersion ); + public static void assumeJavaVersion(double expectedVersion) { + String thisVersion = System.getProperty("java.specification.version"); + assumeTrue("java.specification.version: " + thisVersion, parseDouble(thisVersion) >= expectedVersion); } - public static void assumeJavaMaxVersion( double expectedMaxVersion ) - { - String thisVersion = System.getProperty( "java.specification.version" ); - assumeTrue( "java.specification.version: " + thisVersion, parseDouble( thisVersion ) <= expectedMaxVersion ); + public static void assumeJavaMaxVersion(double expectedMaxVersion) { + String thisVersion = System.getProperty("java.specification.version"); + assumeTrue("java.specification.version: " + thisVersion, parseDouble(thisVersion) <= expectedMaxVersion); } - public static void assumeJavaVersionExcluded( double excludedVersion ) - { - String thisVersion = System.getProperty( "java.specification.version" ); - assumeTrue( "java.specification.version: " + thisVersion, parseDouble( thisVersion ) != excludedVersion ); + public static void assumeJavaVersionExcluded(double excludedVersion) { + String thisVersion = System.getProperty("java.specification.version"); + assumeTrue("java.specification.version: " + thisVersion, parseDouble(thisVersion) != excludedVersion); } - public static String convertUnicodeToUTF8( String unicode ) - { - return new String( unicode.getBytes( UTF_8 ), UTF_8 ); + public static String convertUnicodeToUTF8(String unicode) { + return new String(unicode.getBytes(UTF_8), UTF_8); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/fixture/IntegrationTestSuiteResults.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/fixture/IntegrationTestSuiteResults.java index c2d77439f9..941f6cde6b 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/fixture/IntegrationTestSuiteResults.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/fixture/IntegrationTestSuiteResults.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its.fixture; /* @@ -22,72 +40,58 @@ /** * */ -public class IntegrationTestSuiteResults -{ +public class IntegrationTestSuiteResults { private int total, errors, failures, skipped, flakes; - public IntegrationTestSuiteResults( int total, int errors, int failures, int skipped ) - { + public IntegrationTestSuiteResults(int total, int errors, int failures, int skipped) { this.total = total; this.errors = errors; this.failures = failures; this.skipped = skipped; } - public IntegrationTestSuiteResults( int total, int errors, int failures, int skipped, int flakes ) - { - this( total, errors, failures, skipped ); + public IntegrationTestSuiteResults(int total, int errors, int failures, int skipped, int flakes) { + this(total, errors, failures, skipped); this.flakes = flakes; } - public int getTotal() - { + public int getTotal() { return total; } - public void setTotal( int total ) - { + public void setTotal(int total) { this.total = total; } - public int getErrors() - { + public int getErrors() { return errors; } - public void setErrors( int errors ) - { + public void setErrors(int errors) { this.errors = errors; } - public int getFailures() - { + public int getFailures() { return failures; } - public void setFailures( int failures ) - { + public void setFailures(int failures) { this.failures = failures; } - public int getSkipped() - { + public int getSkipped() { return skipped; } - public void setSkipped( int skipped ) - { + public void setSkipped(int skipped) { this.skipped = skipped; } - public int getFlakes() - { + public int getFlakes() { return flakes; } - public void setFlakes( int flakes ) - { + public void setFlakes(int flakes) { this.flakes = flakes; } - } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/fixture/IsRegex.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/fixture/IsRegex.java index 59d9070607..851d1155cd 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/fixture/IsRegex.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/fixture/IsRegex.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its.fixture; /* @@ -19,81 +37,65 @@ * under the License. */ +import java.util.Iterator; +import java.util.Set; + import org.hamcrest.BaseMatcher; import org.hamcrest.Description; import org.hamcrest.Matcher; -import java.util.Iterator; -import java.util.Set; - import static java.util.Collections.singleton; /** * Java Hamcrest Matcher with Regex. */ -public final class IsRegex - extends BaseMatcher> -{ - public static Matcher> regex( Set expectedRegex ) - { - return new IsRegex( expectedRegex ); +public final class IsRegex extends BaseMatcher> { + public static Matcher> regex(Set expectedRegex) { + return new IsRegex(expectedRegex); } - public static Matcher> regex( String expectedRegex ) - { - return new IsRegex( expectedRegex ); + public static Matcher> regex(String expectedRegex) { + return new IsRegex(expectedRegex); } private final Set expectedRegex; - private IsRegex( String expectedRegex ) - { - this.expectedRegex = singleton( expectedRegex ); + private IsRegex(String expectedRegex) { + this.expectedRegex = singleton(expectedRegex); } - private IsRegex( Set expectedRegex ) - { + private IsRegex(Set expectedRegex) { this.expectedRegex = expectedRegex; } @Override - public boolean matches( Object o ) - { - if ( o != null - && expectedRegex.size() == 1 ? isStringOrSet( o ) : isSet( o ) ) - { + public boolean matches(Object o) { + if (o != null && expectedRegex.size() == 1 ? isStringOrSet(o) : isSet(o)) { //noinspection unchecked - Set actual = isSet( o ) ? ( Set ) o : singleton( ( String ) o ); + Set actual = isSet(o) ? (Set) o : singleton((String) o); boolean matches = actual.size() == expectedRegex.size(); Iterator regex = expectedRegex.iterator(); - for ( String s : actual ) - { - if ( s == null || !regex.hasNext() || !s.matches( regex.next() ) ) - { + for (String s : actual) { + if (s == null || !regex.hasNext() || !s.matches(regex.next())) { matches = false; } } return matches; - } - else - { + } else { return false; } } @Override - public void describeTo( Description description ) - { - description.appendValue( expectedRegex ); + public void describeTo(Description description) { + description.appendValue(expectedRegex); } - private static boolean isStringOrSet( Object o ) - { + private static boolean isStringOrSet(Object o) { return o instanceof String || o instanceof Set; } - private static boolean isSet( Object o ) - { + private static boolean isSet(Object o) { return o instanceof Set; } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/fixture/JUnit4SuiteTest.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/fixture/JUnit4SuiteTest.java index 3961b132f1..ae58fdf3e1 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/fixture/JUnit4SuiteTest.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/fixture/JUnit4SuiteTest.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its.fixture; /* @@ -30,15 +48,10 @@ * @author Tibor Digana (tibor17) * @since 2.21.0 */ -@Suite.SuiteClasses( { - MavenLauncherTest.class, - SurefireLauncherTest.class -} ) -@RunWith( Suite.class ) -public class JUnit4SuiteTest -{ - public static Test suite() - { - return new JUnit4TestAdapter( JUnit4SuiteTest.class ); +@Suite.SuiteClasses({MavenLauncherTest.class, SurefireLauncherTest.class}) +@RunWith(Suite.class) +public class JUnit4SuiteTest { + public static Test suite() { + return new JUnit4TestAdapter(JUnit4SuiteTest.class); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/fixture/MavenLauncher.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/fixture/MavenLauncher.java index 08a3f5bf6f..9d35808617 100755 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/fixture/MavenLauncher.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/fixture/MavenLauncher.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its.fixture; /* @@ -19,11 +37,6 @@ * under the License. */ -import org.apache.maven.it.VerificationException; -import org.apache.maven.it.Verifier; -import org.apache.maven.it.util.ResourceExtractor; -import org.apache.maven.shared.utils.io.FileUtils; - import java.io.File; import java.io.IOException; import java.net.URL; @@ -35,6 +48,11 @@ import java.util.Map; import java.util.Map.Entry; +import org.apache.maven.it.VerificationException; +import org.apache.maven.it.Verifier; +import org.apache.maven.it.util.ResourceExtractor; +import org.apache.maven.shared.utils.io.FileUtils; + import static java.util.Collections.singletonMap; import static java.util.Collections.unmodifiableList; @@ -44,8 +62,7 @@ * * @author Kristian Rosenvold */ -public final class MavenLauncher -{ +public final class MavenLauncher { private static final File SETTINGS_XML_PATH = settingsXmlPath(); private final List cliOptions = new ArrayList<>(); @@ -72,8 +89,7 @@ public final class MavenLauncher private boolean expectFailure; - MavenLauncher( Class testClass, String resourceName, String suffix, String[] cli ) - { + MavenLauncher(Class testClass, String resourceName, String suffix, String[] cli) { this.testCaseBeingRun = testClass; this.resourceName = resourceName; this.suffix = suffix != null ? suffix : ""; @@ -82,427 +98,339 @@ public final class MavenLauncher resetCliOptions(); } - public MavenLauncher( Class testClass, String resourceName, String suffix ) - { - this( testClass, resourceName, suffix, null ); + public MavenLauncher(Class testClass, String resourceName, String suffix) { + this(testClass, resourceName, suffix, null); } - public File getUnpackedAt() - { + public File getUnpackedAt() { return ensureUnpacked(); } - private File ensureUnpacked() - { - if ( unpackedAt == null ) - { - unpackedAt = simpleExtractResources( testCaseBeingRun, resourceName ); + private File ensureUnpacked() { + if (unpackedAt == null) { + unpackedAt = simpleExtractResources(testCaseBeingRun, resourceName); } return unpackedAt; } - public void moveUnpackTo( File dest ) throws IOException - { - FileUtils.deleteDirectory( dest ); + public void moveUnpackTo(File dest) throws IOException { + FileUtils.deleteDirectory(dest); //noinspection ResultOfMethodCallIgnored - boolean moved = getUnpackedAt().renameTo( dest ); - if ( !moved ) - { - String fileEncoding = System.getProperty( "file.encoding" ); - String os = System.getProperty( "os.name" ); - String version = System.getProperty( "os.version" ); - String arch = System.getProperty( "os.arch" ); - throw new IOException( "Could not move " + getUnpackedAt() + " to " + dest - + " (file.encoding=" + fileEncoding + ", " + os + " " + version + " " + arch + ")." ); + boolean moved = getUnpackedAt().renameTo(dest); + if (!moved) { + String fileEncoding = System.getProperty("file.encoding"); + String os = System.getProperty("os.name"); + String version = System.getProperty("os.version"); + String arch = System.getProperty("os.arch"); + throw new IOException("Could not move " + getUnpackedAt() + " to " + dest + " (file.encoding=" + + fileEncoding + ", " + os + " " + version + " " + arch + ")."); } unpackedAt = dest; } - private void resetGoals() - { + private void resetGoals() { goals.clear(); } - private void addCliOption( String cliOption ) - { - cliOptions.add( cliOption ); + private void addCliOption(String cliOption) { + cliOptions.add(cliOption); } - private StackTraceElement findTopElemenent( StackTraceElement[] stackTrace, Class testClassToLookFor ) - { + private StackTraceElement findTopElemenent(StackTraceElement[] stackTrace, Class testClassToLookFor) { StackTraceElement bestmatch = null; - for ( StackTraceElement stackTraceElement : stackTrace ) - { - if ( stackTraceElement.getClassName().equals( testClassToLookFor.getName() ) ) - { + for (StackTraceElement stackTraceElement : stackTrace) { + if (stackTraceElement.getClassName().equals(testClassToLookFor.getName())) { bestmatch = stackTraceElement; } } return bestmatch; } - private static StackTraceElement[] getStackTraceElements() - { - try - { + private static StackTraceElement[] getStackTraceElements() { + try { throw new RuntimeException(); - } - catch ( RuntimeException e ) - { + } catch (RuntimeException e) { return e.getStackTrace(); } } - public void reset() - { + public void reset() { resetGoals(); resetCliOptions(); } - private void resetCliOptions() - { + private void resetCliOptions() { cliOptions.clear(); } - public MavenLauncher getSubProjectLauncher( String subProject ) - { + public MavenLauncher getSubProjectLauncher(String subProject) { MavenLauncher mavenLauncher = - new MavenLauncher( testCaseBeingRun, resourceName + File.separator + subProject, suffix, cli ); - mavenLauncher.unpackedAt = new File( ensureUnpacked(), subProject ); + new MavenLauncher(testCaseBeingRun, resourceName + File.separator + subProject, suffix, cli); + mavenLauncher.unpackedAt = new File(ensureUnpacked(), subProject); return mavenLauncher; } - public OutputValidator getSubProjectValidator( String subProject ) throws VerificationException - { - String subProjectBasedir = getValidator().getSubFile( subProject ).getAbsolutePath(); + public OutputValidator getSubProjectValidator(String subProject) throws VerificationException { + String subProjectBasedir = getValidator().getSubFile(subProject).getAbsolutePath(); String settingsXml = settingsXmlPath().getAbsolutePath(); - Verifier subProjectVerifier = createVerifier( subProjectBasedir, settingsXml, null ); - return new OutputValidator( subProjectVerifier ); + Verifier subProjectVerifier = createVerifier(subProjectBasedir, settingsXml, null); + return new OutputValidator(subProjectVerifier); } - public MavenLauncher addEnvVar( String key, String value ) - { - envVars.put( key, value ); + public MavenLauncher addEnvVar(String key, String value) { + envVars.put(key, value); return this; } - public MavenLauncher verifyFileNotPresent( String subFile ) throws VerificationException - { - getVerifier().verifyFileNotPresent( getValidator().getSubFile( subFile ).getAbsolutePath() ); + public MavenLauncher verifyFileNotPresent(String subFile) throws VerificationException { + getVerifier().verifyFileNotPresent(getValidator().getSubFile(subFile).getAbsolutePath()); return this; } - public MavenLauncher showErrorStackTraces() - { - addCliOption( "-e" ); + public MavenLauncher showErrorStackTraces() { + addCliOption("-e"); return this; } - public MavenLauncher debugLogging() - { - addCliOption( "-X" ); + public MavenLauncher debugLogging() { + addCliOption("-X"); return this; } - public MavenLauncher failNever() - { - addCliOption( "-fn" ); + public MavenLauncher failNever() { + addCliOption("-fn"); return this; } - public MavenLauncher offline() - { - addCliOption( "-o" ); + public MavenLauncher offline() { + addCliOption("-o"); return this; } - public MavenLauncher skipClean() - { - writeGoal( "-Dclean.skip=true" /* for maven-clean-plugin < 3.0 */ ); - writeGoal( "-Dmaven.clean.skip=true" /* for maven-clean-plugin 3.0+ */ ); + public MavenLauncher skipClean() { + writeGoal("-Dclean.skip=true" /* for maven-clean-plugin < 3.0 */); + writeGoal("-Dmaven.clean.skip=true" /* for maven-clean-plugin 3.0+ */); return this; } - public MavenLauncher addGoal( String goal ) - { - writeGoal( goal ); + public MavenLauncher addGoal(String goal) { + writeGoal(goal); return this; } - public FailsafeOutputValidator executeVerify() - { - return new FailsafeOutputValidator( conditionalExec( "verify" ) ); + public FailsafeOutputValidator executeVerify() { + return new FailsafeOutputValidator(conditionalExec("verify")); } - public OutputValidator executeTest() - { - return conditionalExec( "test" ); + public OutputValidator executeTest() { + return conditionalExec("test"); } - List getGoals() - { - return unmodifiableList( goals ); + List getGoals() { + return unmodifiableList(goals); } - private void writeGoal( String newGoal ) - { - if ( newGoal != null && newGoal.startsWith( "-D" ) ) - { - String sysPropKey = newGoal.contains( "=" ) ? newGoal.substring( 0, newGoal.indexOf( '=' ) ) : newGoal; + private void writeGoal(String newGoal) { + if (newGoal != null && newGoal.startsWith("-D")) { + String sysPropKey = newGoal.contains("=") ? newGoal.substring(0, newGoal.indexOf('=')) : newGoal; String sysPropStarter = sysPropKey + "="; - for ( ListIterator it = goals.listIterator(); it.hasNext(); ) - { + for (ListIterator it = goals.listIterator(); it.hasNext(); ) { String goal = it.next(); - if ( goal.equals( sysPropKey ) || goal.startsWith( sysPropStarter ) ) - { - System.out.printf( "[WARNING] System property already exists '%s'. Overriding to '%s'.\n", goal, - newGoal ); - it.set( newGoal ); + if (goal.equals(sysPropKey) || goal.startsWith(sysPropStarter)) { + System.out.printf( + "[WARNING] System property already exists '%s'. Overriding to '%s'.\n", goal, newGoal); + it.set(newGoal); return; } } } - goals.add( newGoal ); + goals.add(newGoal); } - private OutputValidator conditionalExec( String goal ) - { + private OutputValidator conditionalExec(String goal) { OutputValidator verify; - try - { - verify = execute( goal ); - } - catch ( SurefireVerifierException exc ) - { - if ( expectFailure ) - { + try { + verify = execute(goal); + } catch (SurefireVerifierException exc) { + if (expectFailure) { return getValidator(); - } - else - { + } else { throw exc; } } - if ( expectFailure ) - { - throw new RuntimeException( "Expecting build failure, got none!" ); + if (expectFailure) { + throw new RuntimeException("Expecting build failure, got none!"); } return verify; } - public MavenLauncher withFailure() - { + public MavenLauncher withFailure() { expectFailure = true; return this; } - public OutputValidator execute( String goal ) - { - addGoal( goal ); + public OutputValidator execute(String goal) { + addGoal(goal); return executeCurrentGoals(); } - public OutputValidator executeCurrentGoals() - { - try - { - List goalsAndProps = new ArrayList<>( goals ); + public OutputValidator executeCurrentGoals() { + try { + List goalsAndProps = new ArrayList<>(goals); - for ( Entry e : props.entrySet() ) - { + for (Entry e : props.entrySet()) { String key = e.getKey(); String val = e.getValue(); - goalsAndProps.add( val == null ? "-D" + key : "-D" + key + "=" + val ); + goalsAndProps.add(val == null ? "-D" + key : "-D" + key + "=" + val); } - getVerifier().setCliOptions( cliOptions ); - getVerifier().executeGoals( goalsAndProps, envVars ); + getVerifier().setCliOptions(cliOptions); + getVerifier().executeGoals(goalsAndProps, envVars); return getValidator(); - } - catch ( VerificationException e ) - { - throw new SurefireVerifierException( e.getLocalizedMessage(), e ); - } - finally - { + } catch (VerificationException e) { + throw new SurefireVerifierException(e.getLocalizedMessage(), e); + } finally { getVerifier().resetStreams(); } } - public MavenLauncher activateProfile( String profile ) - { - return addGoal( "-P" + profile ); + public MavenLauncher activateProfile(String profile) { + return addGoal("-P" + profile); } - public MavenLauncher sysProp( String key, String value ) - { - return sysProp( singletonMap( key, value ) ); + public MavenLauncher sysProp(String key, String value) { + return sysProp(singletonMap(key, value)); } - public MavenLauncher sysProp( Map properties ) - { - props.putAll( properties ); + public MavenLauncher sysProp(Map properties) { + props.putAll(properties); return this; } - public MavenLauncher sysProp( String key, boolean value ) - { - return sysProp( singletonMap( key, Boolean.toString( value ) ) ); + public MavenLauncher sysProp(String key, boolean value) { + return sysProp(singletonMap(key, Boolean.toString(value))); } - public MavenLauncher sysProp( String key, int value ) - { - return sysProp( singletonMap( key, Integer.toString( value ) ) ); + public MavenLauncher sysProp(String key, int value) { + return sysProp(singletonMap(key, Integer.toString(value))); } - public MavenLauncher sysProp( String key, double value ) - { - return sysProp( singletonMap( key, Double.toString( value ) ) ); + public MavenLauncher sysProp(String key, double value) { + return sysProp(singletonMap(key, Double.toString(value))); } - public MavenLauncher showExceptionMessages() - { - addCliOption( "-e" ); + public MavenLauncher showExceptionMessages() { + addCliOption("-e"); return this; } - public MavenLauncher deleteSiteDir() - { - try - { - FileUtils.deleteDirectory( getValidator().getSubFile( "site" ) ); - } - catch ( IOException e ) - { - throw new SurefireVerifierException( e ); + public MavenLauncher deleteSiteDir() { + try { + FileUtils.deleteDirectory(getValidator().getSubFile("site")); + } catch (IOException e) { + throw new SurefireVerifierException(e); } return this; } - public OutputValidator getValidator() - { - if ( validator == null ) - { - validator = new OutputValidator( getVerifier() ); + public OutputValidator getValidator() { + if (validator == null) { + validator = new OutputValidator(getVerifier()); } return validator; } - public void setForkJvm( boolean forkJvm ) - { - getVerifier().setForkJvm( forkJvm ); + public void setForkJvm(boolean forkJvm) { + getVerifier().setForkJvm(forkJvm); } - public String getLocalRepository() - { + public String getLocalRepository() { return getVerifier().getLocalRepository(); } - public void setAutoclean( boolean autoclean ) - { - getVerifier().setAutoclean( autoclean ); + public void setAutoclean(boolean autoclean) { + getVerifier().setAutoclean(autoclean); } - public void setLogFileName( String logFileName ) - { - getVerifier().setLogFileName( logFileName ); + public void setLogFileName(String logFileName) { + getVerifier().setLogFileName(logFileName); } - private Verifier getVerifier() - { - if ( verifier == null ) - { - try - { + private Verifier getVerifier() { + if (verifier == null) { + try { String unpackedPath = ensureUnpacked().getAbsolutePath(); String settingsXml = SETTINGS_XML_PATH.getAbsolutePath(); - verifier = createVerifier( unpackedPath, settingsXml, cli ); - } - catch ( VerificationException e ) - { - throw new RuntimeException( e ); + verifier = createVerifier(unpackedPath, settingsXml, cli); + } catch (VerificationException e) { + throw new RuntimeException(e); } } return verifier; } - private File simpleExtractResources( Class cl, String resourcePath ) - { - if ( !resourcePath.startsWith( "/" ) ) - { + private File simpleExtractResources(Class cl, String resourcePath) { + if (!resourcePath.startsWith("/")) { resourcePath = "/" + resourcePath; } File tempDir = getUnpackDir(); - File testDir = new File( tempDir, resourcePath ); - try - { - File parentPom = new File( tempDir.getParentFile(), "pom.xml" ); - if ( !parentPom.exists() ) - { - URL resource = cl.getResource( "/pom.xml" ); - FileUtils.copyURLToFile( resource, parentPom ); + File testDir = new File(tempDir, resourcePath); + try { + File parentPom = new File(tempDir.getParentFile(), "pom.xml"); + if (!parentPom.exists()) { + URL resource = cl.getResource("/pom.xml"); + FileUtils.copyURLToFile(resource, parentPom); } - FileUtils.deleteDirectory( testDir ); - File file = ResourceExtractor.extractResourceToDestination( cl, resourcePath, tempDir, true ); + FileUtils.deleteDirectory(testDir); + File file = ResourceExtractor.extractResourceToDestination(cl, resourcePath, tempDir, true); return file.getCanonicalFile(); - } - catch ( IOException e ) - { - throw new RuntimeException( e ); + } catch (IOException e) { + throw new RuntimeException(e); } } - private File getUnpackDir() - { - String tempDirPath = System.getProperty( "maven.test.tmpdir", System.getProperty( "java.io.tmpdir" ) ); - return new File( tempDirPath, testCaseBeingRun.getSimpleName() + "_" + getTestMethodName() + suffix ); + private File getUnpackDir() { + String tempDirPath = System.getProperty("maven.test.tmpdir", System.getProperty("java.io.tmpdir")); + return new File(tempDirPath, testCaseBeingRun.getSimpleName() + "_" + getTestMethodName() + suffix); } - public File getArtifactPath( String gid, String aid, String version, String ext ) - { - return new File( verifier.getArtifactPath( gid, aid, version, ext ) ); + public File getArtifactPath(String gid, String aid, String version, String ext) { + return new File(verifier.getArtifactPath(gid, aid, version, ext)); } - String getTestMethodName() - { + String getTestMethodName() { // dirty. Im sure we can use junit4 rules to attach testname to thread instead StackTraceElement[] stackTrace = getStackTraceElements(); StackTraceElement topInTestClass; - topInTestClass = findTopElemenent( stackTrace, testCaseBeingRun ); - if ( topInTestClass == null ) - { + topInTestClass = findTopElemenent(stackTrace, testCaseBeingRun); + if (topInTestClass == null) { // Look in superclass... - topInTestClass = findTopElemenent( stackTrace, testCaseBeingRun.getSuperclass() ); + topInTestClass = findTopElemenent(stackTrace, testCaseBeingRun.getSuperclass()); } - if ( topInTestClass != null ) - { + if (topInTestClass != null) { return topInTestClass.getMethodName(); } - throw new IllegalStateException( "Cannot find " + testCaseBeingRun.getName() + "in stacktrace" ); + throw new IllegalStateException("Cannot find " + testCaseBeingRun.getName() + "in stacktrace"); } - private static Verifier createVerifier( String basedir, String settingsFile, String[] defaultCliOptions ) - throws VerificationException - { - Verifier verifier = defaultCliOptions == null ? new Verifier( basedir, settingsFile, false ) : new Verifier( - basedir, settingsFile, false, defaultCliOptions ); + private static Verifier createVerifier(String basedir, String settingsFile, String[] defaultCliOptions) + throws VerificationException { + Verifier verifier = defaultCliOptions == null + ? new Verifier(basedir, settingsFile, false) + : new Verifier(basedir, settingsFile, false, defaultCliOptions); - verifier.getVerifierProperties().setProperty( "use.mavenRepoLocal", "true" ); + verifier.getVerifierProperties().setProperty("use.mavenRepoLocal", "true"); return verifier; } - private static File settingsXmlPath() - { - try - { - return new File( System.getProperty( "maven.settings.file" ) ).getCanonicalFile(); - } - catch ( IOException e ) - { - throw new IllegalStateException( e.getLocalizedMessage(), e ); + private static File settingsXmlPath() { + try { + return new File(System.getProperty("maven.settings.file")).getCanonicalFile(); + } catch (IOException e) { + throw new IllegalStateException(e.getLocalizedMessage(), e); } } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/fixture/MavenLauncherTest.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/fixture/MavenLauncherTest.java index 42657c0589..20953bb967 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/fixture/MavenLauncherTest.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/fixture/MavenLauncherTest.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its.fixture; /* @@ -21,27 +39,25 @@ import org.junit.Test; +import static org.hamcrest.CoreMatchers.hasItems; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; -import static org.hamcrest.CoreMatchers.hasItems; /** * @author Tibor Digana (tibor17) * @since 2.20 */ -public class MavenLauncherTest -{ +public class MavenLauncherTest { @Test - public void shouldNotDuplicateSystemProperties() - { - MavenLauncher launcher = new MavenLauncher( getClass(), "", "" ) - .addGoal( "-DskipTests" ) - .addGoal( "-Dx=a" ) - .addGoal( "-DskipTests" ) - .addGoal( "-Dx=b" ); + public void shouldNotDuplicateSystemProperties() { + MavenLauncher launcher = new MavenLauncher(getClass(), "", "") + .addGoal("-DskipTests") + .addGoal("-Dx=a") + .addGoal("-DskipTests") + .addGoal("-Dx=b"); - assertThat( launcher.getGoals(), hasItems( "-Dx=b", "-DskipTests" ) ); + assertThat(launcher.getGoals(), hasItems("-Dx=b", "-DskipTests")); - assertThat( launcher.getGoals().size(), is( 2 ) ); + assertThat(launcher.getGoals().size(), is(2)); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/fixture/OutputValidator.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/fixture/OutputValidator.java index 14b360ca62..09e73715c9 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/fixture/OutputValidator.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/fixture/OutputValidator.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its.fixture; /* @@ -39,102 +57,75 @@ * * @author Kristian Rosenvold */ -public class OutputValidator -{ +public class OutputValidator { final Verifier verifier; private final File baseDir; - public OutputValidator( Verifier verifier ) - { + public OutputValidator(Verifier verifier) { this.verifier = verifier; - this.baseDir = new File( verifier.getBasedir() ); + this.baseDir = new File(verifier.getBasedir()); } - public OutputValidator verifyTextInLog( String text ) - { - try - { - verifier.verifyTextInLog( text ); - } - catch ( VerificationException e ) - { - throw new SurefireVerifierException( e ); + public OutputValidator verifyTextInLog(String text) { + try { + verifier.verifyTextInLog(text); + } catch (VerificationException e) { + throw new SurefireVerifierException(e); } return this; } - - public OutputValidator verifyErrorFreeLog() - { - try - { + public OutputValidator verifyErrorFreeLog() { + try { verifier.verifyErrorFreeLog(); - } - catch ( VerificationException e ) - { - throw new SurefireVerifierException( e ); + } catch (VerificationException e) { + throw new SurefireVerifierException(e); } return this; } - public OutputValidator verifyErrorFree( int total ) - { - try - { + public OutputValidator verifyErrorFree(int total) { + try { verifier.verifyErrorFreeLog(); - this.assertTestSuiteResults( total, 0, 0, 0 ); + this.assertTestSuiteResults(total, 0, 0, 0); return this; - } - catch ( VerificationException e ) - { - throw new SurefireVerifierException( e ); + } catch (VerificationException e) { + throw new SurefireVerifierException(e); } } - public OutputValidator assertThatLogLine( Matcher line, Matcher nTimes ) - throws VerificationException - { - int counter = loadLogLines( line ).size(); - assertThat( "log pattern does not match nTimes", counter, nTimes ); + public OutputValidator assertThatLogLine(Matcher line, Matcher nTimes) + throws VerificationException { + int counter = loadLogLines(line).size(); + assertThat("log pattern does not match nTimes", counter, nTimes); return this; } - public List loadLogLines() - throws VerificationException - { - return verifier.loadFile( verifier.getBasedir(), verifier.getLogFileName(), false ); + public List loadLogLines() throws VerificationException { + return verifier.loadFile(verifier.getBasedir(), verifier.getLogFileName(), false); } - public List loadLogLines( Matcher line ) - throws VerificationException - { + public List loadLogLines(Matcher line) throws VerificationException { List matchedLines = new ArrayList<>(); - for ( String log : loadLogLines() ) - { - if ( line.matches( log ) ) - { - matchedLines.add( log ); + for (String log : loadLogLines()) { + if (line.matches(log)) { + matchedLines.add(log); } } return matchedLines; } - public List loadFile( File file, Charset charset ) - { + public List loadFile(File file, Charset charset) { //noinspection unchecked - try - { - return FileUtils.readLines( file, charset.name() ); - } - catch ( IOException e ) - { - throw new SurefireVerifierException( e ); + try { + return FileUtils.readLines(file, charset.name()); + } catch (IOException e) { + throw new SurefireVerifierException(e); } } - public String getBasedir() - { + public String getBasedir() { return verifier.getBasedir(); } @@ -144,105 +135,85 @@ public String getBasedir() * @param path The subdirectory under basedir * @return A file */ - public File getSubFile( String path ) - { - return new File( getBasedir(), path ); + public File getSubFile(String path) { + return new File(getBasedir(), path); } - public OutputValidator assertTestSuiteResults( int total, int errors, int failures, int skipped ) - { - HelperAssertions.assertTestSuiteResults( total, errors, failures, skipped, baseDir ); + public OutputValidator assertTestSuiteResults(int total, int errors, int failures, int skipped) { + HelperAssertions.assertTestSuiteResults(total, errors, failures, skipped, baseDir); return this; } - public OutputValidator assertTestSuiteResults( int total, int errors, int failures, int skipped, int flakes ) - { - HelperAssertions.assertTestSuiteResults( total, errors, failures, skipped, flakes, baseDir ); + public OutputValidator assertTestSuiteResults(int total, int errors, int failures, int skipped, int flakes) { + HelperAssertions.assertTestSuiteResults(total, errors, failures, skipped, flakes, baseDir); return this; } - public OutputValidator assertTestSuiteResults( int total ) - { - HelperAssertions.assertTestSuiteResults( total, baseDir ); + public OutputValidator assertTestSuiteResults(int total) { + HelperAssertions.assertTestSuiteResults(total, baseDir); return this; } - public OutputValidator assertIntegrationTestSuiteResults( int total, int errors, int failures, int skipped ) - { - HelperAssertions.assertIntegrationTestSuiteResults( total, errors, failures, skipped, baseDir ); + public OutputValidator assertIntegrationTestSuiteResults(int total, int errors, int failures, int skipped) { + HelperAssertions.assertIntegrationTestSuiteResults(total, errors, failures, skipped, baseDir); return this; } - public OutputValidator assertIntegrationTestSuiteResults( int total ) - { - HelperAssertions.assertIntegrationTestSuiteResults( total, baseDir ); + public OutputValidator assertIntegrationTestSuiteResults(int total) { + HelperAssertions.assertIntegrationTestSuiteResults(total, baseDir); return this; } - public TestFile getTargetFile( String modulePath, String fileName ) - { - File targetDir = getSubFile( modulePath + "/target" ); - return new TestFile( new File( targetDir, fileName ), this ); + public TestFile getTargetFile(String modulePath, String fileName) { + File targetDir = getSubFile(modulePath + "/target"); + return new TestFile(new File(targetDir, fileName), this); } - public TestFile getTargetFile( String fileName ) - { - File targetDir = getSubFile( "target" ); - return new TestFile( new File( targetDir, fileName ), this ); + public TestFile getTargetFile(String fileName) { + File targetDir = getSubFile("target"); + return new TestFile(new File(targetDir, fileName), this); } - public TestFile getSurefireReportsFile( String fileName, Charset charset ) - { + public TestFile getSurefireReportsFile(String fileName, Charset charset) { File targetDir = getSurefireReportsDirectory(); - return new TestFile( new File( targetDir, fileName ), charset, this ); + return new TestFile(new File(targetDir, fileName), charset, this); } - public TestFile getSurefireReportsFile( String fileName ) - { - return getSurefireReportsFile( fileName, null ); + public TestFile getSurefireReportsFile(String fileName) { + return getSurefireReportsFile(fileName, null); } - public TestFile getSurefireReportsXmlFile( String fileName ) - { + public TestFile getSurefireReportsXmlFile(String fileName) { File targetDir = getSurefireReportsDirectory(); - return new TestFile( new File( targetDir, fileName ), UTF_8, this ); + return new TestFile(new File(targetDir, fileName), UTF_8, this); } - public File getSurefireReportsDirectory() - { - return getSubFile( "target/surefire-reports" ); + public File getSurefireReportsDirectory() { + return getSubFile("target/surefire-reports"); } - public TestFile getSiteFile( String fileName ) - { - File targetDir = getSubFile( "target/site" ); - return new TestFile( new File( targetDir, fileName ), this ); + public TestFile getSiteFile(String fileName) { + File targetDir = getSubFile("target/site"); + return new TestFile(new File(targetDir, fileName), this); } - public File getBaseDir() - { + public File getBaseDir() { return baseDir; } - public String[] getStringsOrderInLog( String[] strings ) - throws VerificationException - { + public String[] getStringsOrderInLog(String[] strings) throws VerificationException { String[] retArr = new String[strings.length]; - List strList = new ArrayList( Arrays.asList( strings ) ); + List strList = new ArrayList(Arrays.asList(strings)); int i = 0; - for ( String line : loadLogLines() ) - { - for ( int j = 0; j < strList.size(); j++ ) - { - if ( line.startsWith( strList.get( j ) ) ) - { - retArr[i] = strList.get( j ); + for (String line : loadLogLines()) { + for (int j = 0; j < strList.size(); j++) { + if (line.startsWith(strList.get(j))) { + retArr[i] = strList.get(j); ++i; - if ( i == strings.length ) - { + if (i == strings.length) { return retArr; } - strList.remove( j ); + strList.remove(j); break; } } @@ -250,16 +221,11 @@ public String[] getStringsOrderInLog( String[] strings ) return retArr; } - public boolean stringsAppearInSpecificOrderInLog( String[] strings ) - throws VerificationException - { + public boolean stringsAppearInSpecificOrderInLog(String[] strings) throws VerificationException { int i = 0; - for ( String line : loadLogLines() ) - { - if ( line.startsWith( strings[i] ) ) - { - if ( i == strings.length - 1 ) - { + for (String line : loadLogLines()) { + if (line.startsWith(strings[i])) { + if (i == strings.length - 1) { return true; } ++i; diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/fixture/Settings.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/fixture/Settings.java index 28013fb8f9..67e5d81b10 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/fixture/Settings.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/fixture/Settings.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its.fixture; /* @@ -23,50 +41,44 @@ * @author Tibor Digana (tibor17) * @since 2.19 */ -public enum Settings -{ - JUNIT4_TEST( TestFramework.JUNIT4, Configuration.TEST ), - JUNIT47_TEST( TestFramework.JUNIT47, Configuration.TEST ), - JUNIT4_INCLUDES( TestFramework.JUNIT4, Configuration.INCLUDES ), - JUNIT47_INCLUDES( TestFramework.JUNIT47, Configuration.INCLUDES ), - JUNIT4_INCLUDES_EXCLUDES( TestFramework.JUNIT4, Configuration.INCLUDES_EXCLUDES ), - JUNIT47_INCLUDES_EXCLUDES( TestFramework.JUNIT47, Configuration.INCLUDES_EXCLUDES ), - JUNIT4_INCLUDES_FILE( TestFramework.JUNIT4, Configuration.INCLUDES_FILE ), - JUNIT47_INCLUDES_FILE( TestFramework.JUNIT47, Configuration.INCLUDES_FILE ), - JUNIT4_INCLUDES_EXCLUDES_FILE( TestFramework.JUNIT4, Configuration.INCLUDES_EXCLUDES_FILE ), - JUNIT47_INCLUDES_EXCLUDES_FILE( TestFramework.JUNIT47, Configuration.INCLUDES_EXCLUDES_FILE ), - TestNG_TEST( TestFramework.TestNG, Configuration.TEST ), - TestNG_INCLUDES( TestFramework.TestNG, Configuration.INCLUDES ), - TestNG_INCLUDES_EXCLUDES( TestFramework.TestNG, Configuration.INCLUDES_EXCLUDES ), - TestNG_INCLUDES_FILE( TestFramework.TestNG, Configuration.INCLUDES_FILE ), - TestNG_INCLUDES_EXCLUDES_FILE( TestFramework.TestNG, Configuration.INCLUDES_EXCLUDES_FILE ); +public enum Settings { + JUNIT4_TEST(TestFramework.JUNIT4, Configuration.TEST), + JUNIT47_TEST(TestFramework.JUNIT47, Configuration.TEST), + JUNIT4_INCLUDES(TestFramework.JUNIT4, Configuration.INCLUDES), + JUNIT47_INCLUDES(TestFramework.JUNIT47, Configuration.INCLUDES), + JUNIT4_INCLUDES_EXCLUDES(TestFramework.JUNIT4, Configuration.INCLUDES_EXCLUDES), + JUNIT47_INCLUDES_EXCLUDES(TestFramework.JUNIT47, Configuration.INCLUDES_EXCLUDES), + JUNIT4_INCLUDES_FILE(TestFramework.JUNIT4, Configuration.INCLUDES_FILE), + JUNIT47_INCLUDES_FILE(TestFramework.JUNIT47, Configuration.INCLUDES_FILE), + JUNIT4_INCLUDES_EXCLUDES_FILE(TestFramework.JUNIT4, Configuration.INCLUDES_EXCLUDES_FILE), + JUNIT47_INCLUDES_EXCLUDES_FILE(TestFramework.JUNIT47, Configuration.INCLUDES_EXCLUDES_FILE), + TestNG_TEST(TestFramework.TestNG, Configuration.TEST), + TestNG_INCLUDES(TestFramework.TestNG, Configuration.INCLUDES), + TestNG_INCLUDES_EXCLUDES(TestFramework.TestNG, Configuration.INCLUDES_EXCLUDES), + TestNG_INCLUDES_FILE(TestFramework.TestNG, Configuration.INCLUDES_FILE), + TestNG_INCLUDES_EXCLUDES_FILE(TestFramework.TestNG, Configuration.INCLUDES_EXCLUDES_FILE); private final TestFramework framework; private final Configuration configuration; - Settings( TestFramework framework, Configuration configuration ) - { + Settings(TestFramework framework, Configuration configuration) { this.framework = framework; this.configuration = configuration; } - public String path() - { - return name().replace( '_', '-' ).toLowerCase(); + public String path() { + return name().replace('_', '-').toLowerCase(); } - public String profile() - { + public String profile() { return path(); } - public TestFramework getFramework() - { + public TestFramework getFramework() { return framework; } - public Configuration getConfiguration() - { + public Configuration getConfiguration() { return configuration; } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/fixture/SurefireJUnit4IntegrationTestCase.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/fixture/SurefireJUnit4IntegrationTestCase.java index eb8350647b..ec367196d4 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/fixture/SurefireJUnit4IntegrationTestCase.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/fixture/SurefireJUnit4IntegrationTestCase.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its.fixture; /* @@ -31,52 +49,43 @@ * * @author Kristian Rosenvold */ -public abstract class SurefireJUnit4IntegrationTestCase -{ +public abstract class SurefireJUnit4IntegrationTestCase { private static final int JAVA9_VERSION = 9; public static final double JAVA_VERSION = javaVersion(); public static final boolean IS_JAVA9_PLUS = isJDK9Plus(); - public OutputValidator executeErrorFreeTest( String sourceName, int total ) - { - return unpack( sourceName ).executeTest().verifyErrorFree( total ); + public OutputValidator executeErrorFreeTest(String sourceName, int total) { + return unpack(sourceName).executeTest().verifyErrorFree(total); } - public SurefireLauncher unpack( String sourceName ) - { - return unpack( getClass(), sourceName, "" ); + public SurefireLauncher unpack(String sourceName) { + return unpack(getClass(), sourceName, ""); } - public SurefireLauncher unpack( String sourceName, String suffix ) - { - return unpack( getClass(), sourceName, suffix ); + public SurefireLauncher unpack(String sourceName, String suffix) { + return unpack(getClass(), sourceName, suffix); } - public SurefireLauncher unpack( String sourceName, String suffix, String[] cli ) - { - return unpack( getClass(), sourceName, suffix, cli ); + public SurefireLauncher unpack(String sourceName, String suffix, String[] cli) { + return unpack(getClass(), sourceName, suffix, cli); } - public static SurefireLauncher unpack( Class testClass, String sourceName, String suffix ) - { - return unpack( testClass, sourceName, suffix, null ); + public static SurefireLauncher unpack(Class testClass, String sourceName, String suffix) { + return unpack(testClass, sourceName, suffix, null); } - private static SurefireLauncher unpack( Class testClass, String sourceName, String suffix, String[] cli ) - { - MavenLauncher mavenLauncher = new MavenLauncher( testClass, sourceName, suffix, cli ); - return new SurefireLauncher( mavenLauncher ); + private static SurefireLauncher unpack(Class testClass, String sourceName, String suffix, String[] cli) { + MavenLauncher mavenLauncher = new MavenLauncher(testClass, sourceName, suffix, cli); + return new SurefireLauncher(mavenLauncher); } - private static double javaVersion() - { - return parseDouble( System.getProperty( "java.specification.version" ) ); + private static double javaVersion() { + return parseDouble(System.getProperty("java.specification.version")); } - private static boolean isJDK9Plus() - { + private static boolean isJDK9Plus() { return javaVersion() >= JAVA9_VERSION; } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/fixture/SurefireLauncher.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/fixture/SurefireLauncher.java index 87de8f9b07..623bed1de4 100755 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/fixture/SurefireLauncher.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/fixture/SurefireLauncher.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its.fixture; /* @@ -19,12 +37,12 @@ * under the License. */ -import org.apache.maven.it.VerificationException; - import java.io.File; import java.util.ArrayList; import java.util.List; +import org.apache.maven.it.VerificationException; + /** * Encapsulate all needed features to start a surefire run *
    @@ -33,404 +51,329 @@ * * @author Kristian Rosenvold - */ -public final class SurefireLauncher -{ +public final class SurefireLauncher { private final MavenLauncher mavenLauncher; - private final String surefireVersion = System.getProperty( "surefire.version" ); + private final String surefireVersion = System.getProperty("surefire.version"); - public SurefireLauncher( MavenLauncher mavenLauncher ) - { + public SurefireLauncher(MavenLauncher mavenLauncher) { this.mavenLauncher = mavenLauncher; reset(); } - public MavenLauncher maven() - { + public MavenLauncher maven() { return mavenLauncher; } - String getTestMethodName() - { + String getTestMethodName() { return mavenLauncher.getTestMethodName(); } - public void reset() - { + public void reset() { mavenLauncher.reset(); - for ( String s : getInitialGoals() ) - { - mavenLauncher.addGoal( s ); + for (String s : getInitialGoals()) { + mavenLauncher.addGoal(s); } } - public SurefireLauncher getSubProjectLauncher( String subProject ) - { - return new SurefireLauncher( mavenLauncher.getSubProjectLauncher( subProject ) ); + public SurefireLauncher getSubProjectLauncher(String subProject) { + return new SurefireLauncher(mavenLauncher.getSubProjectLauncher(subProject)); } - public OutputValidator getSubProjectValidator( String subProject ) - throws VerificationException - { - return mavenLauncher.getSubProjectValidator( subProject ); + public OutputValidator getSubProjectValidator(String subProject) throws VerificationException { + return mavenLauncher.getSubProjectValidator(subProject); } - private SurefireLauncher addEnvVar( String key, String value ) - { - mavenLauncher.addEnvVar( key, value ); + private SurefireLauncher addEnvVar(String key, String value) { + mavenLauncher.addEnvVar(key, value); return this; } - public SurefireLauncher setMavenOpts( String opts ) - { - return addEnvVar( "MAVEN_OPTS", opts ); + public SurefireLauncher setMavenOpts(String opts) { + return addEnvVar("MAVEN_OPTS", opts); } - private List getInitialGoals() - { + private List getInitialGoals() { List goals = new ArrayList<>(); - goals.add( "-Dsurefire.version=" + surefireVersion ); + goals.add("-Dsurefire.version=" + surefireVersion); - String jacocoAgent = System.getProperty( "jacoco.agent", "" ); - goals.add( "-Djacoco.agent=" + jacocoAgent ); - goals.add( "-nsu" ); + String jacocoAgent = System.getProperty("jacoco.agent", ""); + goals.add("-Djacoco.agent=" + jacocoAgent); + goals.add("-nsu"); return goals; } - public SurefireLauncher showErrorStackTraces() - { + public SurefireLauncher showErrorStackTraces() { mavenLauncher.showErrorStackTraces(); return this; } - public SurefireLauncher debugLogging() - { + public SurefireLauncher debugLogging() { mavenLauncher.debugLogging(); return this; } - @SuppressWarnings( "UnusedDeclaration" ) - public SurefireLauncher debugSurefireFork() - { - mavenLauncher.sysProp( "maven.surefire.debug", "true" ); + @SuppressWarnings("UnusedDeclaration") + public SurefireLauncher debugSurefireFork() { + mavenLauncher.sysProp("maven.surefire.debug", "true"); return this; } - public SurefireLauncher failNever() - { + public SurefireLauncher failNever() { mavenLauncher.failNever(); return this; } - public SurefireLauncher groups( String groups ) - { - mavenLauncher.sysProp( "groups", groups ); + public SurefireLauncher groups(String groups) { + mavenLauncher.sysProp("groups", groups); return this; } - public SurefireLauncher addGoal( String goal ) - { - mavenLauncher.addGoal( goal ); + public SurefireLauncher addGoal(String goal) { + mavenLauncher.addGoal(goal); return this; } - public OutputValidator executeTest() - { - return mavenLauncher.execute( "test" ); + public OutputValidator executeTest() { + return mavenLauncher.execute("test"); } - public OutputValidator executeInstall() - { - return mavenLauncher.execute( "install" ); + public OutputValidator executeInstall() { + return mavenLauncher.execute("install"); } - public FailsafeOutputValidator executeVerify() - { - OutputValidator verify = execute( "verify" ); - return new FailsafeOutputValidator( verify ); + public FailsafeOutputValidator executeVerify() { + OutputValidator verify = execute("verify"); + return new FailsafeOutputValidator(verify); } - public OutputValidator execute( String goal ) - { - return mavenLauncher.execute( goal ); + public OutputValidator execute(String goal) { + return mavenLauncher.execute(goal); } - public OutputValidator executeSurefireReport() - { - return mavenLauncher.execute( "surefire-report:report" ); + public OutputValidator executeSurefireReport() { + return mavenLauncher.execute("surefire-report:report"); } - - public OutputValidator executeCurrentGoals() - { + public OutputValidator executeCurrentGoals() { return mavenLauncher.executeCurrentGoals(); } - - public SurefireLauncher printSummary( boolean printsummary ) - { - mavenLauncher.sysProp( "printSummary", printsummary ); + public SurefireLauncher printSummary(boolean printsummary) { + mavenLauncher.sysProp("printSummary", printsummary); return this; } - public SurefireLauncher redirectToFile( boolean redirect ) - { - mavenLauncher.sysProp( "maven.test.redirectTestOutputToFile", redirect ); + public SurefireLauncher redirectToFile(boolean redirect) { + mavenLauncher.sysProp("maven.test.redirectTestOutputToFile", redirect); return this; } - public SurefireLauncher forkOnce() - { - return forkCount( 1 ).reuseForks( true ); + public SurefireLauncher forkOnce() { + return forkCount(1).reuseForks(true); } - public SurefireLauncher forkNever() - { - return forkCount( 0 ); + public SurefireLauncher forkNever() { + return forkCount(0); } - public SurefireLauncher forkAlways() - { - return forkCount( 1 ).reuseForks( false ); + public SurefireLauncher forkAlways() { + return forkCount(1).reuseForks(false); } - public SurefireLauncher forkPerThread( int threadCount ) - { - return forkCount( threadCount ).reuseForks( true ); + public SurefireLauncher forkPerThread(int threadCount) { + return forkCount(threadCount).reuseForks(true); } - public SurefireLauncher threadCount( int threadCount ) - { - mavenLauncher.sysProp( "threadCount", threadCount ); + public SurefireLauncher threadCount(int threadCount) { + mavenLauncher.sysProp("threadCount", threadCount); return this; } - public SurefireLauncher forkCount( int forkCount ) - { - mavenLauncher.sysProp( "forkCount", forkCount ); + public SurefireLauncher forkCount(int forkCount) { + mavenLauncher.sysProp("forkCount", forkCount); return this; } - public SurefireLauncher reuseForks( boolean reuseForks ) - { - mavenLauncher.sysProp( "reuseForks", reuseForks ); + public SurefireLauncher reuseForks(boolean reuseForks) { + mavenLauncher.sysProp("reuseForks", reuseForks); return this; } - public SurefireLauncher runOrder( String runOrder ) - { - mavenLauncher.sysProp( "surefire.runOrder", runOrder ); + public SurefireLauncher runOrder(String runOrder) { + mavenLauncher.sysProp("surefire.runOrder", runOrder); return this; } - public SurefireLauncher runOrderRandomSeed( String runOrderRandomSeed ) - { - mavenLauncher.sysProp( "surefire.runOrder.random.seed", runOrderRandomSeed ); + public SurefireLauncher runOrderRandomSeed(String runOrderRandomSeed) { + mavenLauncher.sysProp("surefire.runOrder.random.seed", runOrderRandomSeed); return this; } - public SurefireLauncher failIfNoTests( boolean fail ) - { - mavenLauncher.sysProp( "failIfNoTests", fail ); + public SurefireLauncher failIfNoTests(boolean fail) { + mavenLauncher.sysProp("failIfNoTests", fail); return this; } - - public SurefireLauncher mavenTestFailureIgnore( boolean fail ) - { - mavenLauncher.sysProp( "maven.test.failure.ignore", fail ); + public SurefireLauncher mavenTestFailureIgnore(boolean fail) { + mavenLauncher.sysProp("maven.test.failure.ignore", fail); return this; } - public SurefireLauncher failIfNoSpecifiedTests( boolean fail ) - { - mavenLauncher.sysProp( "surefire.failIfNoSpecifiedTests", fail ); + public SurefireLauncher failIfNoSpecifiedTests(boolean fail) { + mavenLauncher.sysProp("surefire.failIfNoSpecifiedTests", fail); return this; } - public SurefireLauncher useSystemClassLoader( boolean useSystemClassLoader ) - { - mavenLauncher.sysProp( "useSystemClassLoader", useSystemClassLoader ); + public SurefireLauncher useSystemClassLoader(boolean useSystemClassLoader) { + mavenLauncher.sysProp("useSystemClassLoader", useSystemClassLoader); return this; } - public SurefireLauncher activateProfile( String profile ) - { - mavenLauncher.activateProfile( profile ); + public SurefireLauncher activateProfile(String profile) { + mavenLauncher.activateProfile(profile); return this; } - public SurefireLauncher disablePerCoreThreadCount() - { - mavenLauncher.sysProp( "perCoreThreadCount", false ); + public SurefireLauncher disablePerCoreThreadCount() { + mavenLauncher.sysProp("perCoreThreadCount", false); return this; } - public SurefireLauncher disableParallelOptimization() - { - mavenLauncher.sysProp( "parallelOptimized", "false" ); + public SurefireLauncher disableParallelOptimization() { + mavenLauncher.sysProp("parallelOptimized", "false"); return this; } - public SurefireLauncher parallel( String parallel ) - { - mavenLauncher.sysProp( "parallel", parallel ); + public SurefireLauncher parallel(String parallel) { + mavenLauncher.sysProp("parallel", parallel); return this; } - public SurefireLauncher parallelSuites() - { - return parallel( "suites" ); + public SurefireLauncher parallelSuites() { + return parallel("suites"); } - public SurefireLauncher parallelClasses() - { - return parallel( "classes" ); + public SurefireLauncher parallelClasses() { + return parallel("classes"); } - public SurefireLauncher parallelMethods() - { - return parallel( "methods" ); + public SurefireLauncher parallelMethods() { + return parallel("methods"); } - public SurefireLauncher parallelBoth() - { - return parallel( "both" ); + public SurefireLauncher parallelBoth() { + return parallel("both"); } - public SurefireLauncher parallelSuitesAndClasses() - { - return parallel( "suitesAndClasses" ); + public SurefireLauncher parallelSuitesAndClasses() { + return parallel("suitesAndClasses"); } - public SurefireLauncher parallelSuitesAndMethods() - { - return parallel( "suitesAndMethods" ); + public SurefireLauncher parallelSuitesAndMethods() { + return parallel("suitesAndMethods"); } - public SurefireLauncher parallelClassesAndMethods() - { - return parallel( "classesAndMethods" ); + public SurefireLauncher parallelClassesAndMethods() { + return parallel("classesAndMethods"); } - public SurefireLauncher parallelAll() - { - return parallel( "all" ); + public SurefireLauncher parallelAll() { + return parallel("all"); } - public SurefireLauncher useUnlimitedThreads() - { - mavenLauncher.sysProp( "useUnlimitedThreads", true ); + public SurefireLauncher useUnlimitedThreads() { + mavenLauncher.sysProp("useUnlimitedThreads", true); return this; } - public SurefireLauncher threadCountSuites( int count ) - { - mavenLauncher.sysProp( "threadCountSuites", count ); + public SurefireLauncher threadCountSuites(int count) { + mavenLauncher.sysProp("threadCountSuites", count); return this; } - public SurefireLauncher threadCountClasses( int count ) - { - mavenLauncher.sysProp( "threadCountClasses", count ); + public SurefireLauncher threadCountClasses(int count) { + mavenLauncher.sysProp("threadCountClasses", count); return this; } - public SurefireLauncher threadCountMethods( int count ) - { - mavenLauncher.sysProp( "threadCountMethods", count ); + public SurefireLauncher threadCountMethods(int count) { + mavenLauncher.sysProp("threadCountMethods", count); return this; } - public SurefireLauncher parallelTestsTimeoutInSeconds( double timeout ) - { - mavenLauncher.sysProp( "surefire.parallel.timeout", timeout ); + public SurefireLauncher parallelTestsTimeoutInSeconds(double timeout) { + mavenLauncher.sysProp("surefire.parallel.timeout", timeout); return this; } - public SurefireLauncher parallelTestsTimeoutForcedInSeconds( double timeout ) - { - mavenLauncher.sysProp( "surefire.parallel.forcedTimeout", timeout ); + public SurefireLauncher parallelTestsTimeoutForcedInSeconds(double timeout) { + mavenLauncher.sysProp("surefire.parallel.forcedTimeout", timeout); return this; } - public SurefireLauncher argLine( String value ) - { - mavenLauncher.sysProp( "argLine", value ); + public SurefireLauncher argLine(String value) { + mavenLauncher.sysProp("argLine", value); return this; } - public SurefireLauncher sysProp( String variable, String value ) - { - mavenLauncher.sysProp( variable, value ); + public SurefireLauncher sysProp(String variable, String value) { + mavenLauncher.sysProp(variable, value); return this; } - public SurefireLauncher setJUnitVersion( String version ) - { - mavenLauncher.sysProp( "junit.version", version ); + public SurefireLauncher setJUnitVersion(String version) { + mavenLauncher.sysProp("junit.version", version); return this; } - public SurefireLauncher setGroups( String groups ) - { - mavenLauncher.sysProp( "groups", groups ); + public SurefireLauncher setGroups(String groups) { + mavenLauncher.sysProp("groups", groups); return this; } - public SurefireLauncher setExcludedGroups( String excludedGroups ) - { - mavenLauncher.sysProp( "excludedGroups", excludedGroups ); + public SurefireLauncher setExcludedGroups(String excludedGroups) { + mavenLauncher.sysProp("excludedGroups", excludedGroups); return this; } - - public File getUnpackedAt() - { + public File getUnpackedAt() { return mavenLauncher.getUnpackedAt(); } - public SurefireLauncher addFailsafeReportOnlyGoal() - { - mavenLauncher.addGoal( getReportPluginGoal( ":failsafe-report-only" ) ); + public SurefireLauncher addFailsafeReportOnlyGoal() { + mavenLauncher.addGoal(getReportPluginGoal(":failsafe-report-only")); return this; } - public SurefireLauncher addSurefireReportGoal() - { - mavenLauncher.addGoal( getReportPluginGoal( "report" ) ); + public SurefireLauncher addSurefireReportGoal() { + mavenLauncher.addGoal(getReportPluginGoal("report")); return this; } - public SurefireLauncher addSurefireReportOnlyGoal() - { - mavenLauncher.addGoal( getReportPluginGoal( "report-only" ) ); + public SurefireLauncher addSurefireReportOnlyGoal() { + mavenLauncher.addGoal(getReportPluginGoal("report-only")); return this; } - private String getReportPluginGoal( String goal ) - { + private String getReportPluginGoal(String goal) { return "org.apache.maven.plugins:maven-surefire-report-plugin:" + surefireVersion + ":" + goal; } - public SurefireLauncher setTestToRun( String basicTest ) - { - mavenLauncher.sysProp( "test", basicTest ); + public SurefireLauncher setTestToRun(String basicTest) { + mavenLauncher.sysProp("test", basicTest); return this; } - public SurefireLauncher setForkJvm() - { - mavenLauncher.setForkJvm( true ); + public SurefireLauncher setForkJvm() { + mavenLauncher.setForkJvm(true); return this; } - - public SurefireLauncher setLogFileName( String logFileName ) - { - mavenLauncher.setLogFileName( logFileName ); + public SurefireLauncher setLogFileName(String logFileName) { + mavenLauncher.setLogFileName(logFileName); return this; } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/fixture/SurefireLauncherTest.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/fixture/SurefireLauncherTest.java index 801ebec637..055c1b4966 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/fixture/SurefireLauncherTest.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/fixture/SurefireLauncherTest.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its.fixture; /* @@ -26,14 +44,11 @@ /** * @author Kristian Rosenvold */ -public class SurefireLauncherTest -{ +public class SurefireLauncherTest { @Test - public void launcherGetsProperMethodName() - { - MavenLauncher mavenLauncher = new MavenLauncher( SurefireLauncherTest.class, "foo", "" ); - String method = new SurefireLauncher( mavenLauncher ).getTestMethodName(); - assertEquals( "launcherGetsProperMethodName", method ); - + public void launcherGetsProperMethodName() { + MavenLauncher mavenLauncher = new MavenLauncher(SurefireLauncherTest.class, "foo", ""); + String method = new SurefireLauncher(mavenLauncher).getTestMethodName(); + assertEquals("launcherGetsProperMethodName", method); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/fixture/SurefireVerifierException.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/fixture/SurefireVerifierException.java index 52015034cb..f73afd2369 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/fixture/SurefireVerifierException.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/fixture/SurefireVerifierException.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its.fixture; /* @@ -22,16 +40,12 @@ /** * @author Kristian Rosenvold */ -public class SurefireVerifierException - extends RuntimeException -{ - public SurefireVerifierException( String message, Throwable cause ) - { - super( message, cause ); +public class SurefireVerifierException extends RuntimeException { + public SurefireVerifierException(String message, Throwable cause) { + super(message, cause); } - public SurefireVerifierException( Throwable cause ) - { - super( cause ); + public SurefireVerifierException(Throwable cause) { + super(cause); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/fixture/TestFile.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/fixture/TestFile.java index 2c1fb0f0e4..e12cb2b709 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/fixture/TestFile.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/fixture/TestFile.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its.fixture; /* @@ -28,9 +46,9 @@ import java.net.URI; import java.nio.charset.Charset; import java.util.List; -import org.apache.commons.io.FileUtils; import junit.framework.Assert; +import org.apache.commons.io.FileUtils; import org.hamcrest.Matcher; import static java.nio.charset.Charset.defaultCharset; @@ -41,146 +59,113 @@ /** * @author Kristian Rosenvold */ -public class TestFile -{ +public class TestFile { private final File file; private final Charset encoding; private final OutputValidator surefireVerifier; - public TestFile( File file, OutputValidator surefireVerifier ) - { - this( file, defaultCharset(), surefireVerifier ); + public TestFile(File file, OutputValidator surefireVerifier) { + this(file, defaultCharset(), surefireVerifier); } - public TestFile( File file, Charset charset, OutputValidator surefireVerifier ) - { - try - { + public TestFile(File file, Charset charset, OutputValidator surefireVerifier) { + try { this.file = file.getCanonicalFile(); this.encoding = charset == null ? defaultCharset() : charset; this.surefireVerifier = surefireVerifier; - } - catch ( IOException e ) - { - throw new IllegalArgumentException( file.getPath() ); + } catch (IOException e) { + throw new IllegalArgumentException(file.getPath()); } } - public OutputValidator assertFileExists() - { - assertTrue( "File doesn't exist: " + file.getAbsolutePath(), file.exists() ); + public OutputValidator assertFileExists() { + assertTrue("File doesn't exist: " + file.getAbsolutePath(), file.exists()); return surefireVerifier; } - public OutputValidator assertFileNotExists() - { - assertFalse( "File doesn't exist: " + file.getAbsolutePath(), file.exists() ); + public OutputValidator assertFileNotExists() { + assertFalse("File doesn't exist: " + file.getAbsolutePath(), file.exists()); return surefireVerifier; } - public void delete() - { + public void delete() { //noinspection ResultOfMethodCallIgnored file.delete(); } - public String getAbsolutePath() - { + public String getAbsolutePath() { return file.getAbsolutePath(); } - public boolean exists() - { + public boolean exists() { return file.exists(); } - public FileInputStream getFileInputStream() - throws FileNotFoundException - { - return new FileInputStream( file ); + public FileInputStream getFileInputStream() throws FileNotFoundException { + return new FileInputStream(file); } - public String slurpFile() - { + public String slurpFile() { StringBuilder sb = new StringBuilder(); - try ( BufferedReader reader = new BufferedReader( new InputStreamReader( getFileInputStream(), encoding ) ) ) - { - for ( String line = reader.readLine(); line != null; line = reader.readLine() ) - { - sb.append( line ); + try (BufferedReader reader = new BufferedReader(new InputStreamReader(getFileInputStream(), encoding))) { + for (String line = reader.readLine(); line != null; line = reader.readLine()) { + sb.append(line); } return sb.toString(); - } - catch ( IOException e ) - { - throw new SurefireVerifierException( e ); + } catch (IOException e) { + throw new SurefireVerifierException(e); } } - public String readFileToString() - { - try - { - return FileUtils.readFileToString( file, encoding ); - } - catch ( IOException e ) - { - throw new SurefireVerifierException( e ); + public String readFileToString() { + try { + return FileUtils.readFileToString(file, encoding); + } catch (IOException e) { + throw new SurefireVerifierException(e); } } - public boolean isFile() - { + public boolean isFile() { return file.isFile(); } - public TestFile assertContainsText( Matcher matcher ) - { - final List list = surefireVerifier.loadFile( file, encoding ); - for ( String line : list ) - { - if ( matcher.matches( line ) ) - { + public TestFile assertContainsText(Matcher matcher) { + final List list = surefireVerifier.loadFile(file, encoding); + for (String line : list) { + if (matcher.matches(line)) { return this; } } - Assert.fail( "Did not find expected message in log" ); + Assert.fail("Did not find expected message in log"); return null; } - public TestFile assertContainsText( String text ) - { - return assertContainsText( containsString( text ) ); + public TestFile assertContainsText(String text) { + return assertContainsText(containsString(text)); } - public TestFile assertNotContainsText( Matcher matcher ) - { - final List list = surefireVerifier.loadFile( file, encoding ); - for ( String line : list ) - { - if ( matcher.matches( line ) ) - { - Assert.fail( "Found unexpected message in log" ); + public TestFile assertNotContainsText(Matcher matcher) { + final List list = surefireVerifier.loadFile(file, encoding); + for (String line : list) { + if (matcher.matches(line)) { + Assert.fail("Found unexpected message in log"); return null; } } return this; } - public TestFile assertNotContainsText( String text ) - { - return assertNotContainsText( containsString( text ) ); + public TestFile assertNotContainsText(String text) { + return assertNotContainsText(containsString(text)); } - public URI toURI() - { + public URI toURI() { return file.toURI(); } - public File getFile() - { + public File getFile() { return file; } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/fixture/TestFramework.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/fixture/TestFramework.java index c544347152..71b70ea15d 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/fixture/TestFramework.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/fixture/TestFramework.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its.fixture; /* @@ -23,7 +41,8 @@ * @author Tibor Digana (tibor17) * @since 2.19 */ -public enum TestFramework -{ - JUNIT4, JUNIT47, TestNG +public enum TestFramework { + JUNIT4, + JUNIT47, + TestNG } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/SpockIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/SpockIT.java index f47963faca..b52a6550d3 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/SpockIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/SpockIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its.jiras; /* @@ -27,15 +45,11 @@ /** * */ -@SuppressWarnings( "checkstyle:magicnumber" ) -public class SpockIT extends SurefireJUnit4IntegrationTestCase -{ +@SuppressWarnings("checkstyle:magicnumber") +public class SpockIT extends SurefireJUnit4IntegrationTestCase { @Test - public void test() - { - assumeJavaMaxVersion( 14d ); - unpack( "junit5-spock" ) - .executeTest() - .verifyErrorFree( 2 ); + public void test() { + assumeJavaMaxVersion(14d); + unpack("junit5-spock").executeTest().verifyErrorFree(2); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1004RunTestFromDependencyJarsTypeAndClassifierIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1004RunTestFromDependencyJarsTypeAndClassifierIT.java index ffc05b202d..c09feec247 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1004RunTestFromDependencyJarsTypeAndClassifierIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1004RunTestFromDependencyJarsTypeAndClassifierIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its.jiras; /* @@ -19,8 +37,6 @@ * under the License. */ -import static org.junit.Assert.assertFalse; - import java.util.Collection; import org.apache.maven.surefire.its.fixture.OutputValidator; @@ -28,31 +44,31 @@ import org.apache.maven.surefire.its.fixture.SurefireLauncher; import org.junit.Test; +import static org.junit.Assert.assertFalse; + /** * */ -public class Surefire1004RunTestFromDependencyJarsTypeAndClassifierIT extends SurefireJUnit4IntegrationTestCase -{ +public class Surefire1004RunTestFromDependencyJarsTypeAndClassifierIT extends SurefireJUnit4IntegrationTestCase { @Test - public void shouldScanAndRunTestsInDependencyJars() throws Exception - { - SurefireLauncher launcher = unpack( "surefire-1004-RunTestFromDependencyJarsTypeAndClassifier" ); - launcher.addGoal( "test" ).addGoal( "install" ); + public void shouldScanAndRunTestsInDependencyJars() throws Exception { + SurefireLauncher launcher = unpack("surefire-1004-RunTestFromDependencyJarsTypeAndClassifier"); + launcher.addGoal("test").addGoal("install"); OutputValidator wholeExecValidator = launcher.executeCurrentGoals(); wholeExecValidator.verifyErrorFreeLog(); - OutputValidator module1 = launcher.getSubProjectValidator( "surefire-1004-module1" ); - module1.assertTestSuiteResults( 3, 0, 0, 0 ); + OutputValidator module1 = launcher.getSubProjectValidator("surefire-1004-module1"); + module1.assertTestSuiteResults(3, 0, 0, 0); // Tests from dependencies - wholeExecValidator.verifyTextInLog( "Running org.acme.tests.TestA" ); - wholeExecValidator.verifyTextInLog( "Running org.acme.classifiedtests.ClassifiedTestA" ); + wholeExecValidator.verifyTextInLog("Running org.acme.tests.TestA"); + wholeExecValidator.verifyTextInLog("Running org.acme.classifiedtests.ClassifiedTestA"); // Tests from module1 to verify classpath - wholeExecValidator.verifyTextInLog( "Running org.acme.tests.ClasspathTest" ); + wholeExecValidator.verifyTextInLog("Running org.acme.tests.ClasspathTest"); // Should not run these tests Collection logLines = wholeExecValidator.loadLogLines(); - assertFalse( logLines.contains( "org.acme.othertests.OtherTestA" ) ); - assertFalse( logLines.contains( "org.acme.tests.TestB" ) ); + assertFalse(logLines.contains("org.acme.othertests.OtherTestA")); + assertFalse(logLines.contains("org.acme.tests.TestB")); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1024VerifyFailsafeIfTestedIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1024VerifyFailsafeIfTestedIT.java index 9db5da8e36..7a2061a8a0 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1024VerifyFailsafeIfTestedIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1024VerifyFailsafeIfTestedIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its.jiras; /* @@ -32,18 +50,13 @@ * @see SUREFIRE-1024 * @since 2.19 */ -public class Surefire1024VerifyFailsafeIfTestedIT - extends SurefireJUnit4IntegrationTestCase -{ +public class Surefire1024VerifyFailsafeIfTestedIT extends SurefireJUnit4IntegrationTestCase { @Test - public void shouldScanAndRunTestsInDependencyJars() throws Exception - { - SurefireLauncher launcher = unpack( "surefire-1024" ); - launcher.executeVerify() - .verifyTextInLog( "class jiras.surefire1024.A1IT#test() dependency to scan" ); + public void shouldScanAndRunTestsInDependencyJars() throws Exception { + SurefireLauncher launcher = unpack("surefire-1024"); + launcher.executeVerify().verifyTextInLog("class jiras.surefire1024.A1IT#test() dependency to scan"); - launcher.getSubProjectValidator( "jiras-surefire-1024-it" ) - .assertIntegrationTestSuiteResults( 1, 0, 0, 0 ); + launcher.getSubProjectValidator("jiras-surefire-1024-it").assertIntegrationTestSuiteResults(1, 0, 0, 0); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1028UnableToRunSingleIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1028UnableToRunSingleIT.java index ec63a8a051..80c3a684c1 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1028UnableToRunSingleIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1028UnableToRunSingleIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its.jiras; /* @@ -41,19 +59,19 @@ * @see SUREFIRE-1028 * @since 2.18 */ -public class Surefire1028UnableToRunSingleIT - extends SurefireJUnit4IntegrationTestCase -{ +public class Surefire1028UnableToRunSingleIT extends SurefireJUnit4IntegrationTestCase { @Test - public void methodFilteringParallelExecution() - { - unpack().setTestToRun( "SomeTest#test" ).parallelClasses().useUnlimitedThreads() - .executeTest().verifyErrorFree( 1 ).verifyTextInLog( "OK!" ); + public void methodFilteringParallelExecution() { + unpack().setTestToRun("SomeTest#test") + .parallelClasses() + .useUnlimitedThreads() + .executeTest() + .verifyErrorFree(1) + .verifyTextInLog("OK!"); } - private SurefireLauncher unpack() - { - return unpack( "surefire-1028-unable-to-run-single-test" ); + private SurefireLauncher unpack() { + return unpack("surefire-1028-unable-to-run-single-test"); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1036NonFilterableJUnitRunnerWithCategoriesIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1036NonFilterableJUnitRunnerWithCategoriesIT.java index ef6388ed71..0565f9074d 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1036NonFilterableJUnitRunnerWithCategoriesIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1036NonFilterableJUnitRunnerWithCategoriesIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its.jiras; /* @@ -19,6 +37,8 @@ * under the License. */ +import java.io.FileNotFoundException; + import org.apache.maven.shared.utils.xml.Xpp3Dom; import org.apache.maven.shared.utils.xml.Xpp3DomBuilder; import org.apache.maven.surefire.its.fixture.OutputValidator; @@ -27,10 +47,8 @@ import org.apache.maven.surefire.its.fixture.TestFile; import org.junit.Test; -import java.io.FileNotFoundException; - -import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; /** @@ -38,35 +56,30 @@ * @see SUREFIRE-1036 * @since 2.18 */ -public class Surefire1036NonFilterableJUnitRunnerWithCategoriesIT - extends SurefireJUnit4IntegrationTestCase -{ +public class Surefire1036NonFilterableJUnitRunnerWithCategoriesIT extends SurefireJUnit4IntegrationTestCase { @Test - public void test() - throws FileNotFoundException - { + public void test() throws FileNotFoundException { OutputValidator validator = unpack().maven().executeTest(); - validator.assertTestSuiteResults( 1, 0, 0, 0 ); - assertFalse( validator.getSurefireReportsXmlFile( - "TEST-jiras.surefire1036.TestSomethingWithMockitoRunner.xml" ).exists() ); - assertFalse( validator.getSurefireReportsXmlFile( "TEST-jiras.surefire1036.TestSomeUnit.xml" ).exists() ); - TestFile reportFile = - validator.getSurefireReportsXmlFile( "TEST-jiras.surefire1036.TestSomeIntegration.xml" ); - assertTestCount( reportFile, 1 ); + validator.assertTestSuiteResults(1, 0, 0, 0); + assertFalse(validator + .getSurefireReportsXmlFile("TEST-jiras.surefire1036.TestSomethingWithMockitoRunner.xml") + .exists()); + assertFalse(validator + .getSurefireReportsXmlFile("TEST-jiras.surefire1036.TestSomeUnit.xml") + .exists()); + TestFile reportFile = validator.getSurefireReportsXmlFile("TEST-jiras.surefire1036.TestSomeIntegration.xml"); + assertTestCount(reportFile, 1); } - private SurefireLauncher unpack() - { - return unpack( "surefire-1036-NonFilterableJUnitRunnerWithCategories" ); + private SurefireLauncher unpack() { + return unpack("surefire-1036-NonFilterableJUnitRunnerWithCategories"); } - private void assertTestCount( TestFile reportFile, int tests ) - throws FileNotFoundException - { - assertTrue( reportFile.exists() ); - Xpp3Dom testResult = Xpp3DomBuilder.build( reportFile.getFileInputStream(), "UTF-8" ); - Xpp3Dom[] children = testResult.getChildren( "testcase" ); - assertEquals( tests, children.length ); + private void assertTestCount(TestFile reportFile, int tests) throws FileNotFoundException { + assertTrue(reportFile.exists()); + Xpp3Dom testResult = Xpp3DomBuilder.build(reportFile.getFileInputStream(), "UTF-8"); + Xpp3Dom[] children = testResult.getChildren("testcase"); + assertEquals(tests, children.length); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1041FailingJUnitRunnerIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1041FailingJUnitRunnerIT.java index 8c23d75a20..383ef51bb2 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1041FailingJUnitRunnerIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1041FailingJUnitRunnerIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its.jiras; /* @@ -27,15 +45,12 @@ * * @author Andreas Gudian */ -public class Surefire1041FailingJUnitRunnerIT - extends SurefireJUnit4IntegrationTestCase -{ +public class Surefire1041FailingJUnitRunnerIT extends SurefireJUnit4IntegrationTestCase { @Test - public void reportErrorInJUnitRunnerAsTestError() - { - unpack( "surefire-1041-exception-in-junit-runner" ) - .mavenTestFailureIgnore( true ) + public void reportErrorInJUnitRunnerAsTestError() { + unpack("surefire-1041-exception-in-junit-runner") + .mavenTestFailureIgnore(true) .executeTest() - .assertTestSuiteResults( 1, 1, 0, 0 ); + .assertTestSuiteResults(1, 1, 0, 0); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1053SystemPropertiesIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1053SystemPropertiesIT.java index b3ed7444ae..a04edf3ef1 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1053SystemPropertiesIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1053SystemPropertiesIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its.jiras; /* @@ -31,42 +49,37 @@ * @see SUREFIRE-1053 * @since 2.18 */ -public class Surefire1053SystemPropertiesIT - extends SurefireJUnit4IntegrationTestCase -{ +public class Surefire1053SystemPropertiesIT extends SurefireJUnit4IntegrationTestCase { @Test - public void checkWarningsFileEncoding() - { - unpack().sysProp( "file.encoding", "ISO-8859-1" ) - .executeTest() - .verifyErrorFree( 1 ) - .verifyTextInLog( "file.encoding cannot be set as system property, use -D" - + "file.encoding=... instead" ); + public void checkWarningsFileEncoding() { + unpack().sysProp("file.encoding", "ISO-8859-1") + .executeTest() + .verifyErrorFree(1) + .verifyTextInLog("file.encoding cannot be set as system property, use -D" + + "file.encoding=... instead"); } + @Test - public void checkWarningsSysPropTwice() throws Exception - { - OutputValidator validator = unpack() - .argLine( "-DmyArg=myVal2 -Dfile.encoding=ISO-8859-1" ) - .sysProp( "file.encoding", "ISO-8859-1" ) - .executeTest() - .verifyErrorFree( 1 ) - .verifyTextInLog( "The system property myArg is configured twice! " - + "The property appears in and any of , " - + " or user property." ); + public void checkWarningsSysPropTwice() throws Exception { + OutputValidator validator = unpack().argLine("-DmyArg=myVal2 -Dfile.encoding=ISO-8859-1") + .sysProp("file.encoding", "ISO-8859-1") + .executeTest() + .verifyErrorFree(1) + .verifyTextInLog("The system property myArg is configured twice! " + + "The property appears in and any of , " + + " or user property."); - for ( String line : validator.loadLogLines() ) - { - assertFalse( "no warning for file.encoding not in argLine", - line.contains( "file.encoding cannot be set as system property, use " ) ); - assertFalse( "no warning for double definition of file.encoding", - line.contains( "The system property file.encoding is configured twice!" ) ); + for (String line : validator.loadLogLines()) { + assertFalse( + "no warning for file.encoding not in argLine", + line.contains("file.encoding cannot be set as system property, use ")); + assertFalse( + "no warning for double definition of file.encoding", + line.contains("The system property file.encoding is configured twice!")); } - } - private SurefireLauncher unpack() - { - return unpack( "surefire-1053-system-properties" ); + private SurefireLauncher unpack() { + return unpack("surefire-1053-system-properties"); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1055CorrectConcurrentTestCountIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1055CorrectConcurrentTestCountIT.java index 9326b367d3..9eba24a52e 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1055CorrectConcurrentTestCountIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1055CorrectConcurrentTestCountIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its.jiras; /* @@ -28,15 +46,12 @@ * * @author Kristian Rosenvold */ -@SuppressWarnings( "checkstyle:magicnumber" ) -public class Surefire1055CorrectConcurrentTestCountIT - extends SurefireJUnit4IntegrationTestCase -{ +@SuppressWarnings("checkstyle:magicnumber") +public class Surefire1055CorrectConcurrentTestCountIT extends SurefireJUnit4IntegrationTestCase { @Test - public void testTestNgAndJUnitTogether() - { - OutputValidator outputValidator = unpack( "surefire-1055-parallelTestCount" ).executeTest(); - outputValidator.assertTestSuiteResults( 21, 0, 0, 0 ); - + public void testTestNgAndJUnitTogether() { + OutputValidator outputValidator = + unpack("surefire-1055-parallelTestCount").executeTest(); + outputValidator.assertTestSuiteResults(21, 0, 0, 0); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1080ParallelForkDoubleTestIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1080ParallelForkDoubleTestIT.java index d6a38fa7ce..16ab621430 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1080ParallelForkDoubleTestIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1080ParallelForkDoubleTestIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its.jiras; /* @@ -38,17 +56,13 @@ * @see SUREFIRE-1080 * @since 2.18 */ -public class Surefire1080ParallelForkDoubleTestIT - extends SurefireJUnit4IntegrationTestCase -{ +public class Surefire1080ParallelForkDoubleTestIT extends SurefireJUnit4IntegrationTestCase { @Test - public void test() - { - unpack().executeTest().assertTestSuiteResults( 9 ); + public void test() { + unpack().executeTest().assertTestSuiteResults(9); } - private SurefireLauncher unpack() - { - return unpack( "surefire-1080-parallel-fork-double-test" ); + private SurefireLauncher unpack() { + return unpack("surefire-1080-parallel-fork-double-test"); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1082ParallelJUnitParameterizedIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1082ParallelJUnitParameterizedIT.java index 5bac50666b..2134657020 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1082ParallelJUnitParameterizedIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1082ParallelJUnitParameterizedIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its.jiras; /* @@ -19,6 +37,10 @@ * under the License. */ +import java.util.Collection; +import java.util.Set; +import java.util.TreeSet; + import org.apache.maven.it.VerificationException; import org.apache.maven.surefire.its.fixture.OutputValidator; import org.apache.maven.surefire.its.fixture.SurefireJUnit4IntegrationTestCase; @@ -26,10 +48,6 @@ import org.apache.maven.surefire.its.fixture.TestFile; import org.junit.Test; -import java.util.Collection; -import java.util.Set; -import java.util.TreeSet; - import static java.nio.charset.StandardCharsets.UTF_8; import static org.apache.maven.surefire.its.fixture.IsRegex.regex; import static org.hamcrest.CoreMatchers.startsWith; @@ -43,115 +61,108 @@ * @see SUREFIRE-1082 * @since 2.18 */ -public class Surefire1082ParallelJUnitParameterizedIT - extends SurefireJUnit4IntegrationTestCase -{ - private static Set printOnlyTestLinesFromOutFile( OutputValidator validator ) - { - TestFile report = validator.getSurefireReportsFile( "jiras.surefire1082.Jira1082Test-output.txt" ); +public class Surefire1082ParallelJUnitParameterizedIT extends SurefireJUnit4IntegrationTestCase { + private static Set printOnlyTestLinesFromOutFile(OutputValidator validator) { + TestFile report = validator.getSurefireReportsFile("jiras.surefire1082.Jira1082Test-output.txt"); report.assertFileExists(); - return printOnlyTestLines( validator.loadFile( report.getFile(), UTF_8 ) ); + return printOnlyTestLines(validator.loadFile(report.getFile(), UTF_8)); } - private static Set printOnlyTestLines( Collection logs ) - { + private static Set printOnlyTestLines(Collection logs) { Set log = new TreeSet<>(); - for ( String line : logs ) - { - if ( line.startsWith( "class jiras.surefire1082." ) ) - { - log.add( line ); + for (String line : logs) { + if (line.startsWith("class jiras.surefire1082.")) { + log.add(line); } } return log; } - private static void assertParallelRun( Set log ) - { - assertThat( log.size(), is( 4 ) ); + private static void assertParallelRun(Set log) { + assertThat(log.size(), is(4)); Set expectedLogs1 = new TreeSet<>(); - expectedLogs1.add( "class jiras.surefire1082.Jira1082Test a 0 pool-[\\d]+-thread-1" ); - expectedLogs1.add( "class jiras.surefire1082.Jira1082Test b 0 pool-[\\d]+-thread-1" ); - expectedLogs1.add( "class jiras.surefire1082.Jira1082Test a 1 pool-[\\d]+-thread-2" ); - expectedLogs1.add( "class jiras.surefire1082.Jira1082Test b 1 pool-[\\d]+-thread-2" ); + expectedLogs1.add("class jiras.surefire1082.Jira1082Test a 0 pool-[\\d]+-thread-1"); + expectedLogs1.add("class jiras.surefire1082.Jira1082Test b 0 pool-[\\d]+-thread-1"); + expectedLogs1.add("class jiras.surefire1082.Jira1082Test a 1 pool-[\\d]+-thread-2"); + expectedLogs1.add("class jiras.surefire1082.Jira1082Test b 1 pool-[\\d]+-thread-2"); Set expectedLogs2 = new TreeSet<>(); - expectedLogs2.add( "class jiras.surefire1082.Jira1082Test a 1 pool-[\\d]+-thread-1" ); - expectedLogs2.add( "class jiras.surefire1082.Jira1082Test b 1 pool-[\\d]+-thread-1" ); - expectedLogs2.add( "class jiras.surefire1082.Jira1082Test a 0 pool-[\\d]+-thread-2" ); - expectedLogs2.add( "class jiras.surefire1082.Jira1082Test b 0 pool-[\\d]+-thread-2" ); + expectedLogs2.add("class jiras.surefire1082.Jira1082Test a 1 pool-[\\d]+-thread-1"); + expectedLogs2.add("class jiras.surefire1082.Jira1082Test b 1 pool-[\\d]+-thread-1"); + expectedLogs2.add("class jiras.surefire1082.Jira1082Test a 0 pool-[\\d]+-thread-2"); + expectedLogs2.add("class jiras.surefire1082.Jira1082Test b 0 pool-[\\d]+-thread-2"); - assertThat( log, anyOf( regex( expectedLogs1 ), regex( expectedLogs2 ) ) ); + assertThat(log, anyOf(regex(expectedLogs1), regex(expectedLogs2))); } @Test - public void checkClassesRunParallel() - throws VerificationException - { - OutputValidator validator = unpack().setTestToRun( "Jira1082Test" ) - .parallelClasses() - .useUnlimitedThreads() - .executeTest() - .verifyErrorFree( 4 ); - - validator.getSurefireReportsXmlFile( "TEST-jiras.surefire1082.Jira1082Test.xml" ) + public void checkClassesRunParallel() throws VerificationException { + OutputValidator validator = unpack().setTestToRun("Jira1082Test") + .parallelClasses() + .useUnlimitedThreads() + .executeTest() + .verifyErrorFree(4); + + validator + .getSurefireReportsXmlFile("TEST-jiras.surefire1082.Jira1082Test.xml") .assertFileExists(); - validator.assertThatLogLine( containsString( "Running jiras.surefire1082.Jira1082Test" ), is( 1 ) ); + validator.assertThatLogLine(containsString("Running jiras.surefire1082.Jira1082Test"), is(1)); - Set log = new TreeSet<>( validator.loadLogLines( startsWith( "class jiras.surefire1082." ) ) ); - assertParallelRun( log ); + Set log = new TreeSet<>(validator.loadLogLines(startsWith("class jiras.surefire1082."))); + assertParallelRun(log); } @Test - public void checkOutFileClassesRunParallel() - throws VerificationException - { - OutputValidator validator = unpack().redirectToFile( true ) - .setTestToRun( "Jira1082Test" ) - .parallelClasses() - .useUnlimitedThreads() - .executeTest() - .verifyErrorFree( 4 ); - - validator.getSurefireReportsXmlFile( "TEST-jiras.surefire1082.Jira1082Test.xml" ) + public void checkOutFileClassesRunParallel() throws VerificationException { + OutputValidator validator = unpack().redirectToFile(true) + .setTestToRun("Jira1082Test") + .parallelClasses() + .useUnlimitedThreads() + .executeTest() + .verifyErrorFree(4); + + validator + .getSurefireReportsXmlFile("TEST-jiras.surefire1082.Jira1082Test.xml") .assertFileExists(); - validator.assertThatLogLine( containsString( "Running jiras.surefire1082.Jira1082Test" ), is( 1 ) ); + validator.assertThatLogLine(containsString("Running jiras.surefire1082.Jira1082Test"), is(1)); - Set log = printOnlyTestLinesFromOutFile( validator ); - assertParallelRun( log ); + Set log = printOnlyTestLinesFromOutFile(validator); + assertParallelRun(log); } @Test - public void shouldRunTwo() throws VerificationException - { - OutputValidator validator = unpack().redirectToFile( true ) - .parallelClasses() - .useUnlimitedThreads() - .executeTest() - .verifyErrorFree( 8 ); - - validator.getSurefireReportsXmlFile( "TEST-jiras.surefire1082.Jira1082Test.xml" ) + public void shouldRunTwo() throws VerificationException { + OutputValidator validator = unpack().redirectToFile(true) + .parallelClasses() + .useUnlimitedThreads() + .executeTest() + .verifyErrorFree(8); + + validator + .getSurefireReportsXmlFile("TEST-jiras.surefire1082.Jira1082Test.xml") .assertFileExists(); - validator.getSurefireReportsXmlFile( "TEST-jiras.surefire1082.Jira1264Test.xml" ) + validator + .getSurefireReportsXmlFile("TEST-jiras.surefire1082.Jira1264Test.xml") .assertFileExists(); - validator.getSurefireReportsFile( "jiras.surefire1082.Jira1082Test-output.txt" ) + validator + .getSurefireReportsFile("jiras.surefire1082.Jira1082Test-output.txt") .assertFileExists(); - validator.getSurefireReportsFile( "jiras.surefire1082.Jira1264Test-output.txt" ) + validator + .getSurefireReportsFile("jiras.surefire1082.Jira1264Test-output.txt") .assertFileExists(); - validator.assertThatLogLine( containsString( "Running jiras.surefire1082.Jira1082Test" ), is( 1 ) ); + validator.assertThatLogLine(containsString("Running jiras.surefire1082.Jira1082Test"), is(1)); - validator.assertThatLogLine( containsString( "Running jiras.surefire1082.Jira1264Test" ), is( 1 ) ); + validator.assertThatLogLine(containsString("Running jiras.surefire1082.Jira1264Test"), is(1)); } - private SurefireLauncher unpack() - { - return unpack( "surefire-1082-parallel-junit-parameterized" ); + private SurefireLauncher unpack() { + return unpack("surefire-1082-parallel-junit-parameterized"); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1095NpeInRunListenerIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1095NpeInRunListenerIT.java index 91df0af47f..0807279c50 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1095NpeInRunListenerIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1095NpeInRunListenerIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its.jiras; /* @@ -23,7 +41,7 @@ import org.apache.maven.surefire.its.fixture.SurefireLauncher; import org.junit.Test; -@SuppressWarnings( { "javadoc", "checkstyle:javadoctype", "checkstyle:linelength" } ) +@SuppressWarnings({"javadoc", "checkstyle:javadoctype", "checkstyle:linelength"}) /** * * In the surefire plugin, it is possible to specify one or more RunListener when running tests with JUnit. @@ -45,22 +63,19 @@ * @see * @since 2.18 */ -public final class Surefire1095NpeInRunListenerIT - extends SurefireJUnit4IntegrationTestCase -{ +public final class Surefire1095NpeInRunListenerIT extends SurefireJUnit4IntegrationTestCase { /** * Method Request.classes( String, Class[] ); exists in JUnit 4.0 - 4.4 * See JUnit4Reflector. */ @Test - public void testRunStartedWithJUnit40() - { - unpack().setJUnitVersion( "4.0" ) - .executeTest() - .verifyErrorFree( 1 ) - .verifyTextInLog( "Running JUnit 4.0" ) - .verifyTextInLog( "testRunStarted [jiras.surefire1095.SomeTest]" ); + public void testRunStartedWithJUnit40() { + unpack().setJUnitVersion("4.0") + .executeTest() + .verifyErrorFree(1) + .verifyTextInLog("Running JUnit 4.0") + .verifyTextInLog("testRunStarted [jiras.surefire1095.SomeTest]"); } /** @@ -68,27 +83,24 @@ public void testRunStartedWithJUnit40() * See JUnit4Reflector. */ @Test - public void testRunStartedWithJUnit45() - { - unpack().setJUnitVersion( "4.5" ) - .executeTest() - .verifyErrorFree( 1 ) - .verifyTextInLog( "Running JUnit 4.5" ) - .verifyTextInLog( "testRunStarted [jiras.surefire1095.SomeTest]" ); + public void testRunStartedWithJUnit45() { + unpack().setJUnitVersion("4.5") + .executeTest() + .verifyErrorFree(1) + .verifyTextInLog("Running JUnit 4.5") + .verifyTextInLog("testRunStarted [jiras.surefire1095.SomeTest]"); } @Test - public void testRunStartedWithJUnit47() - { - unpack().setJUnitVersion( "4.7" ) - .executeTest() - .verifyErrorFree( 1 ) - .verifyTextInLog( "Running JUnit 4.7" ) - .verifyTextInLog( "testRunStarted [jiras.surefire1095.SomeTest]" ); + public void testRunStartedWithJUnit47() { + unpack().setJUnitVersion("4.7") + .executeTest() + .verifyErrorFree(1) + .verifyTextInLog("Running JUnit 4.7") + .verifyTextInLog("testRunStarted [jiras.surefire1095.SomeTest]"); } - private SurefireLauncher unpack() - { - return unpack( "surefire-1095-npe-in-runlistener" ); + private SurefireLauncher unpack() { + return unpack("surefire-1095-npe-in-runlistener"); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1098BalancedRunOrderIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1098BalancedRunOrderIT.java index 00546ef67b..4560dd5cb9 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1098BalancedRunOrderIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1098BalancedRunOrderIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its.jiras; /* @@ -19,20 +37,20 @@ * under the License. */ +import java.util.ArrayList; +import java.util.Collections; +import java.util.Iterator; +import java.util.List; + import org.apache.maven.it.VerificationException; import org.apache.maven.surefire.its.fixture.OutputValidator; import org.apache.maven.surefire.its.fixture.SurefireJUnit4IntegrationTestCase; import org.apache.maven.surefire.its.fixture.SurefireLauncher; import org.junit.Test; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Iterator; -import java.util.List; - -import static org.junit.Assert.assertThat; -import static org.hamcrest.core.Is.is; import static org.hamcrest.core.AnyOf.anyOf; +import static org.hamcrest.core.Is.is; +import static org.junit.Assert.assertThat; /** * The purpose of this IT is to assert that the run order of test classes is according to the settings:
    @@ -45,69 +63,68 @@ * @see
    SUREFIRE-1098 * @since 2.18 */ -public class Surefire1098BalancedRunOrderIT extends SurefireJUnit4IntegrationTestCase -{ +public class Surefire1098BalancedRunOrderIT extends SurefireJUnit4IntegrationTestCase { @Test - public void reorderedParallelClasses() throws VerificationException - { + public void reorderedParallelClasses() throws VerificationException { // first execution - unpack().setLogFileName( "log1.txt" ) + unpack().setLogFileName("log1.txt") // .runOrder( "balanced" ) call it in 3.x and remove it in surefire-1098-balanced-runorder/pom.xml // as soon as there is prefix available "failsafe" and "surefire" in system property for this parameter. - .parallelClasses().threadCount( 2 ).disablePerCoreThreadCount().executeTest().verifyErrorFree( 4 ); - + .parallelClasses() + .threadCount(2) + .disablePerCoreThreadCount() + .executeTest() + .verifyErrorFree(4); // and second from new instance - if we use the same instance - hasExecutedBefore return true - OutputValidator validator = unpack().setLogFileName( "log2.txt" ) + OutputValidator validator = unpack().setLogFileName("log2.txt") // .runOrder( "balanced" ) call it in 3.x and remove it in surefire-1098-balanced-runorder/pom.xml // as soon as there is prefix available "failsafe" and "surefire" in system property for this parameter. - .parallelClasses().threadCount( 2 ).disablePerCoreThreadCount().executeTest().verifyErrorFree( 4 ); + .parallelClasses() + .threadCount(2) + .disablePerCoreThreadCount() + .executeTest() + .verifyErrorFree(4); - List log = printOnlyTestLines( validator ); - assertThat( log.size(), is( 4 ) ); - Collections.sort( log ); - final int[] threadPoolIdsOfLongestTest = extractThreadPoolIds( log.get( 3 ) ); + List log = printOnlyTestLines(validator); + assertThat(log.size(), is(4)); + Collections.sort(log); + final int[] threadPoolIdsOfLongestTest = extractThreadPoolIds(log.get(3)); final int pool = threadPoolIdsOfLongestTest[0]; int thread = threadPoolIdsOfLongestTest[1]; - assertThat( thread, anyOf( is( 1 ), is( 2 ) ) ); + assertThat(thread, anyOf(is(1), is(2))); thread = thread == 1 ? 2 : 1; // If the longest test class DTest is running in pool-2-thread-1, the others should run in pool-2-thread-2 // and vice versa. - assertThat( log.get( 0 ), is( testLine( "A", pool, thread ) ) ); - assertThat( log.get( 1 ), is( testLine( "B", pool, thread ) ) ); - assertThat( log.get( 2 ), is( testLine( "C", pool, thread ) ) ); + assertThat(log.get(0), is(testLine("A", pool, thread))); + assertThat(log.get(1), is(testLine("B", pool, thread))); + assertThat(log.get(2), is(testLine("C", pool, thread))); } - private SurefireLauncher unpack() - { - return unpack( "surefire-1098-balanced-runorder" ); + private SurefireLauncher unpack() { + return unpack("surefire-1098-balanced-runorder"); } - private static List printOnlyTestLines( OutputValidator validator ) throws VerificationException - { - List log = new ArrayList<>( validator.loadLogLines() ); - for ( Iterator it = log.iterator(); it.hasNext(); ) - { + private static List printOnlyTestLines(OutputValidator validator) throws VerificationException { + List log = new ArrayList<>(validator.loadLogLines()); + for (Iterator it = log.iterator(); it.hasNext(); ) { String line = it.next(); - if ( !line.startsWith( "class jiras.surefire1098." ) ) - { + if (!line.startsWith("class jiras.surefire1098.")) { it.remove(); } } return log; } - private static int[] extractThreadPoolIds( String logLine ) - { - //Example to parse "class jiras.surefire1098.DTest pool-2-thread-1" into {2, 1}. - String t = logLine.split( " " )[2]; - String[] ids = t.split( "-" ); - return new int[] {Integer.parseInt( ids[1] ), Integer.parseInt( ids[3] )}; + private static int[] extractThreadPoolIds(String logLine) { + // Example to parse "class jiras.surefire1098.DTest pool-2-thread-1" into {2, 1}. + String t = logLine.split(" ")[2]; + String[] ids = t.split("-"); + return new int[] {Integer.parseInt(ids[1]), Integer.parseInt(ids[3])}; } - private String testLine( String test, int pool, int thread ) - { - return String.format( "class jiras.surefire1098.%sTest pool-%d-thread-%d", test, pool, thread ); + private String testLine(String test, int pool, int thread) { + return String.format("class jiras.surefire1098.%sTest pool-%d-thread-%d", test, pool, thread); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1122ParallelAndFlakyTestsIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1122ParallelAndFlakyTestsIT.java index 5f8b561188..fe854ba796 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1122ParallelAndFlakyTestsIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1122ParallelAndFlakyTestsIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its.jiras; /* @@ -26,32 +44,25 @@ * @author agudian * @see SUREFIRE-1122 */ -public class Surefire1122ParallelAndFlakyTestsIT - extends SurefireJUnit4IntegrationTestCase -{ +public class Surefire1122ParallelAndFlakyTestsIT extends SurefireJUnit4IntegrationTestCase { @Test - public void nonParallelCreatesCorrectReport() - { - unpack( "surefire-1122-parallel-and-flakyTests" ) - .executeTest() - .assertTestSuiteResults( 2, 0, 0, 0, 1 ); + public void nonParallelCreatesCorrectReport() { + unpack("surefire-1122-parallel-and-flakyTests").executeTest().assertTestSuiteResults(2, 0, 0, 0, 1); } @Test - public void parallelCreatesCorrectReport() - { - unpack( "surefire-1122-parallel-and-flakyTests" ) - .activateProfile( "parallel" ) - .executeTest() - .assertTestSuiteResults( 2, 0, 0, 0, 1 ); + public void parallelCreatesCorrectReport() { + unpack("surefire-1122-parallel-and-flakyTests") + .activateProfile("parallel") + .executeTest() + .assertTestSuiteResults(2, 0, 0, 0, 1); } @Test - public void parallelCreatesCorrectReportFork() - { - unpack( "surefire-1122-parallel-and-flakyTests" ) - .activateProfile( "parallel-one-fork" ) + public void parallelCreatesCorrectReportFork() { + unpack("surefire-1122-parallel-and-flakyTests") + .activateProfile("parallel-one-fork") .executeTest() - .assertTestSuiteResults( 2, 0, 0, 0, 1 ); + .assertTestSuiteResults(2, 0, 0, 0, 1); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1135ImproveIgnoreMessageForTestNGIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1135ImproveIgnoreMessageForTestNGIT.java index fe1ec8f60e..8b02657ad8 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1135ImproveIgnoreMessageForTestNGIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1135ImproveIgnoreMessageForTestNGIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its.jiras; /* @@ -19,14 +37,6 @@ * under the License. */ -import static org.apache.maven.shared.utils.xml.Xpp3DomBuilder.build; -import static org.hamcrest.Matchers.arrayWithSize; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.isEmptyOrNullString; -import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertThat; - import java.io.FileNotFoundException; import org.apache.maven.shared.utils.xml.Xpp3Dom; @@ -35,117 +45,115 @@ import org.apache.maven.surefire.its.fixture.SurefireLauncher; import org.junit.Test; +import static org.apache.maven.shared.utils.xml.Xpp3DomBuilder.build; +import static org.hamcrest.Matchers.arrayWithSize; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.isEmptyOrNullString; +import static org.hamcrest.Matchers.nullValue; +import static org.junit.Assert.assertThat; + /** * Test surefire-report on TestNG test * * @author Michal Bocek */ -public class Surefire1135ImproveIgnoreMessageForTestNGIT extends SurefireJUnit4IntegrationTestCase -{ +public class Surefire1135ImproveIgnoreMessageForTestNGIT extends SurefireJUnit4IntegrationTestCase { - private enum ResultType - { - SKIPPED( "skipped" ), - FAILURE( "failure" ); + private enum ResultType { + SKIPPED("skipped"), + FAILURE("failure"); private final String type; - ResultType( String type ) - { + ResultType(String type) { this.type = type; } - public String getType() - { + public String getType() { return type; } } @Test - public void testNgReport688() throws Exception - { - testNgReport( "6.8.8", null, ResultType.SKIPPED, "Skip test", + public void testNgReport688() throws Exception { + testNgReport( + "6.8.8", + null, + ResultType.SKIPPED, + "Skip test", /*"org.testng.SkipException"*/ null, - /*"SkipExceptionReportTest.java:30"*/ null ); + /*"SkipExceptionReportTest.java:30"*/ null); } @Test - public void testNgReport57() throws Exception - { - testNgReport( "5.7", "jdk15", ResultType.SKIPPED, "Skip test", + public void testNgReport57() throws Exception { + testNgReport( + "5.7", + "jdk15", + ResultType.SKIPPED, + "Skip test", /*"org.testng.SkipException"*/ null, - /*"SkipExceptionReportTest.java:30"*/ null ); + /*"SkipExceptionReportTest.java:30"*/ null); } - private void testNgReport( String version, String classifier, ResultType resultType, String message, String type, - String stackTrace ) throws Exception - { - OutputValidator outputValidator = runTest( version, classifier, resultType, - "/surefire-1135-improve-ignore-message-for-testng" ); + private void testNgReport( + String version, String classifier, ResultType resultType, String message, String type, String stackTrace) + throws Exception { + OutputValidator outputValidator = + runTest(version, classifier, resultType, "/surefire-1135-improve-ignore-message-for-testng"); - Xpp3Dom[] children = readTests( outputValidator, "testng.SkipExceptionReportTest" ); - assertThat( "Report should contains only one test case", children.length, is( 1 ) ); + Xpp3Dom[] children = readTests(outputValidator, "testng.SkipExceptionReportTest"); + assertThat("Report should contains only one test case", children.length, is(1)); Xpp3Dom test = children[0]; - assertThat( "Not expected classname", test.getAttribute( "classname" ), - is( "testng.SkipExceptionReportTest" ) ); + assertThat("Not expected classname", test.getAttribute("classname"), is("testng.SkipExceptionReportTest")); - assertThat( "Not expected test name", test.getAttribute( "name" ), is( "testSkipException" ) ); + assertThat("Not expected test name", test.getAttribute("name"), is("testSkipException")); - children = test.getChildren( resultType.getType() ); - assertThat( "Test should contains only one " + resultType.getType() + " element", children, - is( arrayWithSize( 1 ) ) ); + children = test.getChildren(resultType.getType()); + assertThat( + "Test should contains only one " + resultType.getType() + " element", children, is(arrayWithSize(1))); Xpp3Dom result = children[0]; - if ( message == null ) - { - assertThat( "Subelement message attribute must be null", result.getAttribute( "message" ), - is( nullValue() ) ); - } - else - { - assertThat( "Subelement should contains message attribute", result.getAttribute( "message" ), - is( message ) ); + if (message == null) { + assertThat("Subelement message attribute must be null", result.getAttribute("message"), is(nullValue())); + } else { + assertThat("Subelement should contains message attribute", result.getAttribute("message"), is(message)); } - if ( type == null ) - { - assertThat( "Subelement type attribute must be null", result.getAttribute( "type" ), is( nullValue() ) ); - } - else - { - assertThat( "Subelement should contains type attribute", result.getAttribute( "type" ), is( type ) ); + if (type == null) { + assertThat("Subelement type attribute must be null", result.getAttribute("type"), is(nullValue())); + } else { + assertThat("Subelement should contains type attribute", result.getAttribute("type"), is(type)); } - if ( stackTrace == null ) - { - assertThat( "Element body must be null", result.getValue(), isEmptyOrNullString() ); - } - else - { - assertThat( "Element body must contains", result.getValue(), containsString( stackTrace ) ); + if (stackTrace == null) { + assertThat("Element body must be null", result.getValue(), isEmptyOrNullString()); + } else { + assertThat("Element body must contains", result.getValue(), containsString(stackTrace)); } } - private OutputValidator runTest( String version, String classifier, ResultType resultType, String resource ) - { - int skipped = ResultType.SKIPPED.equals( resultType ) ? 1 : 0; - int failure = ResultType.FAILURE.equals( resultType ) ? 1 : 0; + private OutputValidator runTest(String version, String classifier, ResultType resultType, String resource) { + int skipped = ResultType.SKIPPED.equals(resultType) ? 1 : 0; + int failure = ResultType.FAILURE.equals(resultType) ? 1 : 0; - SurefireLauncher launcher = unpack( resource ).sysProp( "testNgVersion", version ); + SurefireLauncher launcher = unpack(resource).sysProp("testNgVersion", version); - if ( classifier != null ) - { - launcher.sysProp( "testNgClassifier", classifier ); + if (classifier != null) { + launcher.sysProp("testNgClassifier", classifier); } - return launcher.addSurefireReportGoal().executeCurrentGoals().assertTestSuiteResults( 1, 0, failure, skipped ); + return launcher.addSurefireReportGoal().executeCurrentGoals().assertTestSuiteResults(1, 0, failure, skipped); } - private static Xpp3Dom[] readTests( OutputValidator validator, String className ) throws FileNotFoundException - { + private static Xpp3Dom[] readTests(OutputValidator validator, String className) throws FileNotFoundException { Xpp3Dom testResult = build( - validator.getSurefireReportsXmlFile( "TEST-" + className + ".xml" ).getFileInputStream(), "UTF-8" ); - return testResult.getChildren( "testcase" ); + validator + .getSurefireReportsXmlFile("TEST-" + className + ".xml") + .getFileInputStream(), + "UTF-8"); + return testResult.getChildren("testcase"); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1136CwdPropagationInForkedModeIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1136CwdPropagationInForkedModeIT.java index 8aaeceae83..3310d6af36 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1136CwdPropagationInForkedModeIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1136CwdPropagationInForkedModeIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its.jiras; /* @@ -31,13 +49,11 @@ * * @author Norbert Wnuk */ -public class Surefire1136CwdPropagationInForkedModeIT - extends SurefireJUnit4IntegrationTestCase -{ +public class Surefire1136CwdPropagationInForkedModeIT extends SurefireJUnit4IntegrationTestCase { @Test - public void testTestNgAndJUnitTogether() - { - OutputValidator outputValidator = unpack( "surefire-1136-cwd-propagation-in-forked-mode" ).executeTest(); - outputValidator.assertTestSuiteResults( 1, 0, 0, 0 ); + public void testTestNgAndJUnitTogether() { + OutputValidator outputValidator = + unpack("surefire-1136-cwd-propagation-in-forked-mode").executeTest(); + outputValidator.assertTestSuiteResults(1, 0, 0, 0); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1144XmlRunTimeIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1144XmlRunTimeIT.java index 8902291872..d74b25d6f3 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1144XmlRunTimeIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1144XmlRunTimeIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its.jiras; /* @@ -19,13 +37,13 @@ * under the License. */ +import java.util.List; + import org.apache.maven.plugins.surefire.report.ReportTestSuite; import org.apache.maven.surefire.its.fixture.OutputValidator; import org.apache.maven.surefire.its.fixture.SurefireJUnit4IntegrationTestCase; import org.junit.Test; -import java.util.List; - import static org.apache.maven.surefire.its.fixture.HelperAssertions.extractReports; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.greaterThanOrEqualTo; @@ -37,22 +55,20 @@ * * @author Lamyaa Eloussi */ -@SuppressWarnings( "checkstyle:magicnumber" ) -public class Surefire1144XmlRunTimeIT - extends SurefireJUnit4IntegrationTestCase -{ +@SuppressWarnings("checkstyle:magicnumber") +public class Surefire1144XmlRunTimeIT extends SurefireJUnit4IntegrationTestCase { @Test - public void testXmlRunTime() - { - OutputValidator outputValidator = unpack( "/surefire-1144-xml-runtime" ).forkOnce().executeTest(); + public void testXmlRunTime() { + OutputValidator outputValidator = + unpack("/surefire-1144-xml-runtime").forkOnce().executeTest(); - List reports = extractReports( outputValidator.getBaseDir() ); - assertThat( reports, hasSize( 1 ) ); + List reports = extractReports(outputValidator.getBaseDir()); + assertThat(reports, hasSize(1)); - ReportTestSuite report = reports.get( 0 ); + ReportTestSuite report = reports.get(0); float xmlTime = report.getTimeElapsed(); - assertThat( xmlTime, is( greaterThanOrEqualTo( 1.6f ) ) ); //include beforeClass and afterClass - outputValidator.verifyTextInLog( Float.toString( xmlTime ) ); //same time in console + assertThat(xmlTime, is(greaterThanOrEqualTo(1.6f))); // include beforeClass and afterClass + outputValidator.verifyTextInLog(Float.toString(xmlTime)); // same time in console } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1146RerunFailedAndParameterizedIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1146RerunFailedAndParameterizedIT.java index a1c5666553..1c2d4683ba 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1146RerunFailedAndParameterizedIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1146RerunFailedAndParameterizedIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its.jiras; /* @@ -26,64 +44,73 @@ /** * @see SUREFIRE-1146 */ -public class Surefire1146RerunFailedAndParameterizedIT - extends SurefireJUnit4IntegrationTestCase -{ - +public class Surefire1146RerunFailedAndParameterizedIT extends SurefireJUnit4IntegrationTestCase { + @Test - public void testsAreRerun() - { - OutputValidator outputValidator = unpack( "surefire-1146-rerunFailingTests-with-Parameterized" ).executeTest(); - verify( outputValidator, 8, 0, 0, 0, 5 ); + public void testsAreRerun() { + OutputValidator outputValidator = + unpack("surefire-1146-rerunFailingTests-with-Parameterized").executeTest(); + verify(outputValidator, 8, 0, 0, 0, 5); } - @SuppressWarnings( "checkstyle:linelength" ) - private void verify( OutputValidator outputValidator, int run, int failures, int errors, int skipped, int flakes ) - { - outputValidator.verifyTextInLog( "Flakes:" ); - outputValidator.verifyTextInLog( "jiras.surefire1146.CustomDescriptionParameterizedTest.flakyTest[0: (Test11); Test12; Test13;]" ); - outputValidator.verifyTextInLog( "Run 1: CustomDescriptionParameterizedTest.flakyTest:" ); - outputValidator.verifyTextInLog( "Run 2: CustomDescriptionParameterizedTest.flakyTest:" ); - outputValidator.verifyTextInLog( "Run 3: PASS" ); + @SuppressWarnings("checkstyle:linelength") + private void verify(OutputValidator outputValidator, int run, int failures, int errors, int skipped, int flakes) { + outputValidator.verifyTextInLog("Flakes:"); + outputValidator.verifyTextInLog( + "jiras.surefire1146.CustomDescriptionParameterizedTest.flakyTest[0: (Test11); Test12; Test13;]"); + outputValidator.verifyTextInLog("Run 1: CustomDescriptionParameterizedTest.flakyTest:"); + outputValidator.verifyTextInLog("Run 2: CustomDescriptionParameterizedTest.flakyTest:"); + outputValidator.verifyTextInLog("Run 3: PASS"); + + outputValidator + .getSurefireReportsXmlFile("TEST-jiras.surefire1146.CustomDescriptionParameterizedTest.xml") + .assertContainsText( + "SUREFIRE-1158 * @since 2.19 */ -@RunWith( Parameterized.class ) -public class Surefire1158RemoveInfoLinesIT extends SurefireJUnit4IntegrationTestCase -{ +@RunWith(Parameterized.class) +public class Surefire1158RemoveInfoLinesIT extends SurefireJUnit4IntegrationTestCase { - @Parameters( name = "{0}" ) - public static Iterable data() - { + @Parameters(name = "{0}") + public static Iterable data() { ArrayList args = new ArrayList<>(); - args.add( new Object[] {"junit-option-ff", "JUnitTest", "-ff", "surefire-junit47", false, true} ); - args.add( new Object[] {"testng-option-ff", "TestNGSuiteTest", "-ff", "surefire-testng", false, false} ); - args.add( new Object[] {"junit-option-X", "JUnitTest", "-X", "surefire-junit47", true, true} ); - args.add( new Object[] {"testng-option-X", "TestNGSuiteTest", "-X", "surefire-testng", true, false} ); - args.add( new Object[] {"junit-option-e", "JUnitTest", "-e", "surefire-junit47", true, true} ); - args.add( new Object[] {"testng-option-e", "TestNGSuiteTest", "-e", "surefire-testng", true, false} ); + args.add(new Object[] {"junit-option-ff", "JUnitTest", "-ff", "surefire-junit47", false, true}); + args.add(new Object[] {"testng-option-ff", "TestNGSuiteTest", "-ff", "surefire-testng", false, false}); + args.add(new Object[] {"junit-option-X", "JUnitTest", "-X", "surefire-junit47", true, true}); + args.add(new Object[] {"testng-option-X", "TestNGSuiteTest", "-X", "surefire-testng", true, false}); + args.add(new Object[] {"junit-option-e", "JUnitTest", "-e", "surefire-junit47", true, true}); + args.add(new Object[] {"testng-option-e", "TestNGSuiteTest", "-e", "surefire-testng", true, false}); return args; } - @Parameter( 0 ) - @SuppressWarnings( "checkstyle:visibilitymodifier" ) + @Parameter(0) + @SuppressWarnings("checkstyle:visibilitymodifier") public String description; - @Parameter( 1 ) - @SuppressWarnings( "checkstyle:visibilitymodifier" ) + @Parameter(1) + @SuppressWarnings("checkstyle:visibilitymodifier") public String testToRun; - @Parameter( 2 ) - @SuppressWarnings( "checkstyle:visibilitymodifier" ) + @Parameter(2) + @SuppressWarnings("checkstyle:visibilitymodifier") public String cliOption; - @Parameter( 3 ) - @SuppressWarnings( "checkstyle:visibilitymodifier" ) + @Parameter(3) + @SuppressWarnings("checkstyle:visibilitymodifier") public String provider; - @Parameter( 4 ) - @SuppressWarnings( "checkstyle:visibilitymodifier" ) + @Parameter(4) + @SuppressWarnings("checkstyle:visibilitymodifier") public boolean printsInfoLines; - @Parameter( 5 ) - @SuppressWarnings( "checkstyle:visibilitymodifier" ) + @Parameter(5) + @SuppressWarnings("checkstyle:visibilitymodifier") public boolean isJUnit; @Test - public void shouldRunWithCliOption() - { + public void shouldRunWithCliOption() { OutputValidator validator = assertTest(); - if ( isJUnit ) - { - assertJUnitTestLogs( validator ); - } - else - { - assertTestNGTestLogs( validator ); + if (isJUnit) { + assertJUnitTestLogs(validator); + } else { + assertTestNGTestLogs(validator); } } - private OutputValidator assertTest() - { + private OutputValidator assertTest() { final String[] cli = {"--batch-mode"}; - return unpack( "/surefire-1158-remove-info-lines", "_" + description, cli ) - .sysProp( "provider", provider ) - .addGoal( cliOption ) - .setTestToRun( testToRun ) - .executeTest() - .verifyErrorFreeLog() - .assertTestSuiteResults( 1, 0, 0, 0 ); + return unpack("/surefire-1158-remove-info-lines", "_" + description, cli) + .sysProp("provider", provider) + .addGoal(cliOption) + .setTestToRun(testToRun) + .executeTest() + .verifyErrorFreeLog() + .assertTestSuiteResults(1, 0, 0, 0); } - private void assertJUnitTestLogs( OutputValidator validator ) - { - try - { - validator.verifyTextInLog( "Surefire report directory:" ); + private void assertJUnitTestLogs(OutputValidator validator) { + try { + validator.verifyTextInLog("Surefire report directory:"); validator.verifyTextInLog( - "Using configured provider org.apache.maven.surefire.junitcore.JUnitCoreProvider" ); - validator.verifyTextInLog( "parallel='none', perCoreThreadCount=true, threadCount=0, " + "Using configured provider org.apache.maven.surefire.junitcore.JUnitCoreProvider"); + validator.verifyTextInLog("parallel='none', perCoreThreadCount=true, threadCount=0, " + "useUnlimitedThreads=false, threadCountSuites=0, threadCountClasses=0, " - + "threadCountMethods=0, parallelOptimized=true" ); - if ( !printsInfoLines ) - { + + "threadCountMethods=0, parallelOptimized=true"); + if (!printsInfoLines) { fail(); } - } - catch ( SurefireVerifierException e ) - { - if ( printsInfoLines ) - { + } catch (SurefireVerifierException e) { + if (printsInfoLines) { fail(); } } } - private void assertTestNGTestLogs( OutputValidator validator ) - { - try - { - validator.verifyTextInLog( "Surefire report directory:" ); - validator.verifyTextInLog( "Using configured provider org.apache.maven.surefire.testng.TestNGProvider" ); - validator.verifyTextInLog( "Configuring TestNG with: TestNGMapConfigurator" ); - if ( !printsInfoLines ) - { + private void assertTestNGTestLogs(OutputValidator validator) { + try { + validator.verifyTextInLog("Surefire report directory:"); + validator.verifyTextInLog("Using configured provider org.apache.maven.surefire.testng.TestNGProvider"); + validator.verifyTextInLog("Configuring TestNG with: TestNGMapConfigurator"); + if (!printsInfoLines) { fail(); } - } - catch ( SurefireVerifierException e ) - { - if ( printsInfoLines ) - { + } catch (SurefireVerifierException e) { + if (printsInfoLines) { fail(); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1177TestngParallelSuitesIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1177TestngParallelSuitesIT.java index c28254b46b..61e4b9556d 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1177TestngParallelSuitesIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1177TestngParallelSuitesIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its.jiras; /* @@ -35,44 +53,31 @@ * @author Tibor Digana (tibor17) * @since 2.19 */ -public class Surefire1177TestngParallelSuitesIT - extends SurefireJUnit4IntegrationTestCase -{ +public class Surefire1177TestngParallelSuitesIT extends SurefireJUnit4IntegrationTestCase { private static final String EXPECTED_LINE = "TestNGSuiteTest#shouldRunAndPrintItself()"; private static final String UNEXPECTED_LINE = "ShouldNotRunTest#shouldNotRun()"; @Test - public void twoSuitesInParallel() - throws VerificationException - { - OutputValidator validator = unpack() - .forkNever() - .executeTest() - .verifyErrorFree( 2 ); + public void twoSuitesInParallel() throws VerificationException { + OutputValidator validator = unpack().forkNever().executeTest().verifyErrorFree(2); - validator.assertThatLogLine( startsWith( EXPECTED_LINE ), is( 2 ) ); - validator.assertThatLogLine( is( EXPECTED_LINE + " 1." ), is( 1 ) ); - validator.assertThatLogLine( is( EXPECTED_LINE + " 2." ), is( 1 ) ); - validator.assertThatLogLine( containsString( UNEXPECTED_LINE ), is( 0 ) ); + validator.assertThatLogLine(startsWith(EXPECTED_LINE), is(2)); + validator.assertThatLogLine(is(EXPECTED_LINE + " 1."), is(1)); + validator.assertThatLogLine(is(EXPECTED_LINE + " 2."), is(1)); + validator.assertThatLogLine(containsString(UNEXPECTED_LINE), is(0)); } @Test - public void twoSuitesInParallelForked() - throws VerificationException - { - OutputValidator validator = unpack() - .forkOnce() - .executeTest() - .verifyErrorFree( 2 ); + public void twoSuitesInParallelForked() throws VerificationException { + OutputValidator validator = unpack().forkOnce().executeTest().verifyErrorFree(2); - validator.assertThatLogLine( startsWith( EXPECTED_LINE ), is( 2 ) ); - validator.assertThatLogLine( is( EXPECTED_LINE + " 1." ), is( 1 ) ); - validator.assertThatLogLine( is( EXPECTED_LINE + " 2." ), is( 1 ) ); - validator.assertThatLogLine( containsString( UNEXPECTED_LINE ), is( 0 ) ); + validator.assertThatLogLine(startsWith(EXPECTED_LINE), is(2)); + validator.assertThatLogLine(is(EXPECTED_LINE + " 1."), is(1)); + validator.assertThatLogLine(is(EXPECTED_LINE + " 2."), is(1)); + validator.assertThatLogLine(containsString(UNEXPECTED_LINE), is(0)); } - private SurefireLauncher unpack() - { - return unpack( "testng-parallel-suites" ); + private SurefireLauncher unpack() { + return unpack("testng-parallel-suites"); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1179IT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1179IT.java index e4e8e31bb0..27582cf676 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1179IT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1179IT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its.jiras; /* @@ -26,18 +44,14 @@ /** * Fix for TestNG parameter -dataproviderthreadcount. */ -public class Surefire1179IT - extends SurefireJUnit4IntegrationTestCase -{ +public class Surefire1179IT extends SurefireJUnit4IntegrationTestCase { @Test - public void suiteXmlForkCountTwoReuse() - { - unpack().executeTest().verifyErrorFreeLog().verifyTextInLog( " CONCURRENCY=30." ); + public void suiteXmlForkCountTwoReuse() { + unpack().executeTest().verifyErrorFreeLog().verifyTextInLog(" CONCURRENCY=30."); } - private SurefireLauncher unpack() - { - return unpack( "surefire-1179-testng-parallel-dataprovider" ); + private SurefireLauncher unpack() { + return unpack("surefire-1179-testng-parallel-dataprovider"); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1185DoNotSpawnTestsIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1185DoNotSpawnTestsIT.java index 74a4e469b1..14dab2c2c2 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1185DoNotSpawnTestsIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1185DoNotSpawnTestsIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its.jiras; /* @@ -41,22 +59,17 @@ * * Tests run: 1, Failures: 0, Errors: 0, Skipped: 0 */ -public class Surefire1185DoNotSpawnTestsIT - extends SurefireJUnit4IntegrationTestCase -{ +public class Surefire1185DoNotSpawnTestsIT extends SurefireJUnit4IntegrationTestCase { @Test - public void doNotSpawnUnwantedTests() - throws VerificationException - { - unpack().setTestToRun( "RunningTest#test" ) - .executeTest() - .assertTestSuiteResults( 1 ) - .assertThatLogLine( containsString( "in pkg.RunningTest" ), is( 1 ) ) - .assertThatLogLine( containsString( "in pkg.UnlistedTest" ), is( 0 ) ); + public void doNotSpawnUnwantedTests() throws VerificationException { + unpack().setTestToRun("RunningTest#test") + .executeTest() + .assertTestSuiteResults(1) + .assertThatLogLine(containsString("in pkg.RunningTest"), is(1)) + .assertThatLogLine(containsString("in pkg.UnlistedTest"), is(0)); } - private SurefireLauncher unpack() - { - return unpack( "surefire-1185" ); + private SurefireLauncher unpack() { + return unpack("surefire-1185"); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1202RerunAndSkipIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1202RerunAndSkipIT.java index 1d40b561b4..c5f18f5160 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1202RerunAndSkipIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1202RerunAndSkipIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its.jiras; /* @@ -30,26 +48,18 @@ * @see SUREFIRE-1202 * @since 2.19.1 */ -public class Surefire1202RerunAndSkipIT - extends SurefireJUnit4IntegrationTestCase -{ +public class Surefire1202RerunAndSkipIT extends SurefireJUnit4IntegrationTestCase { @Test - public void junit47() - { - unpack().executeTest() - .assertTestSuiteResults( 5, 0, 0, 3, 4 ); + public void junit47() { + unpack().executeTest().assertTestSuiteResults(5, 0, 0, 3, 4); } @Test - public void junit4() - { - unpack().addGoal( "-Pjunit4" ) - .executeTest() - .assertTestSuiteResults( 5, 0, 0, 3, 4 ); + public void junit4() { + unpack().addGoal("-Pjunit4").executeTest().assertTestSuiteResults(5, 0, 0, 3, 4); } - private SurefireLauncher unpack() - { - return unpack( "surefire-1202-rerun-and-failfast" ); + private SurefireLauncher unpack() { + return unpack("surefire-1202-rerun-and-failfast"); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1209RerunAndForkCountIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1209RerunAndForkCountIT.java index 696e0acdb9..11fa26a9e6 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1209RerunAndForkCountIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1209RerunAndForkCountIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its.jiras; /* @@ -24,58 +42,50 @@ import org.apache.maven.surefire.its.fixture.SurefireLauncher; import org.junit.Test; -import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.containsString; +import static org.hamcrest.CoreMatchers.is; /** * @author Tibor Digana (tibor17) * @see SUREFIRE-1209 * @since 2.19 */ -public class Surefire1209RerunAndForkCountIT - extends SurefireJUnit4IntegrationTestCase -{ +public class Surefire1209RerunAndForkCountIT extends SurefireJUnit4IntegrationTestCase { private static final String SUMMARY_COUNTS = "Tests run: 5, Failures: 0, Errors: 0, Skipped: 0, Flakes: 2"; @Test - public void reusableForksJUnit47() throws VerificationException - { + public void reusableForksJUnit47() throws VerificationException { unpack().executeTest() - .assertTestSuiteResults( 5, 0, 0, 0, 4 ) - .assertThatLogLine( containsString( SUMMARY_COUNTS ), is( 1 ) ); + .assertTestSuiteResults(5, 0, 0, 0, 4) + .assertThatLogLine(containsString(SUMMARY_COUNTS), is(1)); } @Test - public void notReusableForksJUnit47() throws VerificationException - { - unpack().reuseForks( false ) + public void notReusableForksJUnit47() throws VerificationException { + unpack().reuseForks(false) .executeTest() - .assertTestSuiteResults( 5, 0, 0, 0, 4 ) - .assertThatLogLine( containsString( SUMMARY_COUNTS ), is( 1 ) ); + .assertTestSuiteResults(5, 0, 0, 0, 4) + .assertThatLogLine(containsString(SUMMARY_COUNTS), is(1)); } @Test - public void reusableForksJUnit4() throws VerificationException - { - unpack().activateProfile( "junit4" ) + public void reusableForksJUnit4() throws VerificationException { + unpack().activateProfile("junit4") .executeTest() - .assertTestSuiteResults( 5, 0, 0, 0, 4 ) - .assertThatLogLine( containsString( SUMMARY_COUNTS ), is( 1 ) ); + .assertTestSuiteResults(5, 0, 0, 0, 4) + .assertThatLogLine(containsString(SUMMARY_COUNTS), is(1)); } @Test - public void notReusableForksJUnit4() - throws VerificationException - { - unpack().activateProfile( "junit4" ) - .reuseForks( false ) + public void notReusableForksJUnit4() throws VerificationException { + unpack().activateProfile("junit4") + .reuseForks(false) .executeTest() - .assertTestSuiteResults( 5, 0, 0, 0, 4 ) - .assertThatLogLine( containsString( SUMMARY_COUNTS ), is( 1 ) ); + .assertTestSuiteResults(5, 0, 0, 0, 4) + .assertThatLogLine(containsString(SUMMARY_COUNTS), is(1)); } - private SurefireLauncher unpack() - { - return unpack( "surefire-1209-rerun-and-forkcount" ); + private SurefireLauncher unpack() { + return unpack("surefire-1209-rerun-and-forkcount"); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1211JUnitTestNgIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1211JUnitTestNgIT.java index 698df57fc2..24279fdca7 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1211JUnitTestNgIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1211JUnitTestNgIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its.jiras; /* @@ -28,29 +46,19 @@ * @see SUREFIRE-1211 * @since 2.19.1 */ -public class Surefire1211JUnitTestNgIT - extends SurefireJUnit4IntegrationTestCase -{ +public class Surefire1211JUnitTestNgIT extends SurefireJUnit4IntegrationTestCase { @Test - public void withJUnit() - { - unpack().threadCount( 1 ) - .executeTest() - .verifyErrorFree( 2 ); + public void withJUnit() { + unpack().threadCount(1).executeTest().verifyErrorFree(2); } @Test - public void withoutJUnit() - { - unpack().threadCount( 1 ) - .sysProp( "junit", "false" ) - .executeTest() - .verifyErrorFree( 1 ); + public void withoutJUnit() { + unpack().threadCount(1).sysProp("junit", "false").executeTest().verifyErrorFree(1); } - private SurefireLauncher unpack() - { - return unpack( "surefire-1211" ); + private SurefireLauncher unpack() { + return unpack("surefire-1211"); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1260NewTestsPattern.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1260NewTestsPattern.java index 640c551b62..f431c0733e 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1260NewTestsPattern.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1260NewTestsPattern.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its.jiras; /* @@ -32,19 +50,13 @@ * @see SUREFIRE-1260 * @since 2.20 */ -public class Surefire1260NewTestsPattern - extends SurefireJUnit4IntegrationTestCase -{ +public class Surefire1260NewTestsPattern extends SurefireJUnit4IntegrationTestCase { @Test - public void defaultConfig() - { - unpack() - .executeTest() - .verifyErrorFree( 5 ); + public void defaultConfig() { + unpack().executeTest().verifyErrorFree(5); } - private SurefireLauncher unpack() - { - return unpack( "/surefire-1260-new-tests-pattern" ); + private SurefireLauncher unpack() { + return unpack("/surefire-1260-new-tests-pattern"); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1264IT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1264IT.java index bd9af176d3..79c3d6456a 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1264IT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1264IT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its.jiras; /* @@ -27,32 +45,28 @@ * @see SUREFIRE-1264 * @since 2.20.1 */ -public class Surefire1264IT - extends SurefireJUnit4IntegrationTestCase -{ +public class Surefire1264IT extends SurefireJUnit4IntegrationTestCase { @Test - public void positiveTests() - { - unpack( "surefire-1264" ) + public void positiveTests() { + unpack("surefire-1264") .setForkJvm() .parallelAll() .useUnlimitedThreads() - .sysProp( "canFail", "false" ) + .sysProp("canFail", "false") .executeTest() - .assertTestSuiteResults( 16, 0, 0, 0 ); + .assertTestSuiteResults(16, 0, 0, 0); } @Test - public void negativeTests() - { - unpack( "surefire-1264" ) + public void negativeTests() { + unpack("surefire-1264") .setForkJvm() .parallelAll() .useUnlimitedThreads() - .sysProp( "canFail", "true" ) - .mavenTestFailureIgnore( true ) + .sysProp("canFail", "true") + .mavenTestFailureIgnore(true) .executeTest() - .assertTestSuiteResults( 16, 0, 16, 0 ); + .assertTestSuiteResults(16, 0, 16, 0); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1265Java9IT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1265Java9IT.java index 38b7af8d49..7e063bb070 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1265Java9IT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1265Java9IT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its.jiras; /* @@ -22,7 +40,7 @@ import org.apache.maven.surefire.its.fixture.AbstractJava9PlusIT; import org.junit.Test; -@SuppressWarnings( { "javadoc", "checkstyle:javadoctype" } ) +@SuppressWarnings({"javadoc", "checkstyle:javadoctype"}) /** * IsolatedClassLoader should take platform ClassLoader as a parent ClassLoader if running on the top of JDK9. * The IsolatedClassLoader should not fail like this: @@ -36,20 +54,14 @@ * @see SUREFIRE-1265 * @since 2.20.1 */ -public class Surefire1265Java9IT - extends AbstractJava9PlusIT -{ +public class Surefire1265Java9IT extends AbstractJava9PlusIT { @Test - public void shouldRunInPluginJava9() - { - assumeJava9() - .executeTest() - .verifyErrorFree( 2 ); + public void shouldRunInPluginJava9() { + assumeJava9().executeTest().verifyErrorFree(2); } @Override - protected String getProjectDirectoryName() - { + protected String getProjectDirectoryName() { return "/surefire-1265"; } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1278GroupNameEndingIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1278GroupNameEndingIT.java index c0b0339274..22acd28734 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1278GroupNameEndingIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1278GroupNameEndingIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its.jiras; /* @@ -27,18 +45,13 @@ * Test the group filter for TestNG * */ -public class Surefire1278GroupNameEndingIT - extends SurefireJUnit4IntegrationTestCase -{ +public class Surefire1278GroupNameEndingIT extends SurefireJUnit4IntegrationTestCase { @Test - public void testOnlyGroups() - { - unpack().setGroups( "group" ).executeTest().verifyErrorFree( 1 ); + public void testOnlyGroups() { + unpack().setGroups("group").executeTest().verifyErrorFree(1); } - public SurefireLauncher unpack() - { - return unpack( "/surefire-1278-group-name-ending" ); + public SurefireLauncher unpack() { + return unpack("/surefire-1278-group-name-ending"); } - } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1295AttributeJvmCrashesToTestsIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1295AttributeJvmCrashesToTestsIT.java index c18edda16b..545602fd30 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1295AttributeJvmCrashesToTestsIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1295AttributeJvmCrashesToTestsIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its.jiras; /* @@ -49,104 +67,87 @@ * @author michaeltandy * @since 2.20 */ -@RunWith( Parameterized.class ) -public class Surefire1295AttributeJvmCrashesToTestsIT - extends SurefireJUnit4IntegrationTestCase -{ +@RunWith(Parameterized.class) +public class Surefire1295AttributeJvmCrashesToTestsIT extends SurefireJUnit4IntegrationTestCase { private static final int ONE_FORK_REUSE_THREAD_COUNT = 1; /** * */ - public enum ForkMode - { + public enum ForkMode { DEFAULT, ONE_FORK_NO_REUSE, ONE_FORK_REUSE } @Parameters - public static Iterable parameters() - { - return asList( new Object[][] { -// exit() does not stop all Threads immediately, -// see https://github.com/michaeltandy/crashjvm/issues/1 - { "exit", DEFAULT }, - { "exit", ONE_FORK_NO_REUSE }, - { "exit", ONE_FORK_REUSE }, - { "abort", DEFAULT }, - { "abort", ONE_FORK_NO_REUSE }, - { "abort", ONE_FORK_REUSE }, - { "segfault", DEFAULT }, - { "segfault", ONE_FORK_NO_REUSE }, - { "segfault", ONE_FORK_REUSE } - } ); + public static Iterable parameters() { + return asList(new Object[][] { + // exit() does not stop all Threads immediately, + // see https://github.com/michaeltandy/crashjvm/issues/1 + {"exit", DEFAULT}, + {"exit", ONE_FORK_NO_REUSE}, + {"exit", ONE_FORK_REUSE}, + {"abort", DEFAULT}, + {"abort", ONE_FORK_NO_REUSE}, + {"abort", ONE_FORK_REUSE}, + {"segfault", DEFAULT}, + {"segfault", ONE_FORK_NO_REUSE}, + {"segfault", ONE_FORK_REUSE} + }); } - @Parameter( 0 ) - @SuppressWarnings( "checkstyle:visibilitymodifier" ) + @Parameter(0) + @SuppressWarnings("checkstyle:visibilitymodifier") public String crashStyle; - @Parameter( 1 ) - @SuppressWarnings( "checkstyle:visibilitymodifier" ) + @Parameter(1) + @SuppressWarnings("checkstyle:visibilitymodifier") public ForkMode forkStyle; @Test - public void test() - throws Exception - { - assumeTrue( IS_OS_LINUX || IS_OS_MAC_OSX || IS_OS_WINDOWS ); + public void test() throws Exception { + assumeTrue(IS_OS_LINUX || IS_OS_MAC_OSX || IS_OS_WINDOWS); - SurefireLauncher launcher = - unpack( "crash-during-test", "_" + crashStyle + "_" + forkStyle.ordinal() ) + SurefireLauncher launcher = unpack("crash-during-test", "_" + crashStyle + "_" + forkStyle.ordinal()) .setForkJvm(); - switch ( forkStyle ) - { + switch (forkStyle) { case DEFAULT: break; case ONE_FORK_NO_REUSE: - launcher.forkCount( 1 ) - .reuseForks( false ); + launcher.forkCount(1).reuseForks(false); break; case ONE_FORK_REUSE: - launcher.forkPerThread( ONE_FORK_REUSE_THREAD_COUNT ) - .threadCount( ONE_FORK_REUSE_THREAD_COUNT ); + launcher.forkPerThread(ONE_FORK_REUSE_THREAD_COUNT).threadCount(ONE_FORK_REUSE_THREAD_COUNT); break; default: fail(); } - checkCrash( launcher.addGoal( "-DcrashType=" + crashStyle ) ); + checkCrash(launcher.addGoal("-DcrashType=" + crashStyle)); } - private static void checkCrash( SurefireLauncher launcher ) throws Exception - { + private static void checkCrash(SurefireLauncher launcher) throws Exception { OutputValidator validator = launcher.maven() .withFailure() .executeTest() - .verifyTextInLog( "The forked VM terminated without properly saying " - + "goodbye. VM crash or System.exit called?" ) - .verifyTextInLog( "Crashed tests:" ); + .verifyTextInLog("The forked VM terminated without properly saying " + + "goodbye. VM crash or System.exit called?") + .verifyTextInLog("Crashed tests:"); // Cannot flush log.txt stream because it is consumed internally by Verifier. // Waiting for the stream to become flushed on disk. - SECONDS.sleep( 1L ); + SECONDS.sleep(1L); - for ( Iterator it = validator.loadLogLines().iterator(); it.hasNext(); ) - { + for (Iterator it = validator.loadLogLines().iterator(); it.hasNext(); ) { String line = it.next(); - if ( line.contains( "Crashed tests:" ) ) - { + if (line.contains("Crashed tests:")) { line = it.next(); - if ( it.hasNext() ) - { - assertThat( line ) - .contains( "junit44.environment.Test1CrashedTest" ); - } - else - { - fail( "Could not find any line after 'Crashed tests:'." ); + if (it.hasNext()) { + assertThat(line).contains("junit44.environment.Test1CrashedTest"); + } else { + fail("Could not find any line after 'Crashed tests:'."); } } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1364SystemPropertiesIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1364SystemPropertiesIT.java index 2a21b9fb2b..a4a780183e 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1364SystemPropertiesIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1364SystemPropertiesIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its.jiras; /* @@ -30,174 +48,176 @@ * @author Tibor Digana (tibor17) * @since 2.20.1 */ -public class Surefire1364SystemPropertiesIT - extends SurefireJUnit4IntegrationTestCase -{ +public class Surefire1364SystemPropertiesIT extends SurefireJUnit4IntegrationTestCase { @Test - public void junit3Forked() - { - SurefireLauncher launcher = unpack( "surefire-1364" ); + public void junit3Forked() { + SurefireLauncher launcher = unpack("surefire-1364"); OutputValidator validator = launcher.setForkJvm() - .activateProfile( "junit3" ) - .forkOnce() - .executeTest() - .verifyErrorFree( 2 ); - - validator.getSurefireReportsXmlFile( "TEST-FirstTest.xml" ) - .assertContainsText( "" ); - - validator.getSurefireReportsXmlFile( "TEST-SecondTest.xml" ) - .assertContainsText( "" ); + .activateProfile("junit3") + .forkOnce() + .executeTest() + .verifyErrorFree(2); + + validator + .getSurefireReportsXmlFile("TEST-FirstTest.xml") + .assertContainsText(""); + + validator + .getSurefireReportsXmlFile("TEST-SecondTest.xml") + .assertContainsText(""); } @Test - public void junit3InProcess() - { - SurefireLauncher launcher = unpack( "surefire-1364" ); + public void junit3InProcess() { + SurefireLauncher launcher = unpack("surefire-1364"); OutputValidator validator = launcher.setForkJvm() - .activateProfile( "junit3" ) - .forkNever() - .executeTest() - .verifyErrorFree( 2 ); - - validator.getSurefireReportsXmlFile( "TEST-FirstTest.xml" ) - .assertContainsText( "" ); - - validator.getSurefireReportsXmlFile( "TEST-SecondTest.xml" ) - .assertContainsText( "" ); + .activateProfile("junit3") + .forkNever() + .executeTest() + .verifyErrorFree(2); + + validator + .getSurefireReportsXmlFile("TEST-FirstTest.xml") + .assertContainsText(""); + + validator + .getSurefireReportsXmlFile("TEST-SecondTest.xml") + .assertContainsText(""); } @Test - public void junit4Forked() - { - SurefireLauncher launcher = unpack( "surefire-1364" ); - OutputValidator validator = launcher.setForkJvm() - .forkOnce() - .executeTest() - .verifyErrorFree( 2 ); - - validator.getSurefireReportsXmlFile( "TEST-FirstTest.xml" ) - .assertContainsText( "" ); - - validator.getSurefireReportsXmlFile( "TEST-SecondTest.xml" ) - .assertContainsText( "" ); + public void junit4Forked() { + SurefireLauncher launcher = unpack("surefire-1364"); + OutputValidator validator = + launcher.setForkJvm().forkOnce().executeTest().verifyErrorFree(2); + + validator + .getSurefireReportsXmlFile("TEST-FirstTest.xml") + .assertContainsText(""); + + validator + .getSurefireReportsXmlFile("TEST-SecondTest.xml") + .assertContainsText(""); } @Test - public void junit4InProcess() - { - SurefireLauncher launcher = unpack( "surefire-1364" ); - OutputValidator validator = launcher.setForkJvm() - .forkNever() - .executeTest() - .verifyErrorFree( 2 ); - - validator.getSurefireReportsXmlFile( "TEST-FirstTest.xml" ) - .assertContainsText( "" ); - - validator.getSurefireReportsXmlFile( "TEST-SecondTest.xml" ) - .assertContainsText( "" ); + public void junit4InProcess() { + SurefireLauncher launcher = unpack("surefire-1364"); + OutputValidator validator = + launcher.setForkJvm().forkNever().executeTest().verifyErrorFree(2); + + validator + .getSurefireReportsXmlFile("TEST-FirstTest.xml") + .assertContainsText(""); + + validator + .getSurefireReportsXmlFile("TEST-SecondTest.xml") + .assertContainsText(""); } @Test - public void junit47Forked() - { - SurefireLauncher launcher = unpack( "surefire-1364" ); + public void junit47Forked() { + SurefireLauncher launcher = unpack("surefire-1364"); OutputValidator validator = launcher.setForkJvm() - .activateProfile( "junit47" ) - .forkOnce() - .executeTest() - .verifyErrorFree( 2 ); - - validator.getSurefireReportsXmlFile( "TEST-FirstTest.xml" ) - .assertContainsText( "" ); - - validator.getSurefireReportsXmlFile( "TEST-SecondTest.xml" ) - .assertContainsText( "" ); + .activateProfile("junit47") + .forkOnce() + .executeTest() + .verifyErrorFree(2); + + validator + .getSurefireReportsXmlFile("TEST-FirstTest.xml") + .assertContainsText(""); + + validator + .getSurefireReportsXmlFile("TEST-SecondTest.xml") + .assertContainsText(""); } @Test - public void junit47InProcess() - { - SurefireLauncher launcher = unpack( "surefire-1364" ); + public void junit47InProcess() { + SurefireLauncher launcher = unpack("surefire-1364"); OutputValidator validator = launcher.setForkJvm() - .activateProfile( "junit47" ) - .forkNever() - .executeTest() - .verifyErrorFree( 2 ); - - validator.getSurefireReportsXmlFile( "TEST-FirstTest.xml" ) - .assertContainsText( "" ); - - validator.getSurefireReportsXmlFile( "TEST-SecondTest.xml" ) - .assertContainsText( "" ); + .activateProfile("junit47") + .forkNever() + .executeTest() + .verifyErrorFree(2); + + validator + .getSurefireReportsXmlFile("TEST-FirstTest.xml") + .assertContainsText(""); + + validator + .getSurefireReportsXmlFile("TEST-SecondTest.xml") + .assertContainsText(""); } @Test - public void junit47ForkedParallel() - { - SurefireLauncher launcher = unpack( "surefire-1364" ); + public void junit47ForkedParallel() { + SurefireLauncher launcher = unpack("surefire-1364"); OutputValidator validator = launcher.setForkJvm() - .activateProfile( "junit47" ) - .forkOnce() - .parallelClasses() - .threadCount( 2 ) - .disablePerCoreThreadCount() - .executeTest() - .verifyErrorFree( 2 ); - - validator.getSurefireReportsXmlFile( "TEST-FirstTest.xml" ) - .assertContainsText( "" ); - - validator.getSurefireReportsXmlFile( "TEST-SecondTest.xml" ) - .assertContainsText( "" ); + .activateProfile("junit47") + .forkOnce() + .parallelClasses() + .threadCount(2) + .disablePerCoreThreadCount() + .executeTest() + .verifyErrorFree(2); + + validator + .getSurefireReportsXmlFile("TEST-FirstTest.xml") + .assertContainsText(""); + + validator + .getSurefireReportsXmlFile("TEST-SecondTest.xml") + .assertContainsText(""); } @Test - public void junit47InProcessParallel() - { - SurefireLauncher launcher = unpack( "surefire-1364" ); + public void junit47InProcessParallel() { + SurefireLauncher launcher = unpack("surefire-1364"); OutputValidator validator = launcher.setForkJvm() - .activateProfile( "junit47" ) - .forkNever() - .parallelClasses() - .threadCount( 2 ) - .disablePerCoreThreadCount() - .executeTest() - .verifyErrorFree( 2 ); - - validator.getSurefireReportsXmlFile( "TEST-FirstTest.xml" ) - .assertContainsText( "" ); - - validator.getSurefireReportsXmlFile( "TEST-SecondTest.xml" ) - .assertContainsText( "" ); + .activateProfile("junit47") + .forkNever() + .parallelClasses() + .threadCount(2) + .disablePerCoreThreadCount() + .executeTest() + .verifyErrorFree(2); + + validator + .getSurefireReportsXmlFile("TEST-FirstTest.xml") + .assertContainsText(""); + + validator + .getSurefireReportsXmlFile("TEST-SecondTest.xml") + .assertContainsText(""); } @Test - public void testNg() - { - SurefireLauncher launcher = unpack( "surefire-1364" ); + public void testNg() { + SurefireLauncher launcher = unpack("surefire-1364"); OutputValidator validator = launcher.setForkJvm() - .activateProfile( "testng" ) - .forkOnce() - .executeTest() - .verifyErrorFree( 3 ); - - validator.getSurefireReportsXmlFile( "TEST-TestSuite.xml" ) - .assertContainsText( "" ); + .activateProfile("testng") + .forkOnce() + .executeTest() + .verifyErrorFree(3); + + validator + .getSurefireReportsXmlFile("TEST-TestSuite.xml") + .assertContainsText(""); } @Test - public void testNgInProcess() - { - SurefireLauncher launcher = unpack( "surefire-1364" ); + public void testNgInProcess() { + SurefireLauncher launcher = unpack("surefire-1364"); OutputValidator validator = launcher.setForkJvm() - .activateProfile( "testng" ) - .forkNever() - .executeTest() - .verifyErrorFree( 3 ); - - validator.getSurefireReportsXmlFile( "TEST-TestSuite.xml" ) - .assertContainsText( "" ); + .activateProfile("testng") + .forkNever() + .executeTest() + .verifyErrorFree(3); + + validator + .getSurefireReportsXmlFile("TEST-TestSuite.xml") + .assertContainsText(""); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1367AssumptionLogsIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1367AssumptionLogsIT.java index 231010f35c..5f23dd4a5c 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1367AssumptionLogsIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1367AssumptionLogsIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its.jiras; /* @@ -31,89 +49,91 @@ * @see SUREFIRE-1367 * @since 2.20.1 */ -public class Surefire1367AssumptionLogsIT extends SurefireJUnit4IntegrationTestCase -{ - private static final String NL = System.getProperty( "line.separator" ); +public class Surefire1367AssumptionLogsIT extends SurefireJUnit4IntegrationTestCase { + private static final String NL = System.getProperty("line.separator"); @Test - public void shouldSeeLogsParallelForked() - { - OutputValidator outputValidator = - unpack().setForkJvm().forkOnce().parallelClassesAndMethods().disablePerCoreThreadCount().threadCountClasses( - 2 ).threadCountMethods( 2 ).executeTest().assertTestSuiteResults( 2, 0, 0, 2 ); - - verifyReportA( outputValidator ); - verifyReportB( outputValidator ); + public void shouldSeeLogsParallelForked() { + OutputValidator outputValidator = unpack().setForkJvm() + .forkOnce() + .parallelClassesAndMethods() + .disablePerCoreThreadCount() + .threadCountClasses(2) + .threadCountMethods(2) + .executeTest() + .assertTestSuiteResults(2, 0, 0, 2); + + verifyReportA(outputValidator); + verifyReportB(outputValidator); } @Test - public void shouldSeeLogsParallelInPlugin() - { - OutputValidator outputValidator = - unpack().setForkJvm().forkNever().parallelClassesAndMethods().disablePerCoreThreadCount() - .threadCountClasses( - 2 ).threadCountMethods( 2 ).executeTest().assertTestSuiteResults( 2, 0, 0, 2 ); - - verifyReportA( outputValidator ); - verifyReportB( outputValidator ); + public void shouldSeeLogsParallelInPlugin() { + OutputValidator outputValidator = unpack().setForkJvm() + .forkNever() + .parallelClassesAndMethods() + .disablePerCoreThreadCount() + .threadCountClasses(2) + .threadCountMethods(2) + .executeTest() + .assertTestSuiteResults(2, 0, 0, 2); + + verifyReportA(outputValidator); + verifyReportB(outputValidator); } @Test - public void shouldSeeLogsForked() - { - OutputValidator outputValidator = unpack().setForkJvm().forkOnce().executeTest().assertTestSuiteResults( - 2, 0, 0, 2 ); + public void shouldSeeLogsForked() { + OutputValidator outputValidator = + unpack().setForkJvm().forkOnce().executeTest().assertTestSuiteResults(2, 0, 0, 2); - verifyReportA( outputValidator ); - verifyReportB( outputValidator ); + verifyReportA(outputValidator); + verifyReportB(outputValidator); } @Test - public void shouldSeeLogsInPlugin() - { + public void shouldSeeLogsInPlugin() { OutputValidator outputValidator = - unpack().setForkJvm().forkNever().executeTest().assertTestSuiteResults( 2, 0, 0, 2 ); + unpack().setForkJvm().forkNever().executeTest().assertTestSuiteResults(2, 0, 0, 2); - verifyReportA( outputValidator ); - verifyReportB( outputValidator ); + verifyReportA(outputValidator); + verifyReportB(outputValidator); } - - private SurefireLauncher unpack() - { - return unpack( "/surefire-1367" ); + private SurefireLauncher unpack() { + return unpack("/surefire-1367"); } - private void verifyReportA( OutputValidator outputValidator ) - { - String xmlReport = outputValidator.getSurefireReportsXmlFile( "TEST-ATest.xml" ).readFileToString(); + private void verifyReportA(OutputValidator outputValidator) { + String xmlReport = + outputValidator.getSurefireReportsXmlFile("TEST-ATest.xml").readFileToString(); String outputCData = "\n " + ""; - assertThat( xmlReport ).contains( outputCData ); - + assertThat(xmlReport).contains(outputCData); - String output = outputValidator.getSurefireReportsFile( "ATest-output.txt" ).readFileToString(); + String output = + outputValidator.getSurefireReportsFile("ATest-output.txt").readFileToString(); String outputExpected = "Hi" + NL + NL + "There!" + NL + "Hello" + NL + NL + "What's up!" + NL; - assertThat( output ).isEqualTo( outputExpected ); + assertThat(output).isEqualTo(outputExpected); } - private void verifyReportB( OutputValidator outputValidator ) - { - String xmlReport = outputValidator.getSurefireReportsXmlFile( "TEST-BTest.xml" ).readFileToString(); + private void verifyReportB(OutputValidator outputValidator) { + String xmlReport = + outputValidator.getSurefireReportsXmlFile("TEST-BTest.xml").readFileToString(); String outputCData = ""; - assertThat( xmlReport ).contains( outputCData ); - + assertThat(xmlReport).contains(outputCData); - String output = outputValidator.getSurefireReportsFile( "BTest-output.txt" ).readFileToString(); + String output = + outputValidator.getSurefireReportsFile("BTest-output.txt").readFileToString(); String outputExpected = "Hey" + NL + NL + "you!" + NL; - assertThat( output ).isEqualTo( outputExpected ); + assertThat(output).isEqualTo(outputExpected); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1383ScanSessionDependenciesIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1383ScanSessionDependenciesIT.java index be8ebd8210..872bcfd5e1 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1383ScanSessionDependenciesIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1383ScanSessionDependenciesIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its.jiras; /* @@ -29,15 +47,11 @@ * @see SUREFIRE-1383 * @since 2.22.0 */ -public class Surefire1383ScanSessionDependenciesIT - extends SurefireJUnit4IntegrationTestCase -{ +public class Surefire1383ScanSessionDependenciesIT extends SurefireJUnit4IntegrationTestCase { @Test - public void test() throws VerificationException - { - SurefireLauncher launcher = unpack( "surefire-1383" ); + public void test() throws VerificationException { + SurefireLauncher launcher = unpack("surefire-1383"); launcher.executeTest(); - launcher.getSubProjectValidator( "sut" ) - .assertTestSuiteResults( 1, 0, 0, 0 ); + launcher.getSubProjectValidator("sut").assertTestSuiteResults(1, 0, 0, 0); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1396CustomProviderClassPathIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1396CustomProviderClassPathIT.java index e0ed72ad2e..6cf6a6251b 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1396CustomProviderClassPathIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1396CustomProviderClassPathIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its.jiras; /* @@ -26,26 +44,24 @@ /** * @author Jonathan Bell */ -public class Surefire1396CustomProviderClassPathIT - extends SurefireJUnit4IntegrationTestCase -{ +public class Surefire1396CustomProviderClassPathIT extends SurefireJUnit4IntegrationTestCase { @BeforeClass - public static void installProvider() - { - unpack( Surefire1396CustomProviderClassPathIT.class, - "surefire-1396-pluggableproviders-classpath-provider", "prov" ) + public static void installProvider() { + unpack( + Surefire1396CustomProviderClassPathIT.class, + "surefire-1396-pluggableproviders-classpath-provider", + "prov") .executeInstall(); } - + @Test - public void pluggableProviderClasspathCorrect() - { - unpack( "surefire-1396-pluggableproviders-classpath" ) - .setForkJvm() - .maven() - .showExceptionMessages() - .debugLogging() - .executeVerify() - .verifyErrorFreeLog(); + public void pluggableProviderClasspathCorrect() { + unpack("surefire-1396-pluggableproviders-classpath") + .setForkJvm() + .maven() + .showExceptionMessages() + .debugLogging() + .executeVerify() + .verifyErrorFreeLog(); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire141PluggableProvidersIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire141PluggableProvidersIT.java index 6f1b748989..80742974c1 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire141PluggableProvidersIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire141PluggableProvidersIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its.jiras; /* @@ -19,15 +37,15 @@ * under the License. */ +import java.io.File; +import java.io.FilenameFilter; + import org.apache.maven.surefire.its.fixture.OutputValidator; import org.apache.maven.surefire.its.fixture.SurefireJUnit4IntegrationTestCase; import org.apache.maven.surefire.its.fixture.SurefireVerifierException; import org.junit.BeforeClass; import org.junit.Test; -import java.io.File; -import java.io.FilenameFilter; - import static org.assertj.core.api.Assertions.assertThat; /** @@ -35,126 +53,108 @@ * * @author Kristian Rosenvold */ -public class Surefire141PluggableProvidersIT - extends SurefireJUnit4IntegrationTestCase -{ +public class Surefire141PluggableProvidersIT extends SurefireJUnit4IntegrationTestCase { @BeforeClass - public static void installProvider() - { - unpack( Surefire141PluggableProvidersIT.class, "surefire-141-pluggableproviders-provider", "prov" ) - .executeInstall(); + public static void installProvider() { + unpack(Surefire141PluggableProvidersIT.class, "surefire-141-pluggableproviders-provider", "prov") + .executeInstall(); } @Test - public void pluggableProviderPresent() - { - unpack( "surefire-141-pluggableproviders" ) - .setForkJvm() - .maven() - .showExceptionMessages() - .debugLogging() - .executeTest() - .verifyTextInLog( "Using configured provider org.apache.maven.surefire.testprovider.TestProvider" ) - .verifyTextInLog( "Using configured provider org.apache.maven.surefire.junit.JUnit3Provider" ) - .verifyErrorFreeLog(); + public void pluggableProviderPresent() { + unpack("surefire-141-pluggableproviders") + .setForkJvm() + .maven() + .showExceptionMessages() + .debugLogging() + .executeTest() + .verifyTextInLog("Using configured provider org.apache.maven.surefire.testprovider.TestProvider") + .verifyTextInLog("Using configured provider org.apache.maven.surefire.junit.JUnit3Provider") + .verifyErrorFreeLog(); } @Test - public void invokeRuntimeException() - { + public void invokeRuntimeException() { final String errorText = "Let's fail with a runtimeException"; - OutputValidator validator = unpack( "surefire-141-pluggableproviders" ) - .setForkJvm() - .sysProp( "invokeCrash", "runtimeException" ) - .maven() - .withFailure() - .executeTest(); + OutputValidator validator = unpack("surefire-141-pluggableproviders") + .setForkJvm() + .sysProp("invokeCrash", "runtimeException") + .maven() + .withFailure() + .executeTest(); - assertErrorMessage( validator, errorText ); + assertErrorMessage(validator, errorText); - boolean hasErrorInLog = verifiedErrorInLog( validator, "There was an error in the forked process" ); - boolean verifiedInLog = verifiedErrorInLog( validator, errorText ); - assertThat( hasErrorInLog && verifiedInLog ) - .describedAs( "'" + errorText + "' could not be verified in log.txt nor *.dump file. (" - + hasErrorInLog + ", " + verifiedInLog + ")" ) + boolean hasErrorInLog = verifiedErrorInLog(validator, "There was an error in the forked process"); + boolean verifiedInLog = verifiedErrorInLog(validator, errorText); + assertThat(hasErrorInLog && verifiedInLog) + .describedAs("'" + errorText + "' could not be verified in log.txt nor *.dump file. (" + hasErrorInLog + + ", " + verifiedInLog + ")") .isTrue(); } @Test - public void invokeReporterException() - { + public void invokeReporterException() { final String errorText = "Let's fail with a reporterexception"; - OutputValidator validator = unpack( "surefire-141-pluggableproviders" ) - .setForkJvm() - .sysProp( "invokeCrash", "reporterException" ) - .maven() - .withFailure() - .executeTest(); + OutputValidator validator = unpack("surefire-141-pluggableproviders") + .setForkJvm() + .sysProp("invokeCrash", "reporterException") + .maven() + .withFailure() + .executeTest(); - assertErrorMessage( validator, errorText ); + assertErrorMessage(validator, errorText); - boolean hasErrorInLog = verifiedErrorInLog( validator, "There was an error in the forked process" ); - boolean verifiedInLog = verifiedErrorInLog( validator, errorText ); - assertThat( hasErrorInLog && verifiedInLog ) - .describedAs( "'" + errorText + "' could not be verified in log.txt nor *.dump file. (" - + hasErrorInLog + ", " + verifiedInLog + ")" ) + boolean hasErrorInLog = verifiedErrorInLog(validator, "There was an error in the forked process"); + boolean verifiedInLog = verifiedErrorInLog(validator, errorText); + assertThat(hasErrorInLog && verifiedInLog) + .describedAs("'" + errorText + "' could not be verified in log.txt nor *.dump file. (" + hasErrorInLog + + ", " + verifiedInLog + ")") .isTrue(); } @Test - public void constructorRuntimeException() - { + public void constructorRuntimeException() { final String errorText = "Let's fail with a runtimeException"; - OutputValidator validator = unpack( "surefire-141-pluggableproviders" ) - .setForkJvm() - .sysProp( "constructorCrash", "runtimeException" ) - .maven() - .withFailure() - .executeTest(); + OutputValidator validator = unpack("surefire-141-pluggableproviders") + .setForkJvm() + .sysProp("constructorCrash", "runtimeException") + .maven() + .withFailure() + .executeTest(); - assertErrorMessage( validator, errorText ); + assertErrorMessage(validator, errorText); - boolean hasErrorInLog = verifiedErrorInLog( validator, "There was an error in the forked process" ); - boolean verifiedInLog = verifiedErrorInLog( validator, errorText ); - assertThat( hasErrorInLog && verifiedInLog ) - .describedAs( "'" + errorText + "' could not be verified in log.txt nor *.dump file. (" - + hasErrorInLog + ", " + verifiedInLog + ")" ) + boolean hasErrorInLog = verifiedErrorInLog(validator, "There was an error in the forked process"); + boolean verifiedInLog = verifiedErrorInLog(validator, errorText); + assertThat(hasErrorInLog && verifiedInLog) + .describedAs("'" + errorText + "' could not be verified in log.txt nor *.dump file. (" + hasErrorInLog + + ", " + verifiedInLog + ")") .isTrue(); } - private static void assertErrorMessage( OutputValidator validator, String message ) - { + private static void assertErrorMessage(OutputValidator validator, String message) { File reportDir = validator.getSurefireReportsDirectory(); - String[] dumpFiles = reportDir.list( new FilenameFilter() - { - @Override - public boolean accept( File dir, String name ) - { - return name.endsWith( "-jvmRun1.dump" ); - } - } ) ; - assertThat( dumpFiles ) - .isNotNull() - .isNotEmpty(); - for ( String dump : dumpFiles ) - { - validator.getSurefireReportsFile( dump ) - .assertContainsText( message ); + String[] dumpFiles = reportDir.list(new FilenameFilter() { + @Override + public boolean accept(File dir, String name) { + return name.endsWith("-jvmRun1.dump"); + } + }); + assertThat(dumpFiles).isNotNull().isNotEmpty(); + for (String dump : dumpFiles) { + validator.getSurefireReportsFile(dump).assertContainsText(message); } } - private static boolean verifiedErrorInLog( OutputValidator validator, String errorText ) - { - try - { - validator.verifyTextInLog( errorText ); + private static boolean verifiedErrorInLog(OutputValidator validator, String errorText) { + try { + validator.verifyTextInLog(errorText); return true; - } - catch ( SurefireVerifierException e ) - { + } catch (SurefireVerifierException e) { return false; } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1426JvmCrashShouldNotBeIgnoredIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1426JvmCrashShouldNotBeIgnoredIT.java index 5a575abbe7..ae4976f938 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1426JvmCrashShouldNotBeIgnoredIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1426JvmCrashShouldNotBeIgnoredIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its.jiras; /* @@ -30,18 +48,15 @@ * Test https://issues.apache.org/jira/browse/SUREFIRE-1426 * */ -public class Surefire1426JvmCrashShouldNotBeIgnoredIT - extends SurefireJUnit4IntegrationTestCase -{ +public class Surefire1426JvmCrashShouldNotBeIgnoredIT extends SurefireJUnit4IntegrationTestCase { @Test - public void mavenShouldFail() throws VerificationException - { - unpack( "surefire-1426-ignore-fail-jvm-crash" ) - .maven() - .withFailure() - .debugLogging() - .executeTest() - .assertThatLogLine( containsString( "BUILD SUCCESS" ), is( 0 ) ) - .verifyTextInLog( "BUILD FAILURE" ); + public void mavenShouldFail() throws VerificationException { + unpack("surefire-1426-ignore-fail-jvm-crash") + .maven() + .withFailure() + .debugLogging() + .executeTest() + .assertThatLogLine(containsString("BUILD SUCCESS"), is(0)) + .verifyTextInLog("BUILD FAILURE"); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire146ForkPerTestNoSetupIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire146ForkPerTestNoSetupIT.java index 7e50f2569e..88ca9fd11e 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire146ForkPerTestNoSetupIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire146ForkPerTestNoSetupIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its.jiras; /* @@ -27,12 +45,9 @@ * * @author Dan Fabulich */ -public class Surefire146ForkPerTestNoSetupIT - extends SurefireJUnit4IntegrationTestCase -{ +public class Surefire146ForkPerTestNoSetupIT extends SurefireJUnit4IntegrationTestCase { @Test - public void testForkPerTestNoSetup() - { - executeErrorFreeTest( "surefire-146-forkPerTestNoSetup", 1 ); + public void testForkPerTestNoSetup() { + executeErrorFreeTest("surefire-146-forkPerTestNoSetup", 1); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1490ReportTitleDescriptionIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1490ReportTitleDescriptionIT.java index 289edec959..541fd130b5 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1490ReportTitleDescriptionIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1490ReportTitleDescriptionIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its.jiras; /* @@ -29,65 +47,60 @@ * @see SUREFIRE-1490 * @since 3.0.0-M1 */ -public class Surefire1490ReportTitleDescriptionIT - extends SurefireJUnit4IntegrationTestCase -{ +public class Surefire1490ReportTitleDescriptionIT extends SurefireJUnit4IntegrationTestCase { @Test - public void shouldHaveDefaultReportTitleAndDescription() - { - OutputValidator validator = unpack() - .addGoal( "verify" ) - .execute( "site" ) - .verifyErrorFreeLog(); + public void shouldHaveDefaultReportTitleAndDescription() { + OutputValidator validator = unpack().addGoal("verify").execute("site").verifyErrorFreeLog(); - validator.getSiteFile( "project-reports.html" ) - .assertContainsText( "Surefire Report" ) - .assertContainsText( "Report on the test results of the project." ) - .assertContainsText( "Failsafe Report" ) - .assertContainsText( "Report on the integration test results of the project." ); + validator + .getSiteFile("project-reports.html") + .assertContainsText("Surefire Report") + .assertContainsText("Report on the test results of the project.") + .assertContainsText("Failsafe Report") + .assertContainsText("Report on the integration test results of the project."); - validator.getSiteFile( "failsafe-report.html" ) - .assertContainsText( "Failsafe Report" ) - .assertContainsText( "Surefire1490IT" ); + validator + .getSiteFile("failsafe-report.html") + .assertContainsText("Failsafe Report") + .assertContainsText("Surefire1490IT"); - validator.getSiteFile( "surefire-report.html" ) - .assertContainsText( "Surefire Report" ) - .assertContainsText( "Surefire1490Test" ); + validator + .getSiteFile("surefire-report.html") + .assertContainsText("Surefire Report") + .assertContainsText("Surefire1490Test"); } @Test - public void shouldHaveCustomizedReportTitleAndDescription() - { - OutputValidator validator = unpack() - .sysProp( "failsafe.report.title", "failsafe title" ) - .sysProp( "failsafe.report.description", "failsafe desc" ) - .sysProp( "surefire.report.title", "surefire title" ) - .sysProp( "surefire.report.description", "surefire desc" ) - .addGoal( "verify" ) - .execute( "site" ) + public void shouldHaveCustomizedReportTitleAndDescription() { + OutputValidator validator = unpack().sysProp("failsafe.report.title", "failsafe title") + .sysProp("failsafe.report.description", "failsafe desc") + .sysProp("surefire.report.title", "surefire title") + .sysProp("surefire.report.description", "surefire desc") + .addGoal("verify") + .execute("site") .verifyErrorFreeLog(); - validator.getSiteFile( "project-reports.html" ) - .assertContainsText( "surefire title" ) - .assertContainsText( "surefire desc" ) - .assertContainsText( "failsafe title" ) - .assertContainsText( "failsafe desc" ); + validator + .getSiteFile("project-reports.html") + .assertContainsText("surefire title") + .assertContainsText("surefire desc") + .assertContainsText("failsafe title") + .assertContainsText("failsafe desc"); - validator.getSiteFile( "failsafe-report.html" ) - .assertContainsText( "failsafe title" ) - .assertContainsText( "Surefire1490IT" ); + validator + .getSiteFile("failsafe-report.html") + .assertContainsText("failsafe title") + .assertContainsText("Surefire1490IT"); - validator.getSiteFile( "surefire-report.html" ) - .assertContainsText( "surefire title" ) - .assertContainsText( "Surefire1490Test" ); + validator + .getSiteFile("surefire-report.html") + .assertContainsText("surefire title") + .assertContainsText("Surefire1490Test"); } - public SurefireLauncher unpack() - { - SurefireLauncher unpack = unpack( "surefire-1490" ); - unpack.sysProp( "user.language", "en" ) - .maven() - .execute( "clean" ); + public SurefireLauncher unpack() { + SurefireLauncher unpack = unpack("surefire-1490"); + unpack.sysProp("user.language", "en").maven().execute("clean"); return unpack; } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1534ReuseForksFalseWithJavaModuleIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1534ReuseForksFalseWithJavaModuleIT.java index 0cc03e96a7..faa3fa3113 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1534ReuseForksFalseWithJavaModuleIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1534ReuseForksFalseWithJavaModuleIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its.jiras; /* @@ -30,69 +48,58 @@ /** * */ -public class Surefire1534ReuseForksFalseWithJavaModuleIT - extends AbstractJava9PlusIT -{ +public class Surefire1534ReuseForksFalseWithJavaModuleIT extends AbstractJava9PlusIT { @Test - public void testExecuteWithReuseForksFalseWithJavaModule() - { - OutputValidator validator = assumeJava9() - .reuseForks( false ) - .forkCount( 1 ) - .executeTest(); + public void testExecuteWithReuseForksFalseWithJavaModule() { + OutputValidator validator = assumeJava9().reuseForks(false).forkCount(1).executeTest(); - validator.assertTestSuiteResults( 2, 0, 0, 0 ); + validator.assertTestSuiteResults(2, 0, 0, 0); validator.verifyErrorFreeLog(); - TestFile report = validator.getSurefireReportsFile( "TEST-it.MainTest.xml", UTF_8 ); - assertTrue( report.exists() ); - report.assertContainsText( "" ) - .assertContainsText( "" ) - .assertContainsText( "") + .assertContainsText("") + .assertContainsText("" ) - .assertContainsText( "" ) - .assertContainsText( "") + .assertContainsText("") + .assertContainsText("" ) - .assertContainsText( "") + .assertContainsText("SUREFIRE-1570 */ -@SuppressWarnings( "checkstyle:magicnumber" ) -public class Surefire1570ModularFailsafeIT - extends AbstractJava9PlusIT -{ +@SuppressWarnings("checkstyle:magicnumber") +public class Surefire1570ModularFailsafeIT extends AbstractJava9PlusIT { @Test - public void shouldRunWithJupiterApi() throws Exception - { + public void shouldRunWithJupiterApi() throws Exception { assumeJava9() - .debugLogging() - .executeVerify() - .verifyErrorFreeLog() - .assertThatLogLine( containsString( "Lets see JDKModulePath" ), is( 2 ) ) - .assertThatLogLine( containsString( "Lets see JDKModulePath: null" ), is( 0 ) ); + .debugLogging() + .executeVerify() + .verifyErrorFreeLog() + .assertThatLogLine(containsString("Lets see JDKModulePath"), is(2)) + .assertThatLogLine(containsString("Lets see JDKModulePath: null"), is(0)); } @Override - protected String getProjectDirectoryName() - { + protected String getProjectDirectoryName() { return "surefire-1570"; } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1585IT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1585IT.java index 35baa0f4ac..fedbb30ff9 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1585IT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1585IT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its.jiras; /* @@ -25,25 +43,15 @@ /** * */ -@SuppressWarnings( "checkstyle:magicnumber" ) -public class Surefire1585IT - extends SurefireJUnit4IntegrationTestCase -{ +@SuppressWarnings("checkstyle:magicnumber") +public class Surefire1585IT extends SurefireJUnit4IntegrationTestCase { @Test - public void shouldRunWithJupiterApi() - { - unpack( "surefire-1585-jupiter-api" ) - .debugLogging() - .executeTest() - .verifyErrorFree( 1 ); + public void shouldRunWithJupiterApi() { + unpack("surefire-1585-jupiter-api").debugLogging().executeTest().verifyErrorFree(1); } @Test - public void shouldRunWithVintage() - { - unpack( "surefire-1585-junit4-vintage" ) - .debugLogging() - .executeTest() - .verifyErrorFree( 1 ); + public void shouldRunWithVintage() { + unpack("surefire-1585-junit4-vintage").debugLogging().executeTest().verifyErrorFree(1); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire162CharsetProviderIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire162CharsetProviderIT.java index 8d6a540489..ebaa0b5fed 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire162CharsetProviderIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire162CharsetProviderIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its.jiras; /* @@ -33,22 +51,18 @@ * * @author Dan Fabulich */ -public class Surefire162CharsetProviderIT - extends SurefireJUnit4IntegrationTestCase -{ - @SuppressWarnings( { "ResultOfMethodCallIgnored" } ) +public class Surefire162CharsetProviderIT extends SurefireJUnit4IntegrationTestCase { + @SuppressWarnings({"ResultOfMethodCallIgnored"}) @Test - public void testCharsetProvider() - throws Exception - { - SurefireLauncher unpack = unpack( "/surefire-162-charsetProvider" ); + public void testCharsetProvider() throws Exception { + SurefireLauncher unpack = unpack("/surefire-162-charsetProvider"); MavenLauncher maven = unpack.maven(); OutputValidator verifier = maven.getValidator(); - File jarFile = maven.getArtifactPath( "jcharset", "jcharset", "1.2.1", "jar" ); - File pomFile = maven.getArtifactPath( "jcharset", "jcharset", "1.2.1", "pom" ); + File jarFile = maven.getArtifactPath("jcharset", "jcharset", "1.2.1", "jar"); + File pomFile = maven.getArtifactPath("jcharset", "jcharset", "1.2.1", "pom"); jarFile.getParentFile().mkdirs(); - FileUtils.copyFile( verifier.getSubFile( "repo/jcharset/jcharset/1.2.1/jcharset-1.2.1.jar" ), jarFile ); - FileUtils.copyFile( verifier.getSubFile( "repo/jcharset/jcharset/1.2.1/jcharset-1.2.1.pom" ), pomFile ); - unpack.executeTest().verifyErrorFree( 1 ); + FileUtils.copyFile(verifier.getSubFile("repo/jcharset/jcharset/1.2.1/jcharset-1.2.1.jar"), jarFile); + FileUtils.copyFile(verifier.getSubFile("repo/jcharset/jcharset/1.2.1/jcharset-1.2.1.pom"), pomFile); + unpack.executeTest().verifyErrorFree(1); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1712ExtractedModulenameWithoutASMIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1712ExtractedModulenameWithoutASMIT.java index 69caf52387..cc9390a734 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1712ExtractedModulenameWithoutASMIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1712ExtractedModulenameWithoutASMIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its.jiras; /* @@ -31,25 +49,20 @@ * @author Tibor Digana (tibor17) * @since 3.0.0-M4 */ -public class Surefire1712ExtractedModulenameWithoutASMIT - extends AbstractJava9PlusIT -{ +public class Surefire1712ExtractedModulenameWithoutASMIT extends AbstractJava9PlusIT { @Test - public void test() - throws Exception - { + public void test() throws Exception { assumeJava9() - .debugLogging() - .executeTest() - .assertTestSuiteResults( 1, 0, 0, 0 ) - .assertThatLogLine( containsString( "Unsupported class file major version" ), is( 0 ) ) - .assertThatLogLine( containsString( "at org.objectweb.asm.ClassReader." ), is( 0 ) ) - .verifyTextInLog( "main module descriptor name: wtf.g4s8.oot" ); + .debugLogging() + .executeTest() + .assertTestSuiteResults(1, 0, 0, 0) + .assertThatLogLine(containsString("Unsupported class file major version"), is(0)) + .assertThatLogLine(containsString("at org.objectweb.asm.ClassReader."), is(0)) + .verifyTextInLog("main module descriptor name: wtf.g4s8.oot"); } @Override - protected String getProjectDirectoryName() - { + protected String getProjectDirectoryName() { return "surefire-1712-extracted-modulename-without-asm"; } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1733JUnitIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1733JUnitIT.java index c0235ebbd4..86ee550e45 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1733JUnitIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1733JUnitIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its.jiras; /* @@ -28,28 +46,25 @@ /** * Integration test for SUREFIRE-1733. */ -public class Surefire1733JUnitIT extends AbstractJava9PlusIT -{ +public class Surefire1733JUnitIT extends AbstractJava9PlusIT { @Test - public void test() throws Exception - { + public void test() throws Exception { assumeJava9() - .debugLogging() - .executeVerify() - .assertTestSuiteResults( 1, 0, 0, 0 ) - .assertIntegrationTestSuiteResults( 1, 0, 0, 0 ) - .assertThatLogLine( containsString( "Running test.MyTest" ), is( 1 ) ) - .assertThatLogLine( containsString( "Running test.MyIT" ), is( 1 ) ) - .assertThatLogLine( containsString( "class main.Service in the module \"main\"" ), is( 2 ) ) - .assertThatLogLine( containsString( "class test.MyTest in the module \"test\"" ), is( 1 ) ) - .assertThatLogLine( containsString( "class test.MyIT in the module \"test\"" ), is( 1 ) ) - .assertThatLogLine( containsString( "Hi there!" ), is( 4 ) ) - .assertThatLogLine( containsString( "Hello!" ), is( 4 ) ); + .debugLogging() + .executeVerify() + .assertTestSuiteResults(1, 0, 0, 0) + .assertIntegrationTestSuiteResults(1, 0, 0, 0) + .assertThatLogLine(containsString("Running test.MyTest"), is(1)) + .assertThatLogLine(containsString("Running test.MyIT"), is(1)) + .assertThatLogLine(containsString("class main.Service in the module \"main\""), is(2)) + .assertThatLogLine(containsString("class test.MyTest in the module \"test\""), is(1)) + .assertThatLogLine(containsString("class test.MyIT in the module \"test\""), is(1)) + .assertThatLogLine(containsString("Hi there!"), is(4)) + .assertThatLogLine(containsString("Hello!"), is(4)); } @Override - protected String getProjectDirectoryName() - { + protected String getProjectDirectoryName() { return "surefire-1733-junit4"; } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1733TestngIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1733TestngIT.java index 7fbf03a53a..d0984ec386 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1733TestngIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1733TestngIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its.jiras; /* @@ -28,26 +46,23 @@ /** * Integration test for SUREFIRE-1733. */ -public class Surefire1733TestngIT extends AbstractJava9PlusIT -{ +public class Surefire1733TestngIT extends AbstractJava9PlusIT { @Test - public void test() throws Exception - { + public void test() throws Exception { assumeJava9() - .debugLogging() - .executeVerify() - .assertTestSuiteResults( 1, 0, 0, 0 ) - .assertIntegrationTestSuiteResults( 1, 0, 0, 0 ) - .assertThatLogLine( containsString( "Running test.MyTest" ), is( 1 ) ) - .assertThatLogLine( containsString( "Running test.MyIT" ), is( 1 ) ) - .assertThatLogLine( containsString( "class main.Service in the module \"main\"" ), is( 2 ) ) - .assertThatLogLine( containsString( "class test.MyTest in the module \"test\"" ), is( 1 ) ) - .assertThatLogLine( containsString( "class test.MyIT in the module \"test\"" ), is( 1 ) ); + .debugLogging() + .executeVerify() + .assertTestSuiteResults(1, 0, 0, 0) + .assertIntegrationTestSuiteResults(1, 0, 0, 0) + .assertThatLogLine(containsString("Running test.MyTest"), is(1)) + .assertThatLogLine(containsString("Running test.MyIT"), is(1)) + .assertThatLogLine(containsString("class main.Service in the module \"main\""), is(2)) + .assertThatLogLine(containsString("class test.MyTest in the module \"test\""), is(1)) + .assertThatLogLine(containsString("class test.MyIT in the module \"test\""), is(1)); } @Override - protected String getProjectDirectoryName() - { + protected String getProjectDirectoryName() { return "surefire-1733-testng"; } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1744AlwaysIncludeOutputLogsIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1744AlwaysIncludeOutputLogsIT.java index 5c4cfafe9e..ee75a66dfe 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1744AlwaysIncludeOutputLogsIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1744AlwaysIncludeOutputLogsIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its.jiras; /* @@ -28,15 +46,13 @@ * * @author Dan Fabulich */ -public class Surefire1744AlwaysIncludeOutputLogsIT - extends SurefireJUnit4IntegrationTestCase -{ +public class Surefire1744AlwaysIncludeOutputLogsIT extends SurefireJUnit4IntegrationTestCase { @Test - public void testAlwaysIncludeOutputLogs() - { - OutputValidator outputValidator = unpack( "/surefire-1744-alwaysIncludeOutputLogs" ).executeTest(); + public void testAlwaysIncludeOutputLogs() { + OutputValidator outputValidator = + unpack("/surefire-1744-alwaysIncludeOutputLogs").executeTest(); - outputValidator.verifyTextInLog( "Log output should be included in the report" ); - outputValidator.verifyTextInLog( "System-out output should be included in the report" ); + outputValidator.verifyTextInLog("Log output should be included in the report"); + outputValidator.verifyTextInLog("System-out output should be included in the report"); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1787JUnit5IT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1787JUnit5IT.java index ede3d11b84..8e984d7972 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1787JUnit5IT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1787JUnit5IT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its.jiras; /* @@ -28,132 +46,120 @@ /** * */ -@SuppressWarnings( "checkstyle:magicnumber" ) -public class Surefire1787JUnit5IT extends SurefireJUnit4IntegrationTestCase -{ +@SuppressWarnings("checkstyle:magicnumber") +public class Surefire1787JUnit5IT extends SurefireJUnit4IntegrationTestCase { @Test - public void bothEngines() - { - unpack( "junit-4-5" ) - .activateProfile( "both-engines" ) - .executeTest() - .verifyErrorFree( 2 ) - .verifyTextInLog( "Running pkg.JUnit4Test" ) - .verifyTextInLog( "Running pkg.JUnit5Test" ) - .verifyTextInLog( - "Using auto detected provider org.apache.maven.surefire.junitplatform.JUnitPlatformProvider" ); + public void bothEngines() { + unpack("junit-4-5") + .activateProfile("both-engines") + .executeTest() + .verifyErrorFree(2) + .verifyTextInLog("Running pkg.JUnit4Test") + .verifyTextInLog("Running pkg.JUnit5Test") + .verifyTextInLog( + "Using auto detected provider org.apache.maven.surefire.junitplatform.JUnitPlatformProvider"); } @Test - public void apiAndEngine() - { - unpack( "junit-4-5" ) - .activateProfile( "api-and-engines" ) - .executeTest() - .verifyErrorFree( 2 ) - .verifyTextInLog( "Running pkg.JUnit4Test" ) - .verifyTextInLog( "Running pkg.JUnit5Test" ) - .verifyTextInLog( - "Using auto detected provider org.apache.maven.surefire.junitplatform.JUnitPlatformProvider" ); - + public void apiAndEngine() { + unpack("junit-4-5") + .activateProfile("api-and-engines") + .executeTest() + .verifyErrorFree(2) + .verifyTextInLog("Running pkg.JUnit4Test") + .verifyTextInLog("Running pkg.JUnit5Test") + .verifyTextInLog( + "Using auto detected provider org.apache.maven.surefire.junitplatform.JUnitPlatformProvider"); } @Test - public void bothApis() - { - unpack( "junit-4-5" ) - .activateProfile( "both-api" ) - .executeTest() - .verifyErrorFree( 2 ) - .verifyTextInLog( "Running pkg.JUnit4Test" ) - .verifyTextInLog( "Running pkg.JUnit5Test" ) - .verifyTextInLog( - "Using auto detected provider org.apache.maven.surefire.junitplatform.JUnitPlatformProvider" ); + public void bothApis() { + unpack("junit-4-5") + .activateProfile("both-api") + .executeTest() + .verifyErrorFree(2) + .verifyTextInLog("Running pkg.JUnit4Test") + .verifyTextInLog("Running pkg.JUnit5Test") + .verifyTextInLog( + "Using auto detected provider org.apache.maven.surefire.junitplatform.JUnitPlatformProvider"); } @Test - public void selectJUnit4() - { - unpack( "junit-4-5" ) - .activateProfile( "select-junit4" ) - .executeTest() - .verifyErrorFree( 1 ) - .verifyTextInLog( "Running pkg.JUnit4Test" ) - .verifyTextInLog( - "Using auto detected provider org.apache.maven.surefire.junitplatform.JUnitPlatformProvider" ); + public void selectJUnit4() { + unpack("junit-4-5") + .activateProfile("select-junit4") + .executeTest() + .verifyErrorFree(1) + .verifyTextInLog("Running pkg.JUnit4Test") + .verifyTextInLog( + "Using auto detected provider org.apache.maven.surefire.junitplatform.JUnitPlatformProvider"); } @Test - public void selectJUnit5() - { - unpack( "junit-4-5" ) - .activateProfile( "select-junit5" ) - .executeTest() - .verifyErrorFree( 1 ) - .verifyTextInLog( "Running pkg.JUnit5Test" ) - .verifyTextInLog( - "Using auto detected provider org.apache.maven.surefire.junitplatform.JUnitPlatformProvider" ); + public void selectJUnit5() { + unpack("junit-4-5") + .activateProfile("select-junit5") + .executeTest() + .verifyErrorFree(1) + .verifyTextInLog("Running pkg.JUnit5Test") + .verifyTextInLog( + "Using auto detected provider org.apache.maven.surefire.junitplatform.JUnitPlatformProvider"); } @Test - public void testNg() - { - unpack( "junit5-testng" ) - .activateProfile( "testng-only" ) - .executeTest() - .verifyErrorFree( 1 ) - .verifyTextInLog( "Running pkg.TestNGTest" ) - .verifyTextInLog( - "Using auto detected provider org.apache.maven.surefire.junitplatform.JUnitPlatformProvider" ); + public void testNg() { + unpack("junit5-testng") + .activateProfile("testng-only") + .executeTest() + .verifyErrorFree(1) + .verifyTextInLog("Running pkg.TestNGTest") + .verifyTextInLog( + "Using auto detected provider org.apache.maven.surefire.junitplatform.JUnitPlatformProvider"); } @Test - public void testNgWithJupiterApi() - { - unpack( "junit5-testng" ) - .activateProfile( "junit5-api" ) - .executeTest() - .verifyErrorFree( 2 ) - .verifyTextInLog( "Running pkg.JUnit5Test" ) - .verifyTextInLog( "Running pkg.TestNGTest" ) - .verifyTextInLog( - "Using auto detected provider org.apache.maven.surefire.junitplatform.JUnitPlatformProvider" ); + public void testNgWithJupiterApi() { + unpack("junit5-testng") + .activateProfile("junit5-api") + .executeTest() + .verifyErrorFree(2) + .verifyTextInLog("Running pkg.JUnit5Test") + .verifyTextInLog("Running pkg.TestNGTest") + .verifyTextInLog( + "Using auto detected provider org.apache.maven.surefire.junitplatform.JUnitPlatformProvider"); } @Test - public void testNgWithJupiterEngine() - { - unpack( "junit5-testng" ) - .activateProfile( "junit5-engine" ) - .executeTest() - .verifyErrorFree( 2 ) - .verifyTextInLog( "Running pkg.JUnit5Test" ) - .verifyTextInLog( "Running pkg.TestNGTest" ) - .verifyTextInLog( - "Using auto detected provider org.apache.maven.surefire.junitplatform.JUnitPlatformProvider" ); + public void testNgWithJupiterEngine() { + unpack("junit5-testng") + .activateProfile("junit5-engine") + .executeTest() + .verifyErrorFree(2) + .verifyTextInLog("Running pkg.JUnit5Test") + .verifyTextInLog("Running pkg.TestNGTest") + .verifyTextInLog( + "Using auto detected provider org.apache.maven.surefire.junitplatform.JUnitPlatformProvider"); } @Test - public void junit4Runner() - { - unpack( "junit5-runner" ) - .executeTest() - .verifyErrorFree( 1 ) - .verifyTextInLog( "Running pkg.JUnit5Tests" ) - .verifyTextInLog( "Using auto detected provider org.apache.maven.surefire.junit4.JUnit4Provider" ); + public void junit4Runner() { + unpack("junit5-runner") + .executeTest() + .verifyErrorFree(1) + .verifyTextInLog("Running pkg.JUnit5Tests") + .verifyTextInLog("Using auto detected provider org.apache.maven.surefire.junit4.JUnit4Provider"); } @Test - public void junit5Suite() throws Exception - { - unpack( "junit5-suite" ) - .executeTest() - .verifyErrorFree( 1 ) - .verifyTextInLog( - "Using auto detected provider org.apache.maven.surefire.junitplatform.JUnitPlatformProvider" ) - .verifyTextInLog( "Running pkg.JUnit5Test" ) - .verifyTextInLog( "Running pkg.domain.AxTest" ) - .assertThatLogLine( containsString( "Running pkg.domain.BxTest" ), equalTo( 0 ) ); + public void junit5Suite() throws Exception { + unpack("junit5-suite") + .executeTest() + .verifyErrorFree(1) + .verifyTextInLog( + "Using auto detected provider org.apache.maven.surefire.junitplatform.JUnitPlatformProvider") + .verifyTextInLog("Running pkg.JUnit5Test") + .verifyTextInLog("Running pkg.domain.AxTest") + .assertThatLogLine(containsString("Running pkg.domain.BxTest"), equalTo(0)); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1881IT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1881IT.java index 8289b98a1a..71fa0326a7 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1881IT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1881IT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its.jiras; /* @@ -25,16 +43,14 @@ /** * */ -@SuppressWarnings( "checkstyle:magicnumber" ) -public class Surefire1881IT extends SurefireJUnit4IntegrationTestCase -{ +@SuppressWarnings("checkstyle:magicnumber") +public class Surefire1881IT extends SurefireJUnit4IntegrationTestCase { - @Test( timeout = 60_000L ) - public void test() - { - unpack( "/surefire-1881" ) - .executeVerify() - .assertTestSuiteResults( 1, 0, 0, 0 ) - .assertIntegrationTestSuiteResults( 1, 0, 0, 0 ); + @Test(timeout = 60_000L) + public void test() { + unpack("/surefire-1881") + .executeVerify() + .assertTestSuiteResults(1, 0, 0, 0) + .assertIntegrationTestSuiteResults(1, 0, 0, 0); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1914XmlReportingParameterizedTestIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1914XmlReportingParameterizedTestIT.java index 2407771cbd..5b4cdadddc 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1914XmlReportingParameterizedTestIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire1914XmlReportingParameterizedTestIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its.jiras; /* @@ -34,63 +52,61 @@ /** * */ -@RunWith( Parameterized.class ) -@SuppressWarnings( "checkstyle:magicnumber" ) -public class Surefire1914XmlReportingParameterizedTestIT extends SurefireJUnit4IntegrationTestCase -{ +@RunWith(Parameterized.class) +@SuppressWarnings("checkstyle:magicnumber") +public class Surefire1914XmlReportingParameterizedTestIT extends SurefireJUnit4IntegrationTestCase { @Parameter - @SuppressWarnings( "checkstyle:visibilitymodifier" ) + @SuppressWarnings("checkstyle:visibilitymodifier") public String jupiterVersion; - @Parameters( name = "{0}" ) - public static Iterable junitJupiterVersions() - { - return Arrays.asList( "5.2.0", "5.8.2", "5.9.1" ); + @Parameters(name = "{0}") + public static Iterable junitJupiterVersions() { + return Arrays.asList("5.2.0", "5.8.2", "5.9.1"); } @Test - public void testXmlReport() - { - OutputValidator validator = unpack( "surefire-1914-xml-reporting-parameterizedtest", "-" + jupiterVersion ) - .sysProp( "junit5.version", jupiterVersion ) + public void testXmlReport() { + OutputValidator validator = unpack("surefire-1914-xml-reporting-parameterizedtest", "-" + jupiterVersion) + .sysProp("junit5.version", jupiterVersion) .executeTest() - .verifyErrorFree( 16 ); + .verifyErrorFree(16); - validator.getSurefireReportsFile( "TEST-jira1914.ParameterizedDisplayNameTest.xml", UTF_8 ) - .assertContainsText( "testcase name=\"theDisplayNameOfTestMethod1[1] a\" " - + "classname=\"theDisplayNameOfTheClass\"" ) - .assertContainsText( "testcase name=\"theDisplayNameOfTestMethod1[2] b\" " - + "classname=\"theDisplayNameOfTheClass\"" ) - .assertContainsText( "testcase name=\"theDisplayNameOfTestMethod1[3] c\" " - + "classname=\"theDisplayNameOfTheClass\"" ) - .assertContainsText( "testcase name=\"theDisplayNameOfTestMethod2 with param a\" " - + "classname=\"theDisplayNameOfTheClass\"" ) - .assertContainsText( "testcase name=\"theDisplayNameOfTestMethod2 with param b\" " - + "classname=\"theDisplayNameOfTheClass\"" ) - .assertContainsText( "testcase name=\"theDisplayNameOfTestMethod2 with param c\" " - + "classname=\"theDisplayNameOfTheClass\"" ); + validator + .getSurefireReportsFile("TEST-jira1914.ParameterizedDisplayNameTest.xml", UTF_8) + .assertContainsText("testcase name=\"theDisplayNameOfTestMethod1[1] a\" " + + "classname=\"theDisplayNameOfTheClass\"") + .assertContainsText("testcase name=\"theDisplayNameOfTestMethod1[2] b\" " + + "classname=\"theDisplayNameOfTheClass\"") + .assertContainsText("testcase name=\"theDisplayNameOfTestMethod1[3] c\" " + + "classname=\"theDisplayNameOfTheClass\"") + .assertContainsText("testcase name=\"theDisplayNameOfTestMethod2 with param a\" " + + "classname=\"theDisplayNameOfTheClass\"") + .assertContainsText("testcase name=\"theDisplayNameOfTestMethod2 with param b\" " + + "classname=\"theDisplayNameOfTheClass\"") + .assertContainsText("testcase name=\"theDisplayNameOfTestMethod2 with param c\" " + + "classname=\"theDisplayNameOfTheClass\""); - validator.getSurefireReportsFile( "TEST-jira1914.ParameterizedJupiterTest.xml", UTF_8 ) - .assertContainsText( " redTestCaseResults = Arrays.asList( - redXmlReport.substring( redXmlReport.indexOf( "" ) ) - .split( ".(?= redTestCaseResults = Arrays.asList(redXmlReport + .substring(redXmlReport.indexOf("")) + .split(".(?= testCaseResult.contains( " testCaseResult.contains(" orangeTestCaseResults = Arrays.asList( - orangeXmlReport.substring( orangeXmlReport.indexOf( "" ) ) - .split( ".(?= orangeTestCaseResults = Arrays.asList(orangeXmlReport + .substring(orangeXmlReport.indexOf("")) + .split(".(?= testCaseResult.contains( " testCaseResult.substring( 0, testCaseResult.indexOf( "classname" ) ) ) - .containsExactlyInAnyOrder( - " testCaseResult.contains(" testCaseResult.substring(0, testCaseResult.indexOf("classname"))) + .containsExactlyInAnyOrder("$" ) ) - .assertContainsText( Matchers.matchesPattern( "^ *$" ) ) - .assertContainsText( "$")) + .assertContainsText(Matchers.matchesPattern("^ *$")) + .assertContainsText("$" ) ) - .assertContainsText( Matchers.matchesPattern( "^ *$" ) ) - .assertContainsText( "$")) + .assertContainsText(Matchers.matchesPattern("^ *$")) + .assertContainsText("$" ) ) - .assertContainsText( Matchers.matchesPattern( "^ *$" ) ) - .assertContainsText( "$")) + .assertContainsText(Matchers.matchesPattern("^ *$")) + .assertContainsText("$" ) ) - .assertContainsText( Matchers.matchesPattern( "^ *$" ) ) - .assertContainsText( "$")) + .assertContainsText(Matchers.matchesPattern("^ *$")) + .assertContainsText(" junitJupiterVersions() - { - return Arrays.asList( "5.2.0", "5.8.2", "5.9.1" ); + @Parameters(name = "{0}") + public static Iterable junitJupiterVersions() { + return Arrays.asList("5.2.0", "5.8.2", "5.9.1"); } @Test - public void testXmlReport() - { - OutputValidator validator = unpack( "surefire-2117-xml-reporting-nested", "-" + jupiterVersion ) - .sysProp( "junit5.version", jupiterVersion ) + public void testXmlReport() { + OutputValidator validator = unpack("surefire-2117-xml-reporting-nested", "-" + jupiterVersion) + .sysProp("junit5.version", jupiterVersion) .executeTest() - .verifyErrorFree( 9 ); + .verifyErrorFree(9); - validator.getSurefireReportsFile( "TEST-jira2117.NestedJupiterTest$A.xml", UTF_8 ) - .assertContainsText( " testCaseResults = Arrays.asList( - xmlReport.substring( xmlReport.indexOf( "" ) ) - .split( ".(?= testCaseResults = Arrays.asList(xmlReport + .substring(xmlReport.indexOf("")) + .split(".(?= testCaseResult.contains( " testCaseResult.substring( 0, testCaseResult.indexOf( "classname" ) ) ) + assertThat(testCaseResults) + .hasSize(5) + .filteredOn(testCaseResult -> testCaseResult.contains(" testCaseResult.substring(0, testCaseResult.indexOf("classname"))) .containsExactlyInAnyOrder( "]*disabledParameterized.*" ) ) - .assertContainsText( matchesRegex( ".*]*disabledNonParameterized.*" ) ) - .assertContainsText( "]*enabledParameterized.*" ) ) - .assertNotContainsText( matchesRegex( ".*]*enabledNonParameterized.*" ) ); + validator + .getSurefireReportsFile("TEST-jira2143.DisabledParameterizedTest.xml", UTF_8) + .assertContainsText("]*disabledParameterized.*")) + .assertContainsText(matchesRegex(".*]*disabledNonParameterized.*")) + .assertContainsText("]*enabledParameterized.*")) + .assertNotContainsText(matchesRegex(".*]*enabledNonParameterized.*")); } @Test - public void junit4ParameterizedSkipped() - { - OutputValidator validator = unpack( "surefire-2143-junit4-parameterized-test-skipped" ) + public void junit4ParameterizedSkipped() { + OutputValidator validator = unpack("surefire-2143-junit4-parameterized-test-skipped") .executeTest() - .assertTestSuiteResults( 4, 0, 0, 2 ); + .assertTestSuiteResults(4, 0, 0, 2); String xmlReport = validator - .getSurefireReportsFile( "TEST-jira2143.IgnoredParameterizedTest.xml", UTF_8 ) + .getSurefireReportsFile("TEST-jira2143.IgnoredParameterizedTest.xml", UTF_8) .readFileToString(); - List testCaseResults = Arrays.asList( - xmlReport.substring( xmlReport.indexOf( "" ) ) - .split( ".(?= testCaseResults = Arrays.asList(xmlReport + .substring(xmlReport.indexOf("")) + .split(".(?= testCaseResult.contains( " testCaseResult.substring( 0, testCaseResult.indexOf( "classname" ) ) ) + assertThat(testCaseResults) + .hasSize(4) + .filteredOn(testCaseResult -> testCaseResult.contains(" testCaseResult.substring(0, testCaseResult.indexOf("classname"))) .containsExactlyInAnyOrder( - "Dan Fabulich */ -public class Surefire224WellFormedXmlFailuresIT - extends SurefireJUnit4IntegrationTestCase -{ - @SuppressWarnings( "ConstantConditions" ) +public class Surefire224WellFormedXmlFailuresIT extends SurefireJUnit4IntegrationTestCase { + @SuppressWarnings("ConstantConditions") @Test - public void testWellFormedXmlFailures() - { - OutputValidator outputValidator = unpack( "/surefire-224-wellFormedXmlFailures" ).executeTest(); + public void testWellFormedXmlFailures() { + OutputValidator outputValidator = + unpack("/surefire-224-wellFormedXmlFailures").executeTest(); - outputValidator.assertTestSuiteResults( 4, 0, 4, 0 ); + outputValidator.assertTestSuiteResults(4, 0, 4, 0); - ReportTestSuite suite = HelperAssertions.extractReports( outputValidator.getBaseDir() ).get( 0 ); + ReportTestSuite suite = + HelperAssertions.extractReports(outputValidator.getBaseDir()).get(0); List testCases = suite.getTestCases(); - assertEquals( "Wrong number of test case objects", 4, testCases.size() ); + assertEquals("Wrong number of test case objects", 4, testCases.size()); ReportTestCase testQuote = null, testLower = null, testGreater = null, testU0000 = null; - for ( ReportTestCase current : testCases ) - { - if ( "testQuote".equals( current.getName() ) ) - { + for (ReportTestCase current : testCases) { + if ("testQuote".equals(current.getName())) { testQuote = current; - } - else if ( "testLower".equals( current.getName() ) ) - { + } else if ("testLower".equals(current.getName())) { testLower = current; - } - else if ( "testGreater".equals( current.getName() ) ) - { + } else if ("testGreater".equals(current.getName())) { testGreater = current; - } - else if ( "testU0000".equals( current.getName() ) ) - { + } else if ("testU0000".equals(current.getName())) { testU0000 = current; } } - assertEquals( "Wrong error message", "\"", testQuote.getFailureMessage() ); - assertEquals( "Wrong error message", "<", testLower.getFailureMessage() ); - assertEquals( "Wrong error message", ">", testGreater.getFailureMessage() ); + assertEquals("Wrong error message", "\"", testQuote.getFailureMessage()); + assertEquals("Wrong error message", "<", testLower.getFailureMessage()); + assertEquals("Wrong error message", ">", testGreater.getFailureMessage()); // SUREFIRE-456 we have to doubly-escape non-visible control characters like \u0000 - assertEquals( "Wrong error message", "Hi � there!", testU0000.getFailureMessage() ); + assertEquals("Wrong error message", "Hi � there!", testU0000.getFailureMessage()); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire257NotRerunningTestsIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire257NotRerunningTestsIT.java index 7c5f941b99..62cb13fd6f 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire257NotRerunningTestsIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire257NotRerunningTestsIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its.jiras; /* @@ -27,13 +45,14 @@ * * @author Kristian Rosenvold */ -public class Surefire257NotRerunningTestsIT extends SurefireJUnit4IntegrationTestCase -{ +public class Surefire257NotRerunningTestsIT extends SurefireJUnit4IntegrationTestCase { @Test - public void shouldNotRerun() - { - unpack( "/surefire-257-rerunningTests" ) - .addSurefireReportGoal().addSurefireReportGoal().executeCurrentGoals().verifyTextInLog( - "Skipping execution of surefire because it has already been run for this configuration" ); + public void shouldNotRerun() { + unpack("/surefire-257-rerunningTests") + .addSurefireReportGoal() + .addSurefireReportGoal() + .executeCurrentGoals() + .verifyTextInLog( + "Skipping execution of surefire because it has already been run for this configuration"); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire260TestWithIdenticalNamesIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire260TestWithIdenticalNamesIT.java index 393a21e456..33e5997699 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire260TestWithIdenticalNamesIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire260TestWithIdenticalNamesIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its.jiras; /* @@ -22,14 +40,13 @@ import java.io.IOException; import java.net.URI; -import org.apache.maven.surefire.its.fixture.OutputValidator; -import org.apache.maven.surefire.its.fixture.SurefireJUnit4IntegrationTestCase; -import org.apache.maven.surefire.its.fixture.TestFile; - import com.gargoylesoftware.htmlunit.WebClient; import com.gargoylesoftware.htmlunit.html.HtmlAnchor; import com.gargoylesoftware.htmlunit.html.HtmlDivision; import com.gargoylesoftware.htmlunit.html.HtmlPage; +import org.apache.maven.surefire.its.fixture.OutputValidator; +import org.apache.maven.surefire.its.fixture.SurefireJUnit4IntegrationTestCase; +import org.apache.maven.surefire.its.fixture.TestFile; import org.junit.Test; import static org.junit.Assert.assertFalse; @@ -41,35 +58,30 @@ * * @author Kristian Rosenvold */ -@SuppressWarnings( "checkstyle:magicnumber" ) -public class Surefire260TestWithIdenticalNamesIT - extends SurefireJUnit4IntegrationTestCase -{ +@SuppressWarnings("checkstyle:magicnumber") +public class Surefire260TestWithIdenticalNamesIT extends SurefireJUnit4IntegrationTestCase { @Test - public void testWithIdenticalNames() - throws IOException - { - OutputValidator validator = unpack( "surefire-260-testWithIdenticalNames" ) + public void testWithIdenticalNames() throws IOException { + OutputValidator validator = unpack("surefire-260-testWithIdenticalNames") .failNever() - .addGoal( "site" ) + .addGoal("site") .addSurefireReportGoal() .executeCurrentGoals(); - TestFile siteFile = validator.getSiteFile( "surefire-report.html" ); + TestFile siteFile = validator.getSiteFile("surefire-report.html"); final URI uri = siteFile.toURI(); - try ( WebClient webClient = new WebClient() ) - { - HtmlPage page = webClient.getPage( uri.toURL() ); - HtmlAnchor a = ( HtmlAnchor ) page.getByXPath( - "//a[@href = \"javascript:toggleDisplay('surefire260.TestB.testDup');\"]" ) - .get( 0 ); - HtmlDivision content = ( HtmlDivision ) page.getElementById( "surefire260.TestB.testDup-failure" ); - assertNotNull( content ); - assertTrue( content.getAttribute( "style" ).contains( "none" ) ); + try (WebClient webClient = new WebClient()) { + HtmlPage page = webClient.getPage(uri.toURL()); + HtmlAnchor a = (HtmlAnchor) + page.getByXPath("//a[@href = \"javascript:toggleDisplay('surefire260.TestB.testDup');\"]") + .get(0); + HtmlDivision content = (HtmlDivision) page.getElementById("surefire260.TestB.testDup-failure"); + assertNotNull(content); + assertTrue(content.getAttribute("style").contains("none")); a.click(); - assertFalse( content.getAttribute( "style" ).contains( "none" ) ); + assertFalse(content.getAttribute("style").contains("none")); } } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire34SecurityManagerIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire34SecurityManagerIT.java index 267ddfec61..1924fd6ea1 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire34SecurityManagerIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire34SecurityManagerIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its.jiras; /* @@ -34,42 +52,38 @@ * * @author Kristian Rosenvold */ -@SuppressWarnings( "checkstyle:magicnumber" ) -public class Surefire34SecurityManagerIT - extends SurefireJUnit4IntegrationTestCase -{ +@SuppressWarnings("checkstyle:magicnumber") +public class Surefire34SecurityManagerIT extends SurefireJUnit4IntegrationTestCase { @Test - public void testSecurityManager() - { - assumeJavaMaxVersion( 17 ); - SurefireLauncher surefireLauncher = unpack( "surefire-34-securityManager" ).failNever(); - surefireLauncher.executeTest().assertTestSuiteResults( 2, 1, 0, 0 ); + public void testSecurityManager() { + assumeJavaMaxVersion(17); + SurefireLauncher surefireLauncher = + unpack("surefire-34-securityManager").failNever(); + surefireLauncher.executeTest().assertTestSuiteResults(2, 1, 0, 0); } @Test - public void testSecurityManagerSuccessful() - { - assumeJavaMaxVersion( 17 ); - SurefireLauncher surefireLauncher = unpack( "surefire-34-securityManager-success" ); - surefireLauncher.executeTest().assertTestSuiteResults( 2, 0, 0, 0 ); + public void testSecurityManagerSuccessful() { + assumeJavaMaxVersion(17); + SurefireLauncher surefireLauncher = unpack("surefire-34-securityManager-success"); + surefireLauncher.executeTest().assertTestSuiteResults(2, 0, 0, 0); } @Test - public void shouldFailOnJDK() - { - assumeJavaVersion( 18 ); + public void shouldFailOnJDK() { + assumeJavaVersion(18); - OutputValidator validator = unpack( "surefire-34-securityManager" ) - .failNever() - .executeTest() - .verifyTextInLog( "JDK does not support overriding Security Manager with " - + "a value in system property 'surefire.security.manager'." ); + OutputValidator validator = unpack("surefire-34-securityManager") + .failNever() + .executeTest() + .verifyTextInLog("JDK does not support overriding Security Manager with " + + "a value in system property 'surefire.security.manager'."); - TestFile xmlReport = validator.getSurefireReportsFile( "junit4.SecurityManagerTest.xml" ); + TestFile xmlReport = validator.getSurefireReportsFile("junit4.SecurityManagerTest.xml"); - assertThat( xmlReport.exists() ) - .describedAs( "junit4.SecurityManagerTest.xml should not exist. " - + "The provider should fail before starting any test." ) - .isFalse(); + assertThat(xmlReport.exists()) + .describedAs("junit4.SecurityManagerTest.xml should not exist. " + + "The provider should fail before starting any test.") + .isFalse(); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire376TestNgAfterSuiteFailureIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire376TestNgAfterSuiteFailureIT.java index ebc0e1e824..e25f9d7c52 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire376TestNgAfterSuiteFailureIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire376TestNgAfterSuiteFailureIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its.jiras; /* @@ -27,18 +45,15 @@ * * @author Dan Fabulich */ -public class Surefire376TestNgAfterSuiteFailureIT - extends SurefireJUnit4IntegrationTestCase -{ +public class Surefire376TestNgAfterSuiteFailureIT extends SurefireJUnit4IntegrationTestCase { @Test - public void testAfterSuiteFailure() - { - unpack( "/testng-afterSuiteFailure" ) + public void testAfterSuiteFailure() { + unpack("/testng-afterSuiteFailure") .maven() - .sysProp( "testNgVersion", "5.7" ) - .sysProp( "testNgClassifier", "jdk15" ) + .sysProp("testNgVersion", "5.7") + .sysProp("testNgClassifier", "jdk15") .withFailure() .executeTest() - .assertTestSuiteResults( 2, 0, 1, 0 ); + .assertTestSuiteResults(2, 0, 1, 0); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire377TestNgAndJUnitTogetherIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire377TestNgAndJUnitTogetherIT.java index a29d030306..5892252126 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire377TestNgAndJUnitTogetherIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire377TestNgAndJUnitTogetherIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its.jiras; /* @@ -27,26 +45,22 @@ * * @author Dan Fabulich */ -public class Surefire377TestNgAndJUnitTogetherIT - extends SurefireJUnit4IntegrationTestCase -{ +public class Surefire377TestNgAndJUnitTogetherIT extends SurefireJUnit4IntegrationTestCase { @Test - public void testTestNgAndJUnitTogether() - { - unpack( "/testng-junit-together" ) - .sysProp( "testNgVersion", "5.7" ) - .sysProp( "testNgClassifier", "jdk15" ) + public void testTestNgAndJUnitTogether() { + unpack("/testng-junit-together") + .sysProp("testNgVersion", "5.7") + .sysProp("testNgClassifier", "jdk15") .executeTest() - .verifyErrorFree( 2 ); + .verifyErrorFree(2); } @Test - public void testTestNgAndJUnit4Together() - { - unpack( "/testng-junit4-together" ) - .sysProp( "testNgVersion", "5.7" ) - .sysProp( "testNgClassifier", "jdk15" ) + public void testTestNgAndJUnit4Together() { + unpack("/testng-junit4-together") + .sysProp("testNgVersion", "5.7") + .sysProp("testNgClassifier", "jdk15") .executeTest() - .verifyErrorFree( 3 ); + .verifyErrorFree(3); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire408ManualProviderSelectionIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire408ManualProviderSelectionIT.java index 3287ab4e6d..56621564b5 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire408ManualProviderSelectionIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire408ManualProviderSelectionIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its.jiras; /* @@ -27,16 +45,13 @@ * * @author Kristian Rosenvold */ -public class Surefire408ManualProviderSelectionIT - extends SurefireJUnit4IntegrationTestCase -{ +public class Surefire408ManualProviderSelectionIT extends SurefireJUnit4IntegrationTestCase { @Test - public void testParallelBuildResultCount() - { - unpack( "/surefire-408-manual-provider-selection" ) - .showErrorStackTraces() - .debugLogging() - .executeTest() - .verifyTextInLog( "Using configured provider org.apache.maven.surefire.junit.JUnit3Provider" ); + public void testParallelBuildResultCount() { + unpack("/surefire-408-manual-provider-selection") + .showErrorStackTraces() + .debugLogging() + .executeTest() + .verifyTextInLog("Using configured provider org.apache.maven.surefire.junit.JUnit3Provider"); } -} \ No newline at end of file +} diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire42NotExtendingTestCaseIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire42NotExtendingTestCaseIT.java index 00c2aeefb0..69369f3ccb 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire42NotExtendingTestCaseIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire42NotExtendingTestCaseIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its.jiras; /* @@ -27,12 +45,9 @@ * * @author Dan Fabulich */ -public class Surefire42NotExtendingTestCaseIT - extends SurefireJUnit4IntegrationTestCase -{ +public class Surefire42NotExtendingTestCaseIT extends SurefireJUnit4IntegrationTestCase { @Test - public void testInnerClass() - { - executeErrorFreeTest( "junit-notExtendingTestCase", 1 ); + public void testInnerClass() { + executeErrorFreeTest("junit-notExtendingTestCase", 1); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire44InnerClassTestIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire44InnerClassTestIT.java index 928019a2ea..afe60762b7 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire44InnerClassTestIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire44InnerClassTestIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its.jiras; /* @@ -27,12 +45,9 @@ * * @author Dan Fabulich */ -public class Surefire44InnerClassTestIT - extends SurefireJUnit4IntegrationTestCase -{ +public class Surefire44InnerClassTestIT extends SurefireJUnit4IntegrationTestCase { @Test - public void testInnerClass() - { - executeErrorFreeTest( "/junit-innerClass", 1 ); + public void testInnerClass() { + executeErrorFreeTest("/junit-innerClass", 1); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire500PuzzlingErrorIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire500PuzzlingErrorIT.java index 9356f687bc..55f06fa4ac 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire500PuzzlingErrorIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire500PuzzlingErrorIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its.jiras; /* @@ -29,14 +47,12 @@ * * @author Kristian Rosenvold */ -public class Surefire500PuzzlingErrorIT - extends SurefireJUnit4IntegrationTestCase -{ +public class Surefire500PuzzlingErrorIT extends SurefireJUnit4IntegrationTestCase { @Test - public void testBuildFailingWhenErrors() - { - OutputValidator outputValidator = unpack( "/surefire-500-puzzling-error" ).failNever().executeTest(); - TestFile surefireReportsFile = outputValidator.getSurefireReportsFile( "surefire500.ExplodingTest.txt" ); - surefireReportsFile.assertContainsText( "java.lang.NoClassDefFoundError: whoops!" ); + public void testBuildFailingWhenErrors() { + OutputValidator outputValidator = + unpack("/surefire-500-puzzling-error").failNever().executeTest(); + TestFile surefireReportsFile = outputValidator.getSurefireReportsFile("surefire500.ExplodingTest.txt"); + surefireReportsFile.assertContainsText("java.lang.NoClassDefFoundError: whoops!"); } -} \ No newline at end of file +} diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire510TestClassPathForkModesIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire510TestClassPathForkModesIT.java index 4e4fd13983..428d6a7cb8 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire510TestClassPathForkModesIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire510TestClassPathForkModesIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its.jiras; /* @@ -28,26 +46,19 @@ * * @author Kristian Rosenvold */ -public class Surefire510TestClassPathForkModesIT - extends SurefireJUnit4IntegrationTestCase -{ +public class Surefire510TestClassPathForkModesIT extends SurefireJUnit4IntegrationTestCase { @Test - public void testForkAlways() - { - unpack().forkAlways().executeTest(). - verifyTextInLog( "tcp is set" ); + public void testForkAlways() { + unpack().forkAlways().executeTest().verifyTextInLog("tcp is set"); } @Test - public void testForkOnce() - { - unpack().forkOnce().executeTest(). - verifyTextInLog( "tcp is set" ); + public void testForkOnce() { + unpack().forkOnce().executeTest().verifyTextInLog("tcp is set"); } - public SurefireLauncher unpack() - { - return unpack( "/surefire-510-testClassPath" ); + public SurefireLauncher unpack() { + return unpack("/surefire-510-testClassPath"); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire569RunTestFromDependencyJarsIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire569RunTestFromDependencyJarsIT.java index a46483c141..1aecd87ec7 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire569RunTestFromDependencyJarsIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire569RunTestFromDependencyJarsIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its.jiras; /* @@ -29,17 +47,15 @@ * * @author Aslak Knutsen */ -public class Surefire569RunTestFromDependencyJarsIT extends SurefireJUnit4IntegrationTestCase -{ +public class Surefire569RunTestFromDependencyJarsIT extends SurefireJUnit4IntegrationTestCase { @Test - public void shouldScanAndRunTestsInDependencyJars() throws Exception - { - SurefireLauncher launcher = unpack( "surefire-569-RunTestFromDependencyJars" ); - launcher.addGoal( "test" ).addGoal( "install" ); + public void shouldScanAndRunTestsInDependencyJars() throws Exception { + SurefireLauncher launcher = unpack("surefire-569-RunTestFromDependencyJars"); + launcher.addGoal("test").addGoal("install"); launcher.executeCurrentGoals(); - OutputValidator module1 = launcher.getSubProjectValidator( "module1" ); - module1.assertTestSuiteResults( 1, 0, 0, 0 ); + OutputValidator module1 = launcher.getSubProjectValidator("module1"); + module1.assertTestSuiteResults(1, 0, 0, 0); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire570MultipleReportDirectoriesIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire570MultipleReportDirectoriesIT.java index 20abced0e3..c054aef000 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire570MultipleReportDirectoriesIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire570MultipleReportDirectoriesIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its.jiras; /* @@ -30,41 +48,34 @@ * * @author Kristian Rosenvold */ -public class Surefire570MultipleReportDirectoriesIT - extends SurefireJUnit4IntegrationTestCase -{ +public class Surefire570MultipleReportDirectoriesIT extends SurefireJUnit4IntegrationTestCase { @Test - public void testReportWithAggregate() - { + public void testReportWithAggregate() { SurefireLauncher surefireLauncher = unpack().failNever(); surefireLauncher.executeTest(); - surefireLauncher.addGoal( "-Daggregate=true" ); - OutputValidator validator = surefireLauncher.executeSurefireReport( ); - TestFile siteFile = validator.getSiteFile( "surefire-report.html" ); - siteFile.assertContainsText( "MyModule1ClassTest" ); - siteFile.assertContainsText( "MyModule2ClassTest" ); - siteFile.assertContainsText( "MyDummyClassM1Test" ); + surefireLauncher.addGoal("-Daggregate=true"); + OutputValidator validator = surefireLauncher.executeSurefireReport(); + TestFile siteFile = validator.getSiteFile("surefire-report.html"); + siteFile.assertContainsText("MyModule1ClassTest"); + siteFile.assertContainsText("MyModule2ClassTest"); + siteFile.assertContainsText("MyDummyClassM1Test"); } @Test - public void testReportWithoutAggregate() - throws Exception - { + public void testReportWithoutAggregate() throws Exception { SurefireLauncher surefireLauncher = unpack().failNever(); surefireLauncher.executeTest(); surefireLauncher.reset(); - surefireLauncher.executeSurefireReport( ); - OutputValidator module1 = surefireLauncher.getSubProjectValidator( "module1" ); - TestFile siteFile = module1.getSiteFile( "surefire-report.html" ); - siteFile.assertContainsText( "MyModule1ClassTest" ); - siteFile.assertContainsText( "MyDummyClassM1Test" ); + surefireLauncher.executeSurefireReport(); + OutputValidator module1 = surefireLauncher.getSubProjectValidator("module1"); + TestFile siteFile = module1.getSiteFile("surefire-report.html"); + siteFile.assertContainsText("MyModule1ClassTest"); + siteFile.assertContainsText("MyDummyClassM1Test"); } - public SurefireLauncher unpack() - { - return unpack( "/surefire-570-multipleReportDirectories" ); + public SurefireLauncher unpack() { + return unpack("/surefire-570-multipleReportDirectories"); } - } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire613TestCountInParallelIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire613TestCountInParallelIT.java index 9653693a77..5d89328581 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire613TestCountInParallelIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire613TestCountInParallelIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its.jiras; /* @@ -28,19 +46,17 @@ * * @author Kristian Rosenvold */ -@SuppressWarnings( "checkstyle:magicnumber" ) -public class Surefire613TestCountInParallelIT - extends SurefireJUnit4IntegrationTestCase -{ +@SuppressWarnings("checkstyle:magicnumber") +public class Surefire613TestCountInParallelIT extends SurefireJUnit4IntegrationTestCase { @Test - public void testParallelBuildResultCount() - { - OutputValidator validator = unpack( "/surefire-613-testCount-in-parallel" ).failNever().executeTest(); + public void testParallelBuildResultCount() { + OutputValidator validator = + unpack("/surefire-613-testCount-in-parallel").failNever().executeTest(); - validator.verifyTextInLog( "testAllok to stdout" ); - validator.verifyTextInLog( "testAllok to stderr" ); - validator.verifyTextInLog( "testWithException1 to stdout" ); - validator.verifyTextInLog( "testWithException1 to stderr" ); - validator.assertTestSuiteResults( 30, 8, 4, 17 ); + validator.verifyTextInLog("testAllok to stdout"); + validator.verifyTextInLog("testAllok to stderr"); + validator.verifyTextInLog("testWithException1 to stdout"); + validator.verifyTextInLog("testWithException1 to stderr"); + validator.assertTestSuiteResults(30, 8, 4, 17); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire621TestCountingJunit3InParallelIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire621TestCountingJunit3InParallelIT.java index 6d8e014324..dc1e0e4c7a 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire621TestCountingJunit3InParallelIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire621TestCountingJunit3InParallelIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its.jiras; /* @@ -32,67 +50,60 @@ * @author Kristian Rosenvold * @author Tibor Digana (tibor17) */ -public class Surefire621TestCountingJunit3InParallelIT - extends SurefireJUnit4IntegrationTestCase -{ +public class Surefire621TestCountingJunit3InParallelIT extends SurefireJUnit4IntegrationTestCase { /** * SUREFIRE-1264 */ @Test - public void testJunit3AllParallelBuildResultCount() - { - unpack( "surefire-621-testCounting-junit3-in-parallel" ) - .activateProfile( "all-parallel-junit3-testcases" ) - .execute( "integration-test" ) - .assertTestSuiteResults( 6, 0, 0, 0 ); + public void testJunit3AllParallelBuildResultCount() { + unpack("surefire-621-testCounting-junit3-in-parallel") + .activateProfile("all-parallel-junit3-testcases") + .execute("integration-test") + .assertTestSuiteResults(6, 0, 0, 0); } /** * SUREFIRE-621 */ @Test - public void testJunit3ParallelBuildResultCount() - { - unpack( "surefire-621-testCounting-junit3-in-parallel" ) + public void testJunit3ParallelBuildResultCount() { + unpack("surefire-621-testCounting-junit3-in-parallel") .failNever() - .activateProfile( "parallel-junit3-testcases" ) - .execute( "install" ) - .assertTestSuiteResults( 6, 0, 0, 0 ); + .activateProfile("parallel-junit3-testcases") + .execute("install") + .assertTestSuiteResults(6, 0, 0, 0); } /** * SUREFIRE-1264 */ @Test - public void testJunit3BuildResultCount() - { - unpack( "surefire-621-testCounting-junit3-in-parallel" ) - .activateProfile( "junit3-testcases" ) - .execute( "integration-test" ) - .assertTestSuiteResults( 6, 0, 0, 0 ); + public void testJunit3BuildResultCount() { + unpack("surefire-621-testCounting-junit3-in-parallel") + .activateProfile("junit3-testcases") + .execute("integration-test") + .assertTestSuiteResults(6, 0, 0, 0); } /** * SUREFIRE-1264 */ @Test - public void testJunit3ParallelSuiteBuildResultCount() - { - unpack( "surefire-621-testCounting-junit3-in-parallel" ) - .activateProfile( "parallel-junit3-testsuite" ) - .execute( "integration-test" ) - .assertTestSuiteResults( 6, 0, 0, 0 ); + public void testJunit3ParallelSuiteBuildResultCount() { + unpack("surefire-621-testCounting-junit3-in-parallel") + .activateProfile("parallel-junit3-testsuite") + .execute("integration-test") + .assertTestSuiteResults(6, 0, 0, 0); } /** * SUREFIRE-1264 */ @Test - public void testJunit3SuiteBuildResultCount() - { - unpack( "surefire-621-testCounting-junit3-in-parallel" ) - .activateProfile( "junit3-testsuite" ) - .execute( "integration-test" ) - .assertTestSuiteResults( 6, 0, 0, 0 ); + public void testJunit3SuiteBuildResultCount() { + unpack("surefire-621-testCounting-junit3-in-parallel") + .activateProfile("junit3-testsuite") + .execute("integration-test") + .assertTestSuiteResults(6, 0, 0, 0); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire628ConsoleOutputBeforeAndAfterClassIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire628ConsoleOutputBeforeAndAfterClassIT.java index 27f9572286..d8b98001ba 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire628ConsoleOutputBeforeAndAfterClassIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire628ConsoleOutputBeforeAndAfterClassIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its.jiras; /* @@ -28,21 +46,20 @@ * * @author Kristian Rosenvold assertContainsText */ -public class Surefire628ConsoleOutputBeforeAndAfterClassIT - extends SurefireJUnit4IntegrationTestCase -{ +public class Surefire628ConsoleOutputBeforeAndAfterClassIT extends SurefireJUnit4IntegrationTestCase { @Test - public void testJunit3ParallelBuildResultCount() - { - OutputValidator validator = - unpack( "surefire-628-consoleoutputbeforeandafterclass" ).failNever().parallelMethods().executeTest(); + public void testJunit3ParallelBuildResultCount() { + OutputValidator validator = unpack("surefire-628-consoleoutputbeforeandafterclass") + .failNever() + .parallelMethods() + .executeTest(); - validator.verifyTextInLog( "628Test1" ); - validator.verifyTextInLog( "Before628Test1" ); - validator.verifyTextInLog( "After628Test1" ); - validator.verifyTextInLog( "628Test2" ); - validator.verifyTextInLog( "BeforeClass628Test2" ); - validator.verifyTextInLog( "AfterClass628Test2" ); + validator.verifyTextInLog("628Test1"); + validator.verifyTextInLog("Before628Test1"); + validator.verifyTextInLog("After628Test1"); + validator.verifyTextInLog("628Test2"); + validator.verifyTextInLog("BeforeClass628Test2"); + validator.verifyTextInLog("AfterClass628Test2"); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire634UnsettableSystemPropertiesWarningIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire634UnsettableSystemPropertiesWarningIT.java index 778e776be5..9720b37c45 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire634UnsettableSystemPropertiesWarningIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire634UnsettableSystemPropertiesWarningIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its.jiras; /* @@ -27,13 +45,11 @@ * * @author Kristian Rosenvold */ -public class Surefire634UnsettableSystemPropertiesWarningIT - extends SurefireJUnit4IntegrationTestCase -{ +public class Surefire634UnsettableSystemPropertiesWarningIT extends SurefireJUnit4IntegrationTestCase { @Test - public void testJunit3ParallelBuildResultCount() - { - unpack( "/surefire-634-systemPropertiesWarning" ).executeTest().verifyTextInLog( - "java.library.path cannot be set as system property" ); + public void testJunit3ParallelBuildResultCount() { + unpack("/surefire-634-systemPropertiesWarning") + .executeTest() + .verifyTextInLog("java.library.path cannot be set as system property"); } -} \ No newline at end of file +} diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire649EmptyStringSystemPropertiesIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire649EmptyStringSystemPropertiesIT.java index 7326244260..b6b60c84f1 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire649EmptyStringSystemPropertiesIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire649EmptyStringSystemPropertiesIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its.jiras; /* @@ -32,50 +50,41 @@ * @see SUREFIRE-649 * @since 2.18 */ -public class Surefire649EmptyStringSystemPropertiesIT extends SurefireJUnit4IntegrationTestCase -{ +public class Surefire649EmptyStringSystemPropertiesIT extends SurefireJUnit4IntegrationTestCase { @Test - public void systemProperties() throws VerificationException - { + public void systemProperties() throws VerificationException { SurefireLauncher launcher = unpack1(); - OutputValidator validator = launcher.executeTest().verifyErrorFree( 1 ); + OutputValidator validator = launcher.executeTest().verifyErrorFree(1); - for ( String line : validator.loadLogLines() ) - { - if ( "emptyProperty=''".equals( line ) ) - { + for (String line : validator.loadLogLines()) { + if ("emptyProperty=''".equals(line)) { return; } } - fail( "Could not find text in log: emptyProperty=''" ); + fail("Could not find text in log: emptyProperty=''"); } @Test - public void systemPropertyVariables() throws VerificationException - { + public void systemPropertyVariables() throws VerificationException { SurefireLauncher launcher = unpack2(); - OutputValidator validator = launcher.executeTest().verifyErrorFree( 1 ); + OutputValidator validator = launcher.executeTest().verifyErrorFree(1); - for ( String line : validator.loadLogLines() ) - { - if ( "emptyProperty=''".equals( line ) ) - { + for (String line : validator.loadLogLines()) { + if ("emptyProperty=''".equals(line)) { return; } } - fail( "Could not find text in log: emptyProperty=''" ); + fail("Could not find text in log: emptyProperty=''"); } - private SurefireLauncher unpack1() - { - return unpack( "surefire-649-systemProperties" ); + private SurefireLauncher unpack1() { + return unpack("surefire-649-systemProperties"); } - private SurefireLauncher unpack2() - { - return unpack( "surefire-649-systemPropertyVariables" ); + private SurefireLauncher unpack2() { + return unpack("surefire-649-systemPropertyVariables"); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire673MockitoIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire673MockitoIT.java index 6782e5939c..c7c4d3792d 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire673MockitoIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire673MockitoIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its.jiras; /* @@ -27,15 +45,10 @@ * * @author Kristian Rosenvold */ -@SuppressWarnings( "checkstyle:magicnumber" ) -public class Surefire673MockitoIT - extends SurefireJUnit4IntegrationTestCase -{ +@SuppressWarnings("checkstyle:magicnumber") +public class Surefire673MockitoIT extends SurefireJUnit4IntegrationTestCase { @Test - public void testBuildFailingWhenErrors() - { - unpack( "/surefire-673-mockito" ) - .executeTest() - .assertTestSuiteResults( 1, 0, 0, 0 ); + public void testBuildFailingWhenErrors() { + unpack("/surefire-673-mockito").executeTest().assertTestSuiteResults(1, 0, 0, 0); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire674BuildFailingWhenErrorsIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire674BuildFailingWhenErrorsIT.java index 5aa342f077..dc24841470 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire674BuildFailingWhenErrorsIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire674BuildFailingWhenErrorsIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its.jiras; /* @@ -27,13 +45,13 @@ * * @author Kristian Rosenvold */ -public class Surefire674BuildFailingWhenErrorsIT - extends SurefireJUnit4IntegrationTestCase -{ +public class Surefire674BuildFailingWhenErrorsIT extends SurefireJUnit4IntegrationTestCase { @Test - public void testBuildFailingWhenErrors() - { - unpack( "/surefire-674-buildFailingWhenErrors" ).maven().withFailure().executeTest().verifyTextInLog( - "BUILD FAILURE" ); + public void testBuildFailingWhenErrors() { + unpack("/surefire-674-buildFailingWhenErrors") + .maven() + .withFailure() + .executeTest() + .verifyTextInLog("BUILD FAILURE"); } -} \ No newline at end of file +} diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire674BuildFailingWhenFailsafeErrorsIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire674BuildFailingWhenFailsafeErrorsIT.java index 57c8648899..75fed16a76 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire674BuildFailingWhenFailsafeErrorsIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire674BuildFailingWhenFailsafeErrorsIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its.jiras; /* @@ -27,12 +45,9 @@ * * @author Kristian Rosenvold */ -public class Surefire674BuildFailingWhenFailsafeErrorsIT - extends SurefireJUnit4IntegrationTestCase -{ +public class Surefire674BuildFailingWhenFailsafeErrorsIT extends SurefireJUnit4IntegrationTestCase { @Test - public void testBuildFailingWhenErrors() - { - unpack( "/failsafe-buildfail" ).maven().withFailure().executeVerify().verifyTextInLog( "BUILD FAILURE" ); + public void testBuildFailingWhenErrors() { + unpack("/failsafe-buildfail").maven().withFailure().executeVerify().verifyTextInLog("BUILD FAILURE"); } -} \ No newline at end of file +} diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire685CommaSeparatedIncludesIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire685CommaSeparatedIncludesIT.java index 3d7a684c3f..27193d2d1e 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire685CommaSeparatedIncludesIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire685CommaSeparatedIncludesIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its.jiras; /* @@ -27,12 +45,9 @@ * * @author Kristian Rosenvold */ -public class Surefire685CommaSeparatedIncludesIT - extends SurefireJUnit4IntegrationTestCase -{ +public class Surefire685CommaSeparatedIncludesIT extends SurefireJUnit4IntegrationTestCase { @Test - public void testBuildFailingWhenErrors() - { - executeErrorFreeTest( "/surefire-685-commaseparatedIncludes", 2 ); + public void testBuildFailingWhenErrors() { + executeErrorFreeTest("/surefire-685-commaseparatedIncludes", 2); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire697NiceSummaryIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire697NiceSummaryIT.java index 31751969b6..42d1342803 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire697NiceSummaryIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire697NiceSummaryIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its.jiras; /* @@ -27,13 +45,12 @@ * * @author Kristian Rosenvold */ -public class Surefire697NiceSummaryIT - extends SurefireJUnit4IntegrationTestCase -{ +public class Surefire697NiceSummaryIT extends SurefireJUnit4IntegrationTestCase { @Test - public void testBuildFailingWhenErrors() - { - unpack( "/surefire-697-niceSummary" ).failNever().executeTest().verifyTextInLog( - "junit.surefire697.BasicTest#testShortMultiline RuntimeException A very short m" ); + public void testBuildFailingWhenErrors() { + unpack("/surefire-697-niceSummary") + .failNever() + .executeTest() + .verifyTextInLog("junit.surefire697.BasicTest#testShortMultiline RuntimeException A very short m"); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire705ParallelForkTimeoutIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire705ParallelForkTimeoutIT.java index 6509e493da..fbf7fafe9c 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire705ParallelForkTimeoutIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire705ParallelForkTimeoutIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its.jiras; /* @@ -27,14 +45,17 @@ * * @author Kristian Rosenvold */ -public class Surefire705ParallelForkTimeoutIT extends SurefireJUnit4IntegrationTestCase -{ +public class Surefire705ParallelForkTimeoutIT extends SurefireJUnit4IntegrationTestCase { @Test - public void testTimeoutForked() - { - unpack( "/fork-timeout" ).setJUnitVersion( "4.8.1" ).addGoal( "-Djunit.version=4.8.1" ).addGoal( - "-Djunit.parallel=classes" ).addGoal( - "-DtimeOut=1" ).maven().withFailure().executeTest().verifyTextInLog( - "There was a timeout in the fork" ); + public void testTimeoutForked() { + unpack("/fork-timeout") + .setJUnitVersion("4.8.1") + .addGoal("-Djunit.version=4.8.1") + .addGoal("-Djunit.parallel=classes") + .addGoal("-DtimeOut=1") + .maven() + .withFailure() + .executeTest() + .verifyTextInLog("There was a timeout in the fork"); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire733AllOverrridesCapturedIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire733AllOverrridesCapturedIT.java index aabb05da45..06a1c7b0ae 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire733AllOverrridesCapturedIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire733AllOverrridesCapturedIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its.jiras; /* @@ -25,12 +43,9 @@ /** * @author Kristian Rosenvold */ -public class Surefire733AllOverrridesCapturedIT - extends SurefireJUnit4IntegrationTestCase -{ +public class Surefire733AllOverrridesCapturedIT extends SurefireJUnit4IntegrationTestCase { @Test - public void testLogOutput() - { - unpack( "surefire-733-allOverridesCaptured" ).executeTest().verifyTextInLog( "abc" ); + public void testLogOutput() { + unpack("surefire-733-allOverridesCaptured").executeTest().verifyTextInLog("abc"); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire735ForkFailWithRedirectConsoleOutputIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire735ForkFailWithRedirectConsoleOutputIT.java index 6dd0e05973..7a195ec3da 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire735ForkFailWithRedirectConsoleOutputIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire735ForkFailWithRedirectConsoleOutputIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its.jiras; /* @@ -19,51 +37,44 @@ * under the License. */ +import java.io.File; +import java.io.FilenameFilter; +import java.util.Collection; + import org.apache.maven.it.VerificationException; import org.apache.maven.surefire.its.fixture.OutputValidator; import org.apache.maven.surefire.its.fixture.SurefireJUnit4IntegrationTestCase; import org.apache.maven.surefire.its.fixture.SurefireLauncher; import org.junit.Test; -import java.io.File; -import java.io.FilenameFilter; -import java.util.Collection; - import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.CoreMatchers.containsString; /** * @author Kristian Rosenvold */ -public class Surefire735ForkFailWithRedirectConsoleOutputIT - extends SurefireJUnit4IntegrationTestCase -{ +public class Surefire735ForkFailWithRedirectConsoleOutputIT extends SurefireJUnit4IntegrationTestCase { @Test - public void vmStartFail() throws VerificationException - { + public void vmStartFail() throws VerificationException { OutputValidator outputValidator = unpack().failNever().executeTest(); - assertJvmCrashed( outputValidator ); + assertJvmCrashed(outputValidator); } @Test - public void vmStartFailShouldFailBuildk() throws VerificationException - { + public void vmStartFailShouldFailBuildk() throws VerificationException { OutputValidator outputValidator = unpack().maven().withFailure().executeTest(); - assertJvmCrashed( outputValidator ); + assertJvmCrashed(outputValidator); } - private SurefireLauncher unpack() - { - return unpack( "fork-fail" ); + private SurefireLauncher unpack() { + return unpack("fork-fail"); } - private static void assertJvmCrashed( OutputValidator outputValidator ) throws VerificationException - { + private static void assertJvmCrashed(OutputValidator outputValidator) throws VerificationException { Collection matchedLines = - outputValidator.loadLogLines( containsString( "Invalid maximum heap size: -Xmxxxx712743m" ) ); - if ( !matchedLines.isEmpty() ) - { + outputValidator.loadLogLines(containsString("Invalid maximum heap size: -Xmxxxx712743m")); + if (!matchedLines.isEmpty()) { // the error line was printed in std/err by the JVM return; } @@ -71,23 +82,19 @@ private static void assertJvmCrashed( OutputValidator outputValidator ) throws V // the error line should be printed in std/out by the JVM if we use the process pipes // then the ForkClient caught it and printed in the dump stream File reportDir = outputValidator.getSurefireReportsDirectory(); - String[] dumpFiles = reportDir.list( new FilenameFilter() - { - @Override - public boolean accept( File dir, String name ) - { - return name.endsWith( ".dumpstream" ) - && !name.contains( "-jvmRun1" ); - } - } - ); + String[] dumpFiles = reportDir.list(new FilenameFilter() { + @Override + public boolean accept(File dir, String name) { + return name.endsWith(".dumpstream") && !name.contains("-jvmRun1"); + } + }); - assertThat( dumpFiles ).isNotEmpty(); + assertThat(dumpFiles).isNotEmpty(); - for ( String dump : dumpFiles ) - { - outputValidator.getSurefireReportsFile( dump ) - .assertContainsText( "Invalid maximum heap size: -Xmxxxx712743m" ); + for (String dump : dumpFiles) { + outputValidator + .getSurefireReportsFile(dump) + .assertContainsText("Invalid maximum heap size: -Xmxxxx712743m"); } } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire740TruncatedCommaIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire740TruncatedCommaIT.java index 70484ca39e..13494124bc 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire740TruncatedCommaIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire740TruncatedCommaIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its.jiras; /* @@ -31,21 +49,17 @@ * * @author Kristian Rosenvold */ -public class Surefire740TruncatedCommaIT - extends SurefireJUnit4IntegrationTestCase -{ +public class Surefire740TruncatedCommaIT extends SurefireJUnit4IntegrationTestCase { @Test - public void testRussianLocaleReport() - { - OutputValidator validator = unpack( "/surefire-740-comma-truncated" ) - .setMavenOpts( "-Duser.language=ru -Duser.country=RU" ) + public void testRussianLocaleReport() { + OutputValidator validator = unpack("/surefire-740-comma-truncated") + .setMavenOpts("-Duser.language=ru -Duser.country=RU") .failNever() .addSurefireReportGoal() .executeCurrentGoals(); - TestFile siteFile = validator.getSiteFile( "surefire-report.html" ); - assertTrue( "Expecting file", siteFile.exists() ); - siteFile.assertContainsText( "027" ); // Avoid asserting with the "," or "." ;) + TestFile siteFile = validator.getSiteFile("surefire-report.html"); + assertTrue("Expecting file", siteFile.exists()); + siteFile.assertContainsText("027"); // Avoid asserting with the "," or "." ;) } - } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire747MethodParallelWithSuiteCountIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire747MethodParallelWithSuiteCountIT.java index 77751fe929..335021fac2 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire747MethodParallelWithSuiteCountIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire747MethodParallelWithSuiteCountIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its.jiras; /* @@ -19,6 +37,12 @@ * under the License. */ +import java.text.Format; +import java.text.NumberFormat; +import java.util.Iterator; +import java.util.Set; +import java.util.TreeSet; + import org.apache.maven.it.VerificationException; import org.apache.maven.surefire.its.fixture.OutputValidator; import org.apache.maven.surefire.its.fixture.SurefireJUnit4IntegrationTestCase; @@ -26,12 +50,6 @@ import org.junit.Before; import org.junit.Test; -import java.text.Format; -import java.text.NumberFormat; -import java.util.Iterator; -import java.util.Set; -import java.util.TreeSet; - import static java.lang.String.format; import static java.math.RoundingMode.DOWN; import static java.util.Locale.ROOT; @@ -45,125 +63,106 @@ /** * @author Kristian Rosenvold */ -@SuppressWarnings( "checkstyle:magicnumber" ) -public class Surefire747MethodParallelWithSuiteCountIT - extends SurefireJUnit4IntegrationTestCase -{ +@SuppressWarnings("checkstyle:magicnumber") +public class Surefire747MethodParallelWithSuiteCountIT extends SurefireJUnit4IntegrationTestCase { // if you want to change his constant, change it in SuiteTest1.java and SuiteTest2.java as well private static final int PERFORMANCE_TEST_MULTIPLICATION_FACTOR = 4; private Format lowerScaleFormatter, noFractionalDigitsFormatter; - private static Set printTestLines( OutputValidator validator, String pattern ) - throws VerificationException - { - Set log = new TreeSet<>( validator.loadLogLines() ); - for ( Iterator it = log.iterator(); it.hasNext(); ) - { + private static Set printTestLines(OutputValidator validator, String pattern) throws VerificationException { + Set log = new TreeSet<>(validator.loadLogLines()); + for (Iterator it = log.iterator(); it.hasNext(); ) { String line = it.next(); - if ( !line.contains( pattern ) ) - { + if (!line.contains(pattern)) { it.remove(); } } return log; } - private static long duration( String logLine ) - { - return Integer.decode( logLine.split( "=" )[1] ); + private static long duration(String logLine) { + return Integer.decode(logLine.split("=")[1]); } @Before - public void init() - { - NumberFormat lowScaleFormatter = NumberFormat.getInstance( ROOT ); - lowScaleFormatter.setRoundingMode( DOWN ); - lowScaleFormatter.setMinimumFractionDigits( 1 ); - lowScaleFormatter.setMaximumFractionDigits( 1 ); + public void init() { + NumberFormat lowScaleFormatter = NumberFormat.getInstance(ROOT); + lowScaleFormatter.setRoundingMode(DOWN); + lowScaleFormatter.setMinimumFractionDigits(1); + lowScaleFormatter.setMaximumFractionDigits(1); this.lowerScaleFormatter = lowScaleFormatter; - NumberFormat noFractionalDigitsFormatter = NumberFormat.getInstance( ROOT ); - noFractionalDigitsFormatter.setRoundingMode( DOWN ); - noFractionalDigitsFormatter.setMinimumFractionDigits( 0 ); - noFractionalDigitsFormatter.setMaximumFractionDigits( 0 ); + NumberFormat noFractionalDigitsFormatter = NumberFormat.getInstance(ROOT); + noFractionalDigitsFormatter.setRoundingMode(DOWN); + noFractionalDigitsFormatter.setMinimumFractionDigits(0); + noFractionalDigitsFormatter.setMaximumFractionDigits(0); this.noFractionalDigitsFormatter = noFractionalDigitsFormatter; } @Test - public void testMethodsParallelWithSuite() - throws VerificationException - { - OutputValidator validator = unpack().executeTest().verifyErrorFree( 6 ); - Set testLines = printTestLines( validator, "test finished after duration=" ); - assertThat( testLines.size(), is( 2 ) ); - for ( String testLine : testLines ) - { - long duration = duration( testLine ); + public void testMethodsParallelWithSuite() throws VerificationException { + OutputValidator validator = unpack().executeTest().verifyErrorFree(6); + Set testLines = printTestLines(validator, "test finished after duration="); + assertThat(testLines.size(), is(2)); + for (String testLine : testLines) { + long duration = duration(testLine); long min = 250 * PERFORMANCE_TEST_MULTIPLICATION_FACTOR; long max = 750 * PERFORMANCE_TEST_MULTIPLICATION_FACTOR; - assertTrue( format( "duration %d should be between %d and %d ms", duration, min, max ), - duration > min && duration < max - ); + assertTrue( + format("duration %d should be between %d and %d ms", duration, min, max), + duration > min && duration < max); } - Set suiteLines = printTestLines( validator, "suite finished after duration=" ); - assertThat( suiteLines.size(), is( 1 ) ); - long duration = duration( suiteLines.iterator().next() ); + Set suiteLines = printTestLines(validator, "suite finished after duration="); + assertThat(suiteLines.size(), is(1)); + long duration = duration(suiteLines.iterator().next()); long min = 750 * PERFORMANCE_TEST_MULTIPLICATION_FACTOR; long max = 1250 * PERFORMANCE_TEST_MULTIPLICATION_FACTOR; - assertTrue( format( "duration %d should be between %d and %d ms", duration, min, max ), - duration > min && duration < max - ); + assertTrue( + format("duration %d should be between %d and %d ms", duration, min, max), + duration > min && duration < max); - String delayMin = lowerScaleFormatter.format( 0.98 * PERFORMANCE_TEST_MULTIPLICATION_FACTOR * 0.5 ); - String delayMax = noFractionalDigitsFormatter.format( PERFORMANCE_TEST_MULTIPLICATION_FACTOR * 0.5 ) + "."; + String delayMin = lowerScaleFormatter.format(0.98 * PERFORMANCE_TEST_MULTIPLICATION_FACTOR * 0.5); + String delayMax = noFractionalDigitsFormatter.format(PERFORMANCE_TEST_MULTIPLICATION_FACTOR * 0.5) + "."; - for ( String line : validator.loadLogLines() ) - { - if ( line.startsWith( "Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed:" ) ) - { - assertThat( line, anyOf( // 1.9xx to 2.xxx can vary depending on CI jobs - containsString( "Time elapsed: " + delayMin ), - containsString( "Time elapsed: " + delayMax ) - ) - ); - assertThat( line, anyOf( - endsWith( " s - in surefire747.SuiteTest1" ), - endsWith( " s - in surefire747.SuiteTest2" ) - ) - ); + for (String line : validator.loadLogLines()) { + if (line.startsWith("Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed:")) { + assertThat( + line, + anyOf( // 1.9xx to 2.xxx can vary depending on CI jobs + containsString("Time elapsed: " + delayMin), + containsString("Time elapsed: " + delayMax))); + assertThat( + line, + anyOf(endsWith(" s - in surefire747.SuiteTest1"), endsWith(" s - in surefire747.SuiteTest2"))); } } } @Test - public void testClassesParallelWithSuite() - throws VerificationException - { - OutputValidator validator = unpack().parallelClasses().executeTest().verifyErrorFree( 6 ); - Set testLines = printTestLines( validator, "test finished after duration=" ); - assertThat( testLines.size(), is( 2 ) ); - for ( String testLine : testLines ) - { - long duration = duration( testLine ); + public void testClassesParallelWithSuite() throws VerificationException { + OutputValidator validator = unpack().parallelClasses().executeTest().verifyErrorFree(6); + Set testLines = printTestLines(validator, "test finished after duration="); + assertThat(testLines.size(), is(2)); + for (String testLine : testLines) { + long duration = duration(testLine); long min = 1450 * PERFORMANCE_TEST_MULTIPLICATION_FACTOR; long max = 1750 * PERFORMANCE_TEST_MULTIPLICATION_FACTOR; - assertTrue( format( "duration %d should be between %d and %d ms", duration, min, max ), - duration > min && duration < max - ); + assertTrue( + format("duration %d should be between %d and %d ms", duration, min, max), + duration > min && duration < max); } - Set suiteLines = printTestLines( validator, "suite finished after duration=" ); - assertThat( suiteLines.size(), is( 1 ) ); - long duration = duration( suiteLines.iterator().next() ); + Set suiteLines = printTestLines(validator, "suite finished after duration="); + assertThat(suiteLines.size(), is(1)); + long duration = duration(suiteLines.iterator().next()); long min = 1450 * PERFORMANCE_TEST_MULTIPLICATION_FACTOR; long max = 1750 * PERFORMANCE_TEST_MULTIPLICATION_FACTOR; - assertTrue( format( "duration %d should be between %d and %d ms", duration, min, max ), - duration > min && duration < max - ); + assertTrue( + format("duration %d should be between %d and %d ms", duration, min, max), + duration > min && duration < max); } - public SurefireLauncher unpack() - { - return unpack( "junit47-parallel-with-suite" ); + public SurefireLauncher unpack() { + return unpack("junit47-parallel-with-suite"); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire772BothReportsIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire772BothReportsIT.java index 8bd0564aa2..74c227973c 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire772BothReportsIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire772BothReportsIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its.jiras; /* @@ -33,55 +51,52 @@ * * @author Kristian Rosenvold */ -public class Surefire772BothReportsIT - extends SurefireJUnit4IntegrationTestCase -{ +public class Surefire772BothReportsIT extends SurefireJUnit4IntegrationTestCase { - public SurefireLauncher unpack() - { - SurefireLauncher unpack = unpack( "/surefire-772-both-reports" ); + public SurefireLauncher unpack() { + SurefireLauncher unpack = unpack("/surefire-772-both-reports"); unpack.maven().deleteSiteDir().skipClean().failNever(); return unpack; } @Test - public void testReportGeneration() - { + public void testReportGeneration() { OutputValidator outputValidator = - unpack().addFailsafeReportOnlyGoal().addSurefireReportOnlyGoal().executeCurrentGoals(); + unpack().addFailsafeReportOnlyGoal().addSurefireReportOnlyGoal().executeCurrentGoals(); - TestFile siteFile = outputValidator.getSiteFile( "surefire-report.html" ); - assertTrue( "Expecting surefire report file", siteFile.isFile() ); + TestFile siteFile = outputValidator.getSiteFile("surefire-report.html"); + assertTrue("Expecting surefire report file", siteFile.isFile()); - siteFile = outputValidator.getSiteFile( "failsafe-report.html" ); - assertTrue( "Expecting failsafe report file", siteFile.isFile() ); + siteFile = outputValidator.getSiteFile("failsafe-report.html"); + assertTrue("Expecting failsafe report file", siteFile.isFile()); } @Test - public void testSkippedFailsafeReportGeneration() - { - OutputValidator validator = unpack(). - activateProfile( - "skipFailsafe" ).addFailsafeReportOnlyGoal().addSurefireReportOnlyGoal().executeCurrentGoals(); + public void testSkippedFailsafeReportGeneration() { + OutputValidator validator = unpack().activateProfile("skipFailsafe") + .addFailsafeReportOnlyGoal() + .addSurefireReportOnlyGoal() + .executeCurrentGoals(); - TestFile siteFile = validator.getSiteFile( "surefire-report.html" ); - assertTrue( "Expecting surefire report file", siteFile.isFile() ); + TestFile siteFile = validator.getSiteFile("surefire-report.html"); + assertTrue("Expecting surefire report file", siteFile.isFile()); - siteFile = validator.getSiteFile( "failsafe-report.html" ); - assertFalse( "Expecting no failsafe report file", siteFile.isFile() ); + siteFile = validator.getSiteFile("failsafe-report.html"); + assertFalse("Expecting no failsafe report file", siteFile.isFile()); } @Test - public void testSkippedSurefireReportGeneration() - { - OutputValidator validator = unpack().failNever(). - activateProfile( - "skipSurefire" ).addFailsafeReportOnlyGoal().addSurefireReportOnlyGoal().executeCurrentGoals(); + public void testSkippedSurefireReportGeneration() { + OutputValidator validator = unpack().failNever() + .activateProfile("skipSurefire") + .addFailsafeReportOnlyGoal() + .addSurefireReportOnlyGoal() + .executeCurrentGoals(); - TestFile siteFile = validator.getSiteFile( "surefire-report.html" ); - assertFalse( "Expecting no surefire report file", siteFile.isFile() ); + TestFile siteFile = validator.getSiteFile("surefire-report.html"); + assertFalse("Expecting no surefire report file", siteFile.isFile()); - siteFile = validator.getSiteFile( "failsafe-report.html" ); - assertTrue( "Expecting failsafe report file", siteFile.isFile() ); + siteFile = validator.getSiteFile("failsafe-report.html"); + assertTrue("Expecting failsafe report file", siteFile.isFile()); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire772NoFailsafeReportsIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire772NoFailsafeReportsIT.java index c8de0aedbb..4f4f5b8ae1 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire772NoFailsafeReportsIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire772NoFailsafeReportsIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its.jiras; /* @@ -34,77 +52,67 @@ * * @author Kristian Rosenvold */ -public class Surefire772NoFailsafeReportsIT - extends SurefireJUnit4IntegrationTestCase -{ +public class Surefire772NoFailsafeReportsIT extends SurefireJUnit4IntegrationTestCase { @Test - public void testReportGeneration() - throws Exception - { + public void testReportGeneration() throws Exception { final OutputValidator site = - unpack().addFailsafeReportOnlyGoal().addSurefireReportOnlyGoal().executeCurrentGoals(); + unpack().addFailsafeReportOnlyGoal().addSurefireReportOnlyGoal().executeCurrentGoals(); - assertSurefireReportPresent( site ); - assertNoFailsefeReport( site ); + assertSurefireReportPresent(site); + assertNoFailsefeReport(site); } @Test - public void testSkippedFailsafeReportGeneration() - throws Exception - { - final OutputValidator validator = unpack().activateProfile( - "skipFailsafe" ).addFailsafeReportOnlyGoal().addSurefireReportOnlyGoal().executeCurrentGoals(); - assertSurefireReportPresent( validator ); - assertNoFailsefeReport( validator ); - + public void testSkippedFailsafeReportGeneration() throws Exception { + final OutputValidator validator = unpack().activateProfile("skipFailsafe") + .addFailsafeReportOnlyGoal() + .addSurefireReportOnlyGoal() + .executeCurrentGoals(); + assertSurefireReportPresent(validator); + assertNoFailsefeReport(validator); } @Test - public void testForcedFailsafeReportGeneration() - throws Exception - { - final OutputValidator validator = unpack().activateProfile( - "forceFailsafe" ).addFailsafeReportOnlyGoal().addSurefireReportOnlyGoal().executeCurrentGoals(); - assertSurefireReportPresent( validator ); - assertFailsafeReport( validator ); + public void testForcedFailsafeReportGeneration() throws Exception { + final OutputValidator validator = unpack().activateProfile("forceFailsafe") + .addFailsafeReportOnlyGoal() + .addSurefireReportOnlyGoal() + .executeCurrentGoals(); + assertSurefireReportPresent(validator); + assertFailsafeReport(validator); } @Test - public void testSkipForcedFailsafeReportGeneration() - throws Exception - { - final OutputValidator validator = unpack().activateProfile( "forceFailsafe" ).activateProfile( - "skipFailsafe" ).addFailsafeReportOnlyGoal().addSurefireReportOnlyGoal().executeCurrentGoals(); - - assertSurefireReportPresent( validator ); - assertNoFailsefeReport( validator ); + public void testSkipForcedFailsafeReportGeneration() throws Exception { + final OutputValidator validator = unpack().activateProfile("forceFailsafe") + .activateProfile("skipFailsafe") + .addFailsafeReportOnlyGoal() + .addSurefireReportOnlyGoal() + .executeCurrentGoals(); + + assertSurefireReportPresent(validator); + assertNoFailsefeReport(validator); } - private void assertNoFailsefeReport( OutputValidator site ) - { - TestFile siteFile = site.getSiteFile( "failsafe-report.html" ); - assertFalse( "Expecting no failsafe report file", siteFile.isFile() ); + private void assertNoFailsefeReport(OutputValidator site) { + TestFile siteFile = site.getSiteFile("failsafe-report.html"); + assertFalse("Expecting no failsafe report file", siteFile.isFile()); } - private void assertFailsafeReport( OutputValidator site ) - { - TestFile siteFile = site.getSiteFile( "failsafe-report.html" ); - assertTrue( "Expecting no failsafe report file", siteFile.isFile() ); + private void assertFailsafeReport(OutputValidator site) { + TestFile siteFile = site.getSiteFile("failsafe-report.html"); + assertTrue("Expecting no failsafe report file", siteFile.isFile()); } - private void assertSurefireReportPresent( OutputValidator site ) - { - TestFile siteFile = site.getSiteFile( "surefire-report.html" ); - assertTrue( "Expecting surefire report file", siteFile.isFile() ); + private void assertSurefireReportPresent(OutputValidator site) { + TestFile siteFile = site.getSiteFile("surefire-report.html"); + assertTrue("Expecting surefire report file", siteFile.isFile()); } - private SurefireLauncher unpack() - throws VerificationException - { - final SurefireLauncher unpack = unpack( "surefire-772-no-failsafe-reports" ); - unpack.maven().deleteSiteDir().skipClean().failNever().verifyFileNotPresent( "site" ); + private SurefireLauncher unpack() throws VerificationException { + final SurefireLauncher unpack = unpack("surefire-772-no-failsafe-reports"); + unpack.maven().deleteSiteDir().skipClean().failNever().verifyFileNotPresent("site"); return unpack; } - } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire772NoSurefireReportsIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire772NoSurefireReportsIT.java index 6b59ba2aaf..25ac757712 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire772NoSurefireReportsIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire772NoSurefireReportsIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its.jiras; /* @@ -33,66 +51,65 @@ * * @author Kristian Rosenvold */ -public class Surefire772NoSurefireReportsIT - extends SurefireJUnit4IntegrationTestCase -{ +public class Surefire772NoSurefireReportsIT extends SurefireJUnit4IntegrationTestCase { @Test - public void testReportGeneration() - { + public void testReportGeneration() { OutputValidator validator = - unpack().addFailsafeReportOnlyGoal().addSurefireReportOnlyGoal().executeCurrentGoals(); + unpack().addFailsafeReportOnlyGoal().addSurefireReportOnlyGoal().executeCurrentGoals(); - TestFile siteFile = validator.getSiteFile( "surefire-report.html" ); - assertTrue( "Expecting surefire report file", siteFile.isFile() ); + TestFile siteFile = validator.getSiteFile("surefire-report.html"); + assertTrue("Expecting surefire report file", siteFile.isFile()); - siteFile = validator.getSiteFile( "failsafe-report.html" ); - assertTrue( "Expecting failsafe report file", siteFile.isFile() ); + siteFile = validator.getSiteFile("failsafe-report.html"); + assertTrue("Expecting failsafe report file", siteFile.isFile()); } @Test - public void testSkippedSurefireReportGeneration() - { - OutputValidator validator = unpack().activateProfile( - "skipSurefire" ).addFailsafeReportOnlyGoal().addSurefireReportOnlyGoal().executeCurrentGoals(); + public void testSkippedSurefireReportGeneration() { + OutputValidator validator = unpack().activateProfile("skipSurefire") + .addFailsafeReportOnlyGoal() + .addSurefireReportOnlyGoal() + .executeCurrentGoals(); - TestFile siteFile = validator.getSiteFile( "surefire-report.html" ); - assertFalse( "Expecting no surefire report file", siteFile.isFile() ); + TestFile siteFile = validator.getSiteFile("surefire-report.html"); + assertFalse("Expecting no surefire report file", siteFile.isFile()); - siteFile = validator.getSiteFile( "failsafe-report.html" ); - assertTrue( "Expecting failsafe report file", siteFile.isFile() ); + siteFile = validator.getSiteFile("failsafe-report.html"); + assertTrue("Expecting failsafe report file", siteFile.isFile()); } @Test - public void testOptionalSurefireReportGeneration() - { - OutputValidator validator = unpack().activateProfile( - "optionalSurefire" ).addFailsafeReportOnlyGoal().addSurefireReportOnlyGoal().executeCurrentGoals(); + public void testOptionalSurefireReportGeneration() { + OutputValidator validator = unpack().activateProfile("optionalSurefire") + .addFailsafeReportOnlyGoal() + .addSurefireReportOnlyGoal() + .executeCurrentGoals(); - TestFile siteFile = validator.getSiteFile( "surefire-report.html" ); - assertFalse( "Expecting no surefire report file", siteFile.isFile() ); + TestFile siteFile = validator.getSiteFile("surefire-report.html"); + assertFalse("Expecting no surefire report file", siteFile.isFile()); - siteFile = validator.getSiteFile( "failsafe-report.html" ); - assertTrue( "Expecting failsafe report file", siteFile.isFile() ); + siteFile = validator.getSiteFile("failsafe-report.html"); + assertTrue("Expecting failsafe report file", siteFile.isFile()); } @Test - public void testSkipOptionalSurefireReportGeneration() - { - OutputValidator validator = unpack().activateProfile( "optionalSurefire" ).activateProfile( - "skipSurefire" ).addFailsafeReportOnlyGoal().addSurefireReportOnlyGoal().executeCurrentGoals(); - - TestFile siteFile = validator.getSiteFile( "surefire-report.html" ); - assertFalse( "Expecting no surefire report file", siteFile.isFile() ); - - siteFile = validator.getSiteFile( "failsafe-report.html" ); - assertTrue( "Expecting failsafe report file", siteFile.isFile() ); + public void testSkipOptionalSurefireReportGeneration() { + OutputValidator validator = unpack().activateProfile("optionalSurefire") + .activateProfile("skipSurefire") + .addFailsafeReportOnlyGoal() + .addSurefireReportOnlyGoal() + .executeCurrentGoals(); + + TestFile siteFile = validator.getSiteFile("surefire-report.html"); + assertFalse("Expecting no surefire report file", siteFile.isFile()); + + siteFile = validator.getSiteFile("failsafe-report.html"); + assertTrue("Expecting failsafe report file", siteFile.isFile()); } - public SurefireLauncher unpack() - { - SurefireLauncher unpack = unpack( "/surefire-772-no-surefire-reports" ); - unpack.maven().failNever().deleteSiteDir().skipClean( ); + public SurefireLauncher unpack() { + SurefireLauncher unpack = unpack("/surefire-772-no-surefire-reports"); + unpack.maven().failNever().deleteSiteDir().skipClean(); return unpack; } - } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire772SpecifiedReportsIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire772SpecifiedReportsIT.java index e49435248e..c4ee2a2f9a 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire772SpecifiedReportsIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire772SpecifiedReportsIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its.jiras; /* @@ -33,53 +51,50 @@ * * @author Kristian Rosenvold */ -public class Surefire772SpecifiedReportsIT - extends SurefireJUnit4IntegrationTestCase -{ +public class Surefire772SpecifiedReportsIT extends SurefireJUnit4IntegrationTestCase { @Test - public void testReportGeneration() - { + public void testReportGeneration() { OutputValidator validator = - unpack().addFailsafeReportOnlyGoal().addSurefireReportOnlyGoal().executeCurrentGoals(); + unpack().addFailsafeReportOnlyGoal().addSurefireReportOnlyGoal().executeCurrentGoals(); - TestFile siteFile = validator.getSiteFile( "surefire-report.html" ); - assertTrue( "Expecting surefire report file", siteFile.isFile() ); + TestFile siteFile = validator.getSiteFile("surefire-report.html"); + assertTrue("Expecting surefire report file", siteFile.isFile()); - siteFile = validator.getSiteFile( "failsafe-report.html" ); - assertTrue( "Expecting failsafe report file", siteFile.isFile() ); + siteFile = validator.getSiteFile("failsafe-report.html"); + assertTrue("Expecting failsafe report file", siteFile.isFile()); } @Test - public void testSkippedFailsafeReportGeneration() - { - OutputValidator validator = unpack().activateProfile( - "skipFailsafe" ).addFailsafeReportOnlyGoal().addSurefireReportOnlyGoal().executeCurrentGoals(); + public void testSkippedFailsafeReportGeneration() { + OutputValidator validator = unpack().activateProfile("skipFailsafe") + .addFailsafeReportOnlyGoal() + .addSurefireReportOnlyGoal() + .executeCurrentGoals(); - TestFile siteFile = validator.getSiteFile( "surefire-report.html" ); - assertTrue( "Expecting surefire report file", siteFile.isFile() ); + TestFile siteFile = validator.getSiteFile("surefire-report.html"); + assertTrue("Expecting surefire report file", siteFile.isFile()); - siteFile = validator.getSiteFile( "failsafe-report.html" ); - assertFalse( "Expecting no failsafe report file", siteFile.isFile() ); + siteFile = validator.getSiteFile("failsafe-report.html"); + assertFalse("Expecting no failsafe report file", siteFile.isFile()); } @Test - public void testSkippedSurefireReportGeneration() - { - OutputValidator validator = unpack().activateProfile( - "skipSurefire" ).addFailsafeReportOnlyGoal().addSurefireReportOnlyGoal().executeCurrentGoals(); + public void testSkippedSurefireReportGeneration() { + OutputValidator validator = unpack().activateProfile("skipSurefire") + .addFailsafeReportOnlyGoal() + .addSurefireReportOnlyGoal() + .executeCurrentGoals(); - TestFile siteFile = validator.getSiteFile( "surefire-report.html" ); - assertFalse( "Expecting no surefire report file", siteFile.isFile() ); + TestFile siteFile = validator.getSiteFile("surefire-report.html"); + assertFalse("Expecting no surefire report file", siteFile.isFile()); - siteFile = validator.getSiteFile( "failsafe-report.html" ); - assertTrue( "Expecting failsafe report file", siteFile.isFile() ); + siteFile = validator.getSiteFile("failsafe-report.html"); + assertTrue("Expecting failsafe report file", siteFile.isFile()); } - public SurefireLauncher unpack() - { - SurefireLauncher unpack = unpack( "/surefire-772-specified-reports" ); + public SurefireLauncher unpack() { + SurefireLauncher unpack = unpack("/surefire-772-specified-reports"); unpack.maven().deleteSiteDir().skipClean().failNever(); return unpack; } - } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire801ForkNeverClassLoaderIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire801ForkNeverClassLoaderIT.java index 2e3a8fb4e0..1d6c7bae75 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire801ForkNeverClassLoaderIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire801ForkNeverClassLoaderIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its.jiras; /* @@ -27,12 +45,9 @@ * * @author Kristian Rosenvold */ -public class Surefire801ForkNeverClassLoaderIT - extends SurefireJUnit4IntegrationTestCase -{ +public class Surefire801ForkNeverClassLoaderIT extends SurefireJUnit4IntegrationTestCase { @Test - public void testShouldBeOkWithForkNever() - { - unpack( "fork-count-resource-loading" ).forkNever().executeTest(); + public void testShouldBeOkWithForkNever() { + unpack("fork-count-resource-loading").forkNever().executeTest(); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire803MultiFailsafeExecsIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire803MultiFailsafeExecsIT.java index c05c52a65d..f155f80aed 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire803MultiFailsafeExecsIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire803MultiFailsafeExecsIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its.jiras; /* @@ -26,29 +44,26 @@ /** * */ -public class Surefire803MultiFailsafeExecsIT - extends SurefireJUnit4IntegrationTestCase -{ +public class Surefire803MultiFailsafeExecsIT extends SurefireJUnit4IntegrationTestCase { @Test - public void testSecondExecutionRunsAfterFirstExecutionFails() - { - unpack( - "/surefire-803-multiFailsafeExec-failureInFirst" ) + public void testSecondExecutionRunsAfterFirstExecutionFails() { + unpack("/surefire-803-multiFailsafeExec-failureInFirst") .maven() .withFailure() .executeVerify() - .assertIntegrationTestSuiteResults( 4, 0, 2, 0 ); + .assertIntegrationTestSuiteResults(4, 0, 2, 0); } @Test - public void testOneExecutionRunInTwoBuilds() - { - SurefireLauncher launcher = unpack( "/surefire-803-multiFailsafeExec-rebuildOverwrites" ); - launcher.sysProp( "success", "false" ).maven().withFailure().executeVerify().assertIntegrationTestSuiteResults( - 1, 0, 1, 0 ); + public void testOneExecutionRunInTwoBuilds() { + SurefireLauncher launcher = unpack("/surefire-803-multiFailsafeExec-rebuildOverwrites"); + launcher.sysProp("success", "false") + .maven() + .withFailure() + .executeVerify() + .assertIntegrationTestSuiteResults(1, 0, 1, 0); launcher.reset(); - launcher.sysProp( "success", "true" ).executeVerify().assertIntegrationTestSuiteResults( 1, 0, 0, 0 ); + launcher.sysProp("success", "true").executeVerify().assertIntegrationTestSuiteResults(1, 0, 0, 0); } - } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire806SpecifiedTestControlsIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire806SpecifiedTestControlsIT.java index 0b75c00ff3..93488a8ea7 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire806SpecifiedTestControlsIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire806SpecifiedTestControlsIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its.jiras; /* @@ -20,37 +38,39 @@ */ import org.apache.maven.surefire.its.fixture.SurefireJUnit4IntegrationTestCase; - import org.junit.Ignore; import org.junit.Test; /** * */ -public class Surefire806SpecifiedTestControlsIT - extends SurefireJUnit4IntegrationTestCase -{ +public class Surefire806SpecifiedTestControlsIT extends SurefireJUnit4IntegrationTestCase { @Test - @Ignore( "since SUREFIRE-1153 the includes/excludes are overridden by -Dtest or it.test for whatever execution" ) - public void singleTestInOneExecutionOfMultiExecutionProject() - { - unpack( "/surefire-806-specifiedTests-multi" ).setTestToRun( "FirstTest" ).failIfNoSpecifiedTests( - false ).executeTest().verifyErrorFree( 1 ); + @Ignore("since SUREFIRE-1153 the includes/excludes are overridden by -Dtest or it.test for whatever execution") + public void singleTestInOneExecutionOfMultiExecutionProject() { + unpack("/surefire-806-specifiedTests-multi") + .setTestToRun("FirstTest") + .failIfNoSpecifiedTests(false) + .executeTest() + .verifyErrorFree(1); } @Test - @Ignore( "since SUREFIRE-1153 the includes/excludes are overridden by -Dtest or it.test for whatever execution" ) - public void twoSpecifiedTestExecutionsInCorrectExecutionBlocks() - { - unpack( "/surefire-806-specifiedTests-multi" ).setTestToRun( - "FirstTest,SecondTest" ).executeTest().verifyErrorFree( 2 ); + @Ignore("since SUREFIRE-1153 the includes/excludes are overridden by -Dtest or it.test for whatever execution") + public void twoSpecifiedTestExecutionsInCorrectExecutionBlocks() { + unpack("/surefire-806-specifiedTests-multi") + .setTestToRun("FirstTest,SecondTest") + .executeTest() + .verifyErrorFree(2); } @Test - public void singleTestInSingleExecutionProject() - { - unpack( "/surefire-806-specifiedTests-single" ).setTestToRun( "ThirdTest" ).failIfNoSpecifiedTests( - false ).executeTest().verifyErrorFree( 1 ); + public void singleTestInSingleExecutionProject() { + unpack("/surefire-806-specifiedTests-single") + .setTestToRun("ThirdTest") + .failIfNoSpecifiedTests(false) + .executeTest() + .verifyErrorFree(1); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire809GroupExpressionsIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire809GroupExpressionsIT.java index 3773817649..6c86771dbc 100755 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire809GroupExpressionsIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire809GroupExpressionsIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its.jiras; /* @@ -22,97 +40,93 @@ import org.apache.maven.surefire.its.fixture.OutputValidator; import org.apache.maven.surefire.its.fixture.SurefireJUnit4IntegrationTestCase; import org.apache.maven.surefire.its.fixture.SurefireLauncher; - import org.junit.Test; /** * */ -public class Surefire809GroupExpressionsIT - extends SurefireJUnit4IntegrationTestCase -{ +public class Surefire809GroupExpressionsIT extends SurefireJUnit4IntegrationTestCase { @Test - public void categoryAB() - { - OutputValidator validator = unpackJUnit().groups( "junit4.CategoryA AND junit4.CategoryB" ).executeTest(); + public void categoryAB() { + OutputValidator validator = + unpackJUnit().groups("junit4.CategoryA AND junit4.CategoryB").executeTest(); validator.verifyErrorFreeLog(); - validator.assertTestSuiteResults( 2, 0, 0, 0 ); - validator.verifyTextInLog( "catA: 1" ); - validator.verifyTextInLog( "catB: 1" ); - validator.verifyTextInLog( "catC: 0" ); - validator.verifyTextInLog( "catNone: 0" ); - validator.verifyTextInLog( "mA: 1" ); - validator.verifyTextInLog( "mB: 1" ); - validator.verifyTextInLog( "mC: 0" ); + validator.assertTestSuiteResults(2, 0, 0, 0); + validator.verifyTextInLog("catA: 1"); + validator.verifyTextInLog("catB: 1"); + validator.verifyTextInLog("catC: 0"); + validator.verifyTextInLog("catNone: 0"); + validator.verifyTextInLog("mA: 1"); + validator.verifyTextInLog("mB: 1"); + validator.verifyTextInLog("mC: 0"); } @Test - public void incorrectJUnitVersions() - { - unpackJUnit().setJUnitVersion( "4.5" ).groups( - "junit4.CategoryA AND junit4.CategoryB" ).maven().withFailure().executeTest(); + public void incorrectJUnitVersions() { + unpackJUnit() + .setJUnitVersion("4.5") + .groups("junit4.CategoryA AND junit4.CategoryB") + .maven() + .withFailure() + .executeTest(); } @Test - public void testJUnitRunCategoryNotC() - { - OutputValidator validator = unpackJUnit().groups( "!junit4.CategoryC" ).executeTest(); + public void testJUnitRunCategoryNotC() { + OutputValidator validator = unpackJUnit().groups("!junit4.CategoryC").executeTest(); validator.verifyErrorFreeLog(); - validator.assertTestSuiteResults( 5, 0, 0, 0 ); - validator.verifyTextInLog( "catA: 2" ); - validator.verifyTextInLog( "catB: 2" ); - validator.verifyTextInLog( "catC: 0" ); - validator.verifyTextInLog( "catNone: 1" ); - validator.verifyTextInLog( "NoCategoryTest.CatNone: 1" ); + validator.assertTestSuiteResults(5, 0, 0, 0); + validator.verifyTextInLog("catA: 2"); + validator.verifyTextInLog("catB: 2"); + validator.verifyTextInLog("catC: 0"); + validator.verifyTextInLog("catNone: 1"); + validator.verifyTextInLog("NoCategoryTest.CatNone: 1"); } @Test - public void testExcludedGroups() - { - OutputValidator validator = unpackJUnit().setExcludedGroups( "junit4.CategoryC" ).executeTest(); + public void testExcludedGroups() { + OutputValidator validator = + unpackJUnit().setExcludedGroups("junit4.CategoryC").executeTest(); validator.verifyErrorFreeLog(); - validator.assertTestSuiteResults( 5, 0, 0, 0 ); - validator.verifyTextInLog( "catA: 2" ); - validator.verifyTextInLog( "catB: 2" ); - validator.verifyTextInLog( "catC: 0" ); - validator.verifyTextInLog( "catNone: 1" ); - validator.verifyTextInLog( "NoCategoryTest.CatNone: 1" ); + validator.assertTestSuiteResults(5, 0, 0, 0); + validator.verifyTextInLog("catA: 2"); + validator.verifyTextInLog("catB: 2"); + validator.verifyTextInLog("catC: 0"); + validator.verifyTextInLog("catNone: 1"); + validator.verifyTextInLog("NoCategoryTest.CatNone: 1"); } @Test - public void testNGRunCategoryAB() - { - OutputValidator validator = unpackTestNG().groups( "CategoryA AND CategoryB" ).debugLogging().executeTest(); + public void testNGRunCategoryAB() { + OutputValidator validator = + unpackTestNG().groups("CategoryA AND CategoryB").debugLogging().executeTest(); validator.verifyErrorFreeLog(); - validator.assertTestSuiteResults( 2, 0, 0, 0 ); - validator.verifyTextInLog( "BasicTest.testInCategoriesAB()" ); - validator.verifyTextInLog( "CategoryCTest.testInCategoriesAB()" ); + validator.assertTestSuiteResults(2, 0, 0, 0); + validator.verifyTextInLog("BasicTest.testInCategoriesAB()"); + validator.verifyTextInLog("CategoryCTest.testInCategoriesAB()"); } @Test - public void testNGRunCategoryNotC() - { - OutputValidator validator = unpackTestNG().groups( "!CategoryC" ).debugLogging().executeTest(); + public void testNGRunCategoryNotC() { + OutputValidator validator = + unpackTestNG().groups("!CategoryC").debugLogging().executeTest(); validator.verifyErrorFreeLog(); - validator.assertTestSuiteResults( 8, 0, 0, 0 ); - validator.verifyTextInLog( "catA: 2" ); - validator.verifyTextInLog( "catB: 2" ); - validator.verifyTextInLog( "catC: 0" ); - validator.verifyTextInLog( "catNone: 1" ); - validator.verifyTextInLog( "mA: 2" ); - validator.verifyTextInLog( "mB: 2" ); - validator.verifyTextInLog( "mC: 0" ); - validator.verifyTextInLog( "NoCategoryTest.CatNone: 1" ); + validator.assertTestSuiteResults(8, 0, 0, 0); + validator.verifyTextInLog("catA: 2"); + validator.verifyTextInLog("catB: 2"); + validator.verifyTextInLog("catC: 0"); + validator.verifyTextInLog("catNone: 1"); + validator.verifyTextInLog("mA: 2"); + validator.verifyTextInLog("mB: 2"); + validator.verifyTextInLog("mC: 0"); + validator.verifyTextInLog("NoCategoryTest.CatNone: 1"); } - private SurefireLauncher unpackJUnit() - { - return unpack( "surefire-809-groupExpr-junit48" ); + private SurefireLauncher unpackJUnit() { + return unpack("surefire-809-groupExpr-junit48"); } - private SurefireLauncher unpackTestNG() - { - return unpack( "surefire-809-groupExpr-testng" ); + private SurefireLauncher unpackTestNG() { + return unpack("surefire-809-groupExpr-testng"); } - } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire812Log4JClassLoaderIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire812Log4JClassLoaderIT.java index 065ec19f9d..485e5dd3f2 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire812Log4JClassLoaderIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire812Log4JClassLoaderIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its.jiras; /* @@ -25,12 +43,9 @@ /** * @author Kristian Rosenvold */ -public class Surefire812Log4JClassLoaderIT - extends SurefireJUnit4IntegrationTestCase -{ +public class Surefire812Log4JClassLoaderIT extends SurefireJUnit4IntegrationTestCase { @Test - public void testJunit3ParallelBuildResultCount() - { - executeErrorFreeTest( "surefire-812-log4j-classloader", 1 ); + public void testJunit3ParallelBuildResultCount() { + executeErrorFreeTest("surefire-812-log4j-classloader", 1); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire817SystemExitIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire817SystemExitIT.java index 5031f870b8..17cbc46076 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire817SystemExitIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire817SystemExitIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its.jiras; /* @@ -28,18 +46,14 @@ * @see SUREFIRE-817 * @since 2.18 */ -public class Surefire817SystemExitIT - extends SurefireJUnit4IntegrationTestCase -{ +public class Surefire817SystemExitIT extends SurefireJUnit4IntegrationTestCase { @Test - public void systemExit1() - { - unpack().maven().withFailure().executeTest().verifyTextInLog( "class jiras.surefire817.Test main" ); + public void systemExit1() { + unpack().maven().withFailure().executeTest().verifyTextInLog("class jiras.surefire817.Test main"); } - private SurefireLauncher unpack() - { - return unpack( "surefire-817-system-exit" ); + private SurefireLauncher unpack() { + return unpack("surefire-817-system-exit"); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire818NpeIgnoresTestsIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire818NpeIgnoresTestsIT.java index c74754174b..2aa925cae6 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire818NpeIgnoresTestsIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire818NpeIgnoresTestsIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its.jiras; /* @@ -27,16 +45,13 @@ * * @author Kristian Rosenvold */ -public class Surefire818NpeIgnoresTestsIT - extends SurefireJUnit4IntegrationTestCase -{ +public class Surefire818NpeIgnoresTestsIT extends SurefireJUnit4IntegrationTestCase { @Test - public void testBuildFailingWhenErrors() - { - unpack( "surefire-818-ignored-tests-on-npe" ) + public void testBuildFailingWhenErrors() { + unpack("surefire-818-ignored-tests-on-npe") .maven() .withFailure() .executeTest() - .assertTestSuiteResults( 2, 0, 1, 0 ); + .assertTestSuiteResults(2, 0, 1, 0); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire828EmptyGroupExprIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire828EmptyGroupExprIT.java index 71cb02f33a..b9e632e48c 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire828EmptyGroupExprIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire828EmptyGroupExprIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its.jiras; /* @@ -27,75 +45,70 @@ /** * */ -public class Surefire828EmptyGroupExprIT - extends SurefireJUnit4IntegrationTestCase -{ +public class Surefire828EmptyGroupExprIT extends SurefireJUnit4IntegrationTestCase { // !CategoryC @Test - public void testJUnitRunEmptyGroups() - { - OutputValidator validator = unpackJUnit().sysProp( "profile", "emptyGroups" ).executeTest(); + public void testJUnitRunEmptyGroups() { + OutputValidator validator = + unpackJUnit().sysProp("profile", "emptyGroups").executeTest(); validator.verifyErrorFreeLog(); - validator.assertTestSuiteResults( 5, 0, 0, 0 ); - validator.verifyTextInLog( "catA: 2" ); - validator.verifyTextInLog( "catB: 2" ); - validator.verifyTextInLog( "catC: 0" ); - validator.verifyTextInLog( "catNone: 1" ); - validator.verifyTextInLog( "NoCategoryTest.CatNone: 1" ); + validator.assertTestSuiteResults(5, 0, 0, 0); + validator.verifyTextInLog("catA: 2"); + validator.verifyTextInLog("catB: 2"); + validator.verifyTextInLog("catC: 0"); + validator.verifyTextInLog("catNone: 1"); + validator.verifyTextInLog("NoCategoryTest.CatNone: 1"); } // CategoryA && CategoryB @Test - public void testJUnitRunEmptyExcludeGroups() - { - OutputValidator validator = unpackJUnit().sysProp( "profile", "emptyExcludedGroups" ).executeTest(); + public void testJUnitRunEmptyExcludeGroups() { + OutputValidator validator = + unpackJUnit().sysProp("profile", "emptyExcludedGroups").executeTest(); validator.verifyErrorFreeLog(); - validator.assertTestSuiteResults( 2, 0, 0, 0 ); - validator.verifyTextInLog( "catA: 1" ); - validator.verifyTextInLog( "catB: 1" ); - validator.verifyTextInLog( "catC: 0" ); - validator.verifyTextInLog( "catNone: 0" ); - validator.verifyTextInLog( "mA: 1" ); - validator.verifyTextInLog( "mB: 1" ); - validator.verifyTextInLog( "mC: 0" ); + validator.assertTestSuiteResults(2, 0, 0, 0); + validator.verifyTextInLog("catA: 1"); + validator.verifyTextInLog("catB: 1"); + validator.verifyTextInLog("catC: 0"); + validator.verifyTextInLog("catNone: 0"); + validator.verifyTextInLog("mA: 1"); + validator.verifyTextInLog("mB: 1"); + validator.verifyTextInLog("mC: 0"); } // CategoryA && CategoryB @Test - public void testTestNGRunEmptyExcludeGroups() - { - OutputValidator validator = unpackTestNG().sysProp( "profile", "emptyExcludedGroups" ).executeTest(); + public void testTestNGRunEmptyExcludeGroups() { + OutputValidator validator = + unpackTestNG().sysProp("profile", "emptyExcludedGroups").executeTest(); validator.verifyErrorFreeLog(); - validator.assertTestSuiteResults( 2, 0, 0, 0 ); - validator.verifyTextInLog( "BasicTest.testInCategoriesAB()" ); - validator.verifyTextInLog( "CategoryCTest.testInCategoriesAB()" ); + validator.assertTestSuiteResults(2, 0, 0, 0); + validator.verifyTextInLog("BasicTest.testInCategoriesAB()"); + validator.verifyTextInLog("CategoryCTest.testInCategoriesAB()"); } // !CategoryC @Test - public void testTestNGRunEmptyGroups() - { - OutputValidator validator = unpackTestNG().sysProp( "profile", "emptyGroups" ).executeTest(); + public void testTestNGRunEmptyGroups() { + OutputValidator validator = + unpackTestNG().sysProp("profile", "emptyGroups").executeTest(); validator.verifyErrorFreeLog(); - validator.assertTestSuiteResults( 8, 0, 0, 0 ); - validator.verifyTextInLog( "catA: 2" ); - validator.verifyTextInLog( "catB: 2" ); - validator.verifyTextInLog( "catC: 0" ); - validator.verifyTextInLog( "catNone: 1" ); - validator.verifyTextInLog( "mA: 2" ); - validator.verifyTextInLog( "mB: 2" ); - validator.verifyTextInLog( "mC: 0" ); - validator.verifyTextInLog( "NoCategoryTest.CatNone: 1" ); + validator.assertTestSuiteResults(8, 0, 0, 0); + validator.verifyTextInLog("catA: 2"); + validator.verifyTextInLog("catB: 2"); + validator.verifyTextInLog("catC: 0"); + validator.verifyTextInLog("catNone: 1"); + validator.verifyTextInLog("mA: 2"); + validator.verifyTextInLog("mB: 2"); + validator.verifyTextInLog("mC: 0"); + validator.verifyTextInLog("NoCategoryTest.CatNone: 1"); } - private SurefireLauncher unpackJUnit() - { - return unpack( "surefire-828-emptyGroupExpr-junit48" ); + private SurefireLauncher unpackJUnit() { + return unpack("surefire-828-emptyGroupExpr-junit48"); } - private SurefireLauncher unpackTestNG() - { - return unpack( "surefire-828-emptyGroupExpr-testng" ); + private SurefireLauncher unpackTestNG() { + return unpack("surefire-828-emptyGroupExpr-testng"); } - } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire832ProviderSelectionIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire832ProviderSelectionIT.java index 6e02ed24f8..8eed8cda97 100755 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire832ProviderSelectionIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire832ProviderSelectionIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its.jiras; /* @@ -27,27 +45,23 @@ /** * */ -public class Surefire832ProviderSelectionIT - extends SurefireJUnit4IntegrationTestCase -{ +public class Surefire832ProviderSelectionIT extends SurefireJUnit4IntegrationTestCase { @Test - public void testJUnitRunCategoryAB() - { - OutputValidator validator = unpackJUnit().groups( "junit4.CategoryA AND junit4.CategoryB" ).executeTest(); + public void testJUnitRunCategoryAB() { + OutputValidator validator = + unpackJUnit().groups("junit4.CategoryA AND junit4.CategoryB").executeTest(); validator.verifyErrorFreeLog(); - validator.assertTestSuiteResults( 2, 0, 0, 0 ); - validator.verifyTextInLog( "catA: 1" ); - validator.verifyTextInLog( "catB: 1" ); - validator.verifyTextInLog( "catC: 0" ); - validator.verifyTextInLog( "catNone: 0" ); - validator.verifyTextInLog( "mA: 1" ); - validator.verifyTextInLog( "mB: 1" ); - validator.verifyTextInLog( "mC: 0" ); + validator.assertTestSuiteResults(2, 0, 0, 0); + validator.verifyTextInLog("catA: 1"); + validator.verifyTextInLog("catB: 1"); + validator.verifyTextInLog("catC: 0"); + validator.verifyTextInLog("catNone: 0"); + validator.verifyTextInLog("mA: 1"); + validator.verifyTextInLog("mB: 1"); + validator.verifyTextInLog("mC: 0"); } - private SurefireLauncher unpackJUnit() - { - return unpack( "surefire-832-provider-selection" ); + private SurefireLauncher unpackJUnit() { + return unpack("surefire-832-provider-selection"); } - } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire839TestWithoutCategoriesIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire839TestWithoutCategoriesIT.java index e5925cb2fa..b4655332b3 100755 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire839TestWithoutCategoriesIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire839TestWithoutCategoriesIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its.jiras; /* @@ -20,30 +38,25 @@ */ import org.apache.maven.surefire.its.fixture.SurefireJUnit4IntegrationTestCase; - import org.junit.Test; /** * */ -public class Surefire839TestWithoutCategoriesIT - extends SurefireJUnit4IntegrationTestCase -{ +public class Surefire839TestWithoutCategoriesIT extends SurefireJUnit4IntegrationTestCase { @Test - public void classWithoutCategory() - { - unpack( "junit48-categories" ).setJUnitVersion( "4.11" ).executeTest().verifyErrorFree( 3 ); + public void classWithoutCategory() { + unpack("junit48-categories").setJUnitVersion("4.11").executeTest().verifyErrorFree(3); } @Test - public void classWithoutCategoryForked() - { + public void classWithoutCategoryForked() { int threadCount = 2; - unpack( "junit48-categories" ) - .setJUnitVersion( "4.11" ) - .forkPerThread( threadCount ) - .threadCount( threadCount ) + unpack("junit48-categories") + .setJUnitVersion("4.11") + .forkPerThread(threadCount) + .threadCount(threadCount) .executeTest() - .verifyErrorFree( 3 ); + .verifyErrorFree(3); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire847AdditionalFailureIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire847AdditionalFailureIT.java index 040dd5fa3d..72870d802d 100755 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire847AdditionalFailureIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire847AdditionalFailureIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its.jiras; /* @@ -25,13 +43,12 @@ /** * */ -public class Surefire847AdditionalFailureIT - extends SurefireJUnit4IntegrationTestCase -{ +public class Surefire847AdditionalFailureIT extends SurefireJUnit4IntegrationTestCase { @Test - public void testJUnitRunCategoryAB() - { - unpack( "surefire-847-testngfail" ).setTestToRun( - "org/codehaus/SomePassedTest" ).executeTest().verifyErrorFreeLog(); + public void testJUnitRunCategoryAB() { + unpack("surefire-847-testngfail") + .setTestToRun("org/codehaus/SomePassedTest") + .executeTest() + .verifyErrorFreeLog(); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire855AllowFailsafeUseArtifactFileIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire855AllowFailsafeUseArtifactFileIT.java index 130a50020f..954aae63b7 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire855AllowFailsafeUseArtifactFileIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire855AllowFailsafeUseArtifactFileIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its.jiras; /* @@ -27,33 +45,33 @@ * @see SUREFIRE-855 * @since 2.19 */ -public class Surefire855AllowFailsafeUseArtifactFileIT - extends SurefireJUnit4IntegrationTestCase -{ +public class Surefire855AllowFailsafeUseArtifactFileIT extends SurefireJUnit4IntegrationTestCase { @Test - public void warShouldUseClasses() - { - unpack( "surefire-855-failsafe-use-war" ).maven().executeVerify().verifyErrorFree( 2 ); + public void warShouldUseClasses() { + unpack("surefire-855-failsafe-use-war").maven().executeVerify().verifyErrorFree(2); } @Test - public void jarShouldUseFile() - { - unpack( "surefire-855-failsafe-use-jar" ).maven().sysProp( "forkCount", 1 ) - .sysProp( "reuseForks", true ).executeVerify() - .assertIntegrationTestSuiteResults( 3, 0, 0, 1 ); + public void jarShouldUseFile() { + unpack("surefire-855-failsafe-use-jar") + .maven() + .sysProp("forkCount", 1) + .sysProp("reuseForks", true) + .executeVerify() + .assertIntegrationTestSuiteResults(3, 0, 0, 1); } @Test - public void jarNotForkingShouldUseFile() - { - unpack( "surefire-855-failsafe-use-jar" ) - .maven().sysProp( "forkCount", 0 ).executeVerify().assertIntegrationTestSuiteResults( 3, 0, 0, 1 ); + public void jarNotForkingShouldUseFile() { + unpack("surefire-855-failsafe-use-jar") + .maven() + .sysProp("forkCount", 0) + .executeVerify() + .assertIntegrationTestSuiteResults(3, 0, 0, 1); } @Test - public void osgiBundleShouldUseFile() - { - unpack( "surefire-855-failsafe-use-bundle" ).maven().executeVerify().verifyErrorFree( 2 ); + public void osgiBundleShouldUseFile() { + unpack("surefire-855-failsafe-use-bundle").maven().executeVerify().verifyErrorFree(2); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire901MIssingResultfileWhenNoTestsIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire901MIssingResultfileWhenNoTestsIT.java index 14e278e0e0..81e136c73c 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire901MIssingResultfileWhenNoTestsIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire901MIssingResultfileWhenNoTestsIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its.jiras; /* @@ -20,20 +38,15 @@ */ import org.apache.maven.surefire.its.fixture.SurefireJUnit4IntegrationTestCase; - import org.junit.Test; /** * Failsafe should work with early return when no tests * s */ -public class Surefire901MIssingResultfileWhenNoTestsIT - extends SurefireJUnit4IntegrationTestCase -{ +public class Surefire901MIssingResultfileWhenNoTestsIT extends SurefireJUnit4IntegrationTestCase { @Test - public void failsafeWithNoTests() - { - unpack( "failsafe-notests" ).executeVerify(); + public void failsafeWithNoTests() { + unpack("failsafe-notests").executeVerify(); } - } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire920TestFailureIgnoreWithTimeoutIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire920TestFailureIgnoreWithTimeoutIT.java index 3d1bed84e9..e6a58ef447 100755 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire920TestFailureIgnoreWithTimeoutIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire920TestFailureIgnoreWithTimeoutIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its.jiras; /* @@ -21,29 +39,28 @@ import org.apache.maven.surefire.its.fixture.OutputValidator; import org.apache.maven.surefire.its.fixture.SurefireJUnit4IntegrationTestCase; - import org.junit.Test; /** * */ -public class Surefire920TestFailureIgnoreWithTimeoutIT - extends SurefireJUnit4IntegrationTestCase -{ +public class Surefire920TestFailureIgnoreWithTimeoutIT extends SurefireJUnit4IntegrationTestCase { @Test - public void timeoutInForkWithBuildFail() - { - OutputValidator validator = - unpack( "fork-timeout" ).sysProp( "junit.parallel", "none" ).maven().withFailure().executeTest(); - validator.verifyTextInLog( "There was a timeout in the fork" ); + public void timeoutInForkWithBuildFail() { + OutputValidator validator = unpack("fork-timeout") + .sysProp("junit.parallel", "none") + .maven() + .withFailure() + .executeTest(); + validator.verifyTextInLog("There was a timeout in the fork"); } @Test - public void timeoutInForkWithNoBuildFail() - { - OutputValidator validator = - unpack( "fork-timeout" ).sysProp( "junit.parallel", "none" ).mavenTestFailureIgnore( true ).executeTest(); - validator.verifyTextInLog( "[ERROR] There was a timeout in the fork" ); + public void timeoutInForkWithNoBuildFail() { + OutputValidator validator = unpack("fork-timeout") + .sysProp("junit.parallel", "none") + .mavenTestFailureIgnore(true) + .executeTest(); + validator.verifyTextInLog("[ERROR] There was a timeout in the fork"); } - } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire926FailureWith2ProvidersIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire926FailureWith2ProvidersIT.java index e6f9dc6436..368a38bfd4 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire926FailureWith2ProvidersIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire926FailureWith2ProvidersIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its.jiras; /* @@ -25,12 +43,9 @@ /** * @author Kristian Rosenvold */ -public class Surefire926FailureWith2ProvidersIT - extends SurefireJUnit4IntegrationTestCase -{ +public class Surefire926FailureWith2ProvidersIT extends SurefireJUnit4IntegrationTestCase { @Test - public void testBuildFailingWhenErrors() - { - unpack( "surefire-926-2-provider-failure" ).maven().withFailure().executeTest(); + public void testBuildFailingWhenErrors() { + unpack("surefire-926-2-provider-failure").maven().withFailure().executeTest(); } -} \ No newline at end of file +} diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire930TestNgSuiteXmlIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire930TestNgSuiteXmlIT.java index 80b2c919fc..c65a9e0903 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire930TestNgSuiteXmlIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire930TestNgSuiteXmlIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its.jiras; /* @@ -20,22 +38,19 @@ */ import org.apache.maven.surefire.its.fixture.SurefireJUnit4IntegrationTestCase; - import org.junit.Test; /** * */ -public class Surefire930TestNgSuiteXmlIT - extends SurefireJUnit4IntegrationTestCase -{ +public class Surefire930TestNgSuiteXmlIT extends SurefireJUnit4IntegrationTestCase { @Test - public void suiteXmlRun() - { - unpack( - "surefire-930-failsafe-runtests" ).maven().withFailure().executeVerify().assertIntegrationTestSuiteResults( - 1, 0, 1, 0 ); + public void suiteXmlRun() { + unpack("surefire-930-failsafe-runtests") + .maven() + .withFailure() + .executeVerify() + .assertIntegrationTestSuiteResults(1, 0, 1, 0); } - } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire943ReportContentIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire943ReportContentIT.java index 7ec1893326..047e5f0016 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire943ReportContentIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire943ReportContentIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its.jiras; /* @@ -31,132 +49,128 @@ /** * */ -public class Surefire943ReportContentIT - extends SurefireJUnit4IntegrationTestCase -{ +public class Surefire943ReportContentIT extends SurefireJUnit4IntegrationTestCase { @Test - @SuppressWarnings( "checkstyle:methodname" ) - public void test_noParallel() - throws Exception - { - doTest( "none" ); + @SuppressWarnings("checkstyle:methodname") + public void test_noParallel() throws Exception { + doTest("none"); } @Test - @SuppressWarnings( "checkstyle:methodname" ) - public void test_parallelBoth() - throws Exception - { - doTest( "both" ); + @SuppressWarnings("checkstyle:methodname") + public void test_parallelBoth() throws Exception { + doTest("both"); } - private void doTest( String parallelMode ) - throws Exception - { - OutputValidator validator = - unpack( "surefire-943-report-content" ).maven() - .sysProp( "parallel", parallelMode ) - .sysProp( "threadCount", 4 ) - .withFailure().executeTest(); - - validator.assertTestSuiteResults( 10, 1, 3, 3 ); - - validate( validator, "org.sample.module.My1Test", 1 ); - validate( validator, "org.sample.module.My2Test", 1 ); - validate( validator, "org.sample.module.My3Test", 0 ); - validateSkipped( validator, "org.sample.module.My4Test" ); - validateFailInBeforeClass( validator, "org.sample.module.My5Test" ); + private void doTest(String parallelMode) throws Exception { + OutputValidator validator = unpack("surefire-943-report-content") + .maven() + .sysProp("parallel", parallelMode) + .sysProp("threadCount", 4) + .withFailure() + .executeTest(); + + validator.assertTestSuiteResults(10, 1, 3, 3); + + validate(validator, "org.sample.module.My1Test", 1); + validate(validator, "org.sample.module.My2Test", 1); + validate(validator, "org.sample.module.My3Test", 0); + validateSkipped(validator, "org.sample.module.My4Test"); + validateFailInBeforeClass(validator, "org.sample.module.My5Test"); } - private void validateFailInBeforeClass( OutputValidator validator, String className ) - throws FileNotFoundException - { - Xpp3Dom[] children = readTests( validator, className ); + private void validateFailInBeforeClass(OutputValidator validator, String className) throws FileNotFoundException { + Xpp3Dom[] children = readTests(validator, className); - Assert.assertEquals( 1, children.length ); + Assert.assertEquals(1, children.length); Xpp3Dom child = children[0]; - Assert.assertEquals( className, child.getAttribute( "classname" ) ); - Assert.assertEquals( "", child.getAttribute( "name" ) ); + Assert.assertEquals(className, child.getAttribute("classname")); + Assert.assertEquals("", child.getAttribute("name")); - Assert.assertEquals( "Expected error tag for failed BeforeClass method for " + className, 1, - child.getChildren( "error" ).length ); + Assert.assertEquals( + "Expected error tag for failed BeforeClass method for " + className, + 1, + child.getChildren("error").length); - Assert.assertTrue( "time for test failure in BeforeClass is expected to be positive", - Double.compare( Double.parseDouble( child.getAttribute( "time" ) ), 0.0d ) >= 0 ); + Assert.assertTrue( + "time for test failure in BeforeClass is expected to be positive", + Double.compare(Double.parseDouble(child.getAttribute("time")), 0.0d) >= 0); - Assert.assertTrue( "time for test failure in BeforeClass is expected to be resonably low", - Double.compare( Double.parseDouble( child.getAttribute( "time" ) ), 2.0d ) <= 0 ); + Assert.assertTrue( + "time for test failure in BeforeClass is expected to be resonably low", + Double.compare(Double.parseDouble(child.getAttribute("time")), 2.0d) <= 0); } - private void validateSkipped( OutputValidator validator, String className ) - throws FileNotFoundException - { - Xpp3Dom[] children = readTests( validator, className ); + private void validateSkipped(OutputValidator validator, String className) throws FileNotFoundException { + Xpp3Dom[] children = readTests(validator, className); - Assert.assertEquals( 1, children.length ); + Assert.assertEquals(1, children.length); Xpp3Dom child = children[0]; - Assert.assertEquals( className, child.getAttribute( "classname" ) ); - Assert.assertEquals( "", child.getAttribute( "name" ) ); + Assert.assertEquals(className, child.getAttribute("classname")); + Assert.assertEquals("", child.getAttribute("name")); - Assert.assertEquals( "Expected skipped tag for ignored method for " + className, 1, - child.getChildren( "skipped" ).length ); + Assert.assertEquals( + "Expected skipped tag for ignored method for " + className, 1, child.getChildren("skipped").length); - Assert.assertEquals( "time for ignored test is expected to be zero", 0, - Double.compare( Double.parseDouble( child.getAttribute( "time" ) ), 0.0d ) ); + Assert.assertEquals( + "time for ignored test is expected to be zero", + 0, + Double.compare(Double.parseDouble(child.getAttribute("time")), 0.0d)); } - private void validate( OutputValidator validator, String className, int ignored ) - throws FileNotFoundException - { - Xpp3Dom[] children = readTests( validator, className ); - - Assert.assertEquals( 2 + ignored, children.length ); - - for ( Xpp3Dom child : children ) - { - Assert.assertEquals( className, child.getAttribute( "classname" ) ); - - if ( "alwaysSuccessful".equals( child.getAttribute( "name" ) ) ) - { - Assert.assertEquals( "Expected no failures for method alwaysSuccessful for " + className, 0, - child.getChildCount() ); - - Assert.assertTrue( "time for successful test is expected to be positive", - Double.compare( Double.parseDouble( child.getAttribute( "time" ) ), 0.0d ) > 0 ); - } - else if ( child.getAttribute( "name" ).contains( "Ignored" ) ) - { - Assert.assertEquals( "Expected skipped-tag for ignored method for " + className, 1, - child.getChildren( "skipped" ).length ); - - Assert.assertEquals( "time for ignored test is expected to be zero", 0, - Double.compare( Double.parseDouble( child.getAttribute( "time" ) ), 0.0d ) ); - - } - else - { - Assert.assertEquals( "Expected methods \"alwaysSuccessful\", \"*Ignored\" and \"fails\" in " - + className, "fails", child.getAttribute( "name" ) ); - Assert.assertEquals( "Expected failure description for method \"fails\" in " + className, 1, - child.getChildren( "failure" ).length ); - Assert.assertTrue( "time for failed test is expected to be positive", - Double.compare( Double.parseDouble( child.getAttribute( "time" ) ), 0.0d ) > 0 ); + private void validate(OutputValidator validator, String className, int ignored) throws FileNotFoundException { + Xpp3Dom[] children = readTests(validator, className); + + Assert.assertEquals(2 + ignored, children.length); + + for (Xpp3Dom child : children) { + Assert.assertEquals(className, child.getAttribute("classname")); + + if ("alwaysSuccessful".equals(child.getAttribute("name"))) { + Assert.assertEquals( + "Expected no failures for method alwaysSuccessful for " + className, 0, child.getChildCount()); + + Assert.assertTrue( + "time for successful test is expected to be positive", + Double.compare(Double.parseDouble(child.getAttribute("time")), 0.0d) > 0); + } else if (child.getAttribute("name").contains("Ignored")) { + Assert.assertEquals( + "Expected skipped-tag for ignored method for " + className, + 1, + child.getChildren("skipped").length); + + Assert.assertEquals( + "time for ignored test is expected to be zero", + 0, + Double.compare(Double.parseDouble(child.getAttribute("time")), 0.0d)); + + } else { + Assert.assertEquals( + "Expected methods \"alwaysSuccessful\", \"*Ignored\" and \"fails\" in " + className, + "fails", + child.getAttribute("name")); + Assert.assertEquals( + "Expected failure description for method \"fails\" in " + className, + 1, + child.getChildren("failure").length); + Assert.assertTrue( + "time for failed test is expected to be positive", + Double.compare(Double.parseDouble(child.getAttribute("time")), 0.0d) > 0); } } } - private Xpp3Dom[] readTests( OutputValidator validator, String className ) - throws FileNotFoundException - { - Xpp3Dom testResult = - Xpp3DomBuilder.build( - validator.getSurefireReportsXmlFile( "TEST-" + className + ".xml" ) - .getFileInputStream(), "UTF-8" ); - return testResult.getChildren( "testcase" ); + private Xpp3Dom[] readTests(OutputValidator validator, String className) throws FileNotFoundException { + Xpp3Dom testResult = Xpp3DomBuilder.build( + validator + .getSurefireReportsXmlFile("TEST-" + className + ".xml") + .getFileInputStream(), + "UTF-8"); + return testResult.getChildren("testcase"); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire946KillMainProcessInReusableForkIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire946KillMainProcessInReusableForkIT.java index 77a1b05bf0..07dd3ec38d 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire946KillMainProcessInReusableForkIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire946KillMainProcessInReusableForkIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its.jiras; /* @@ -41,93 +59,83 @@ /** * */ -@RunWith( Parameterized.class ) -@SuppressWarnings( "checkstyle:magicnumber" ) -public class Surefire946KillMainProcessInReusableForkIT - extends SurefireJUnit4IntegrationTestCase -{ +@RunWith(Parameterized.class) +@SuppressWarnings("checkstyle:magicnumber") +public class Surefire946KillMainProcessInReusableForkIT extends SurefireJUnit4IntegrationTestCase { // there are 10 test classes that each would wait 3.5 seconds. private static final int TEST_SLEEP_TIME = 3_500; private String classifierOfDummyDependency; @Parameter - @SuppressWarnings( "checkstyle:visibilitymodifier" ) + @SuppressWarnings("checkstyle:visibilitymodifier") public String shutdownMavenMethod; - @Parameter( 1 ) - @SuppressWarnings( "checkstyle:visibilitymodifier" ) + @Parameter(1) + @SuppressWarnings("checkstyle:visibilitymodifier") public String shutdownSurefireMethod; - @Parameters( name = "{0}-{1}" ) - public static Iterable data() - { + @Parameters(name = "{0}-{1}") + public static Iterable data() { ArrayList args = new ArrayList<>(); - args.add( new Object[] { "halt", "exit" } ); - args.add( new Object[] { "halt", "kill" } ); - args.add( new Object[] { "exit", "exit" } ); - args.add( new Object[] { "exit", "kill" } ); - args.add( new Object[] { "interrupt", "exit" } ); - args.add( new Object[] { "interrupt", "kill" } ); + args.add(new Object[] {"halt", "exit"}); + args.add(new Object[] {"halt", "kill"}); + args.add(new Object[] {"exit", "exit"}); + args.add(new Object[] {"exit", "kill"}); + args.add(new Object[] {"interrupt", "exit"}); + args.add(new Object[] {"interrupt", "kill"}); return args; } @BeforeClass - public static void installSelfdestructPlugin() - { - unpack( Surefire946KillMainProcessInReusableForkIT.class, "surefire-946-self-destruct-plugin", "plugin" ) - .executeInstall(); + public static void installSelfdestructPlugin() { + unpack(Surefire946KillMainProcessInReusableForkIT.class, "surefire-946-self-destruct-plugin", "plugin") + .executeInstall(); } @Before - public void dummyDep() - { + public void dummyDep() { classifierOfDummyDependency = shutdownMavenMethod + shutdownSurefireMethod; - unpack( "surefire-946-dummy-dependency", classifierOfDummyDependency ) - .sysProp( "distinct.classifier", classifierOfDummyDependency ) - .executeInstall(); + unpack("surefire-946-dummy-dependency", classifierOfDummyDependency) + .sysProp("distinct.classifier", classifierOfDummyDependency) + .executeInstall(); } - @Test( timeout = 60_000 ) - public void test() throws Exception - { - unpack( "surefire-946-killMainProcessInReusableFork", - "-" + shutdownMavenMethod + "-" + shutdownSurefireMethod ) - .sysProp( "distinct.classifier", classifierOfDummyDependency ) - .sysProp( "surefire.shutdown", shutdownSurefireMethod ) - .sysProp( "selfdestruct.timeoutInMillis", "20000" ) - .sysProp( "selfdestruct.method", shutdownMavenMethod ) - .sysProp( "testSleepTime", String.valueOf( TEST_SLEEP_TIME ) ) - .addGoal( "org.apache.maven.plugins.surefire:maven-selfdestruct-plugin:selfdestruct" ) + @Test(timeout = 60_000) + public void test() throws Exception { + unpack("surefire-946-killMainProcessInReusableFork", "-" + shutdownMavenMethod + "-" + shutdownSurefireMethod) + .sysProp("distinct.classifier", classifierOfDummyDependency) + .sysProp("surefire.shutdown", shutdownSurefireMethod) + .sysProp("selfdestruct.timeoutInMillis", "20000") + .sysProp("selfdestruct.method", shutdownMavenMethod) + .sysProp("testSleepTime", String.valueOf(TEST_SLEEP_TIME)) + .addGoal("org.apache.maven.plugins.surefire:maven-selfdestruct-plugin:selfdestruct") .setForkJvm() - .forkPerThread( 1 ).maven().withFailure().executeTest(); - + .forkPerThread(1) + .maven() + .withFailure() + .executeTest(); XPathFactory xpathFactory = XPathFactory.newInstance(); XPath xpath = xpathFactory.newXPath(); - File settings = new File( System.getProperty( "maven.settings.file" ) ).getCanonicalFile(); - Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse( settings ); - String localRepository = xpath.evaluate( "/settings/localRepository", doc ); - assertThat( localRepository ) - .isNotNull() - .isNotEmpty(); - - File dep = new File( localRepository, + File settings = new File(System.getProperty("maven.settings.file")).getCanonicalFile(); + Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(settings); + String localRepository = xpath.evaluate("/settings/localRepository", doc); + assertThat(localRepository).isNotNull().isNotEmpty(); + + File dep = new File( + localRepository, "org/apache/maven/plugins/surefire/surefire-946-dummy-dependency/0.1/" - + "surefire-946-dummy-dependency-0.1-" + classifierOfDummyDependency + ".jar" ); + + "surefire-946-dummy-dependency-0.1-" + classifierOfDummyDependency + ".jar"); - assertThat( dep ) - .exists(); + assertThat(dep).exists(); boolean deleted; int iterations = 0; - do - { - Thread.sleep( 1_000L ); + do { + Thread.sleep(1_000L); deleted = dep.delete(); - } - while ( !deleted && ++iterations < 10 ); - assertThat( deleted ) - .isTrue(); + } while (!deleted && ++iterations < 10); + assertThat(deleted).isTrue(); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire972BizarreNoClassDefIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire972BizarreNoClassDefIT.java index 9f93443731..470fb9740e 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire972BizarreNoClassDefIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire972BizarreNoClassDefIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its.jiras; /* @@ -25,12 +43,9 @@ /** * */ -public class Surefire972BizarreNoClassDefIT - extends SurefireJUnit4IntegrationTestCase -{ +public class Surefire972BizarreNoClassDefIT extends SurefireJUnit4IntegrationTestCase { @Test - public void testJunit3ParallelBuildResultCount() - { - unpack( "surefire-972-bizarre-noclassdef" ).maven().withFailure().executeVerify(); + public void testJunit3ParallelBuildResultCount() { + unpack("surefire-972-bizarre-noclassdef").maven().withFailure().executeVerify(); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire975DefaultVMEncodingIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire975DefaultVMEncodingIT.java index 4af055bd23..3e1e43e5df 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire975DefaultVMEncodingIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire975DefaultVMEncodingIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its.jiras; /* @@ -28,18 +46,18 @@ /** * */ -public class Surefire975DefaultVMEncodingIT - extends SurefireJUnit4IntegrationTestCase -{ +public class Surefire975DefaultVMEncodingIT extends SurefireJUnit4IntegrationTestCase { @Test - public void runWithRussian1251() - { - OutputValidator outputValidator = - unpack( "surefire-975-wrong-encoding" ).setMavenOpts( "-Dfile.encoding=windows-1251" ).executeTest(); - outputValidator.getSurefireReportsXmlFile( "TEST-EncodingInReportTest.xml" ).assertContainsText( - // see project.build.sourceEncoding=UTF-8 in src/test/resources/surefire-975-wrong-encoding/pom.xml - convertUnicodeToUTF8( "\u043A\u0438\u0440\u0438\u043B\u043B\u0438\u0446\u0435" ) ); + public void runWithRussian1251() { + OutputValidator outputValidator = unpack("surefire-975-wrong-encoding") + .setMavenOpts("-Dfile.encoding=windows-1251") + .executeTest(); + outputValidator + .getSurefireReportsXmlFile("TEST-EncodingInReportTest.xml") + .assertContainsText( + // see project.build.sourceEncoding=UTF-8 in + // src/test/resources/surefire-975-wrong-encoding/pom.xml + convertUnicodeToUTF8("\u043A\u0438\u0440\u0438\u043B\u043B\u0438\u0446\u0435")); } - } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire979WrongClassLoaderIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire979WrongClassLoaderIT.java index d099184dbc..672304a341 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire979WrongClassLoaderIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire979WrongClassLoaderIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its.jiras; /* @@ -26,18 +44,14 @@ /** * */ -public class Surefire979WrongClassLoaderIT - extends SurefireJUnit4IntegrationTestCase -{ +public class Surefire979WrongClassLoaderIT extends SurefireJUnit4IntegrationTestCase { @Test - public void wrongClassloaderUSedInSmartStacktraceparser() - { - OutputValidator outputValidator = - unpack( "surefire-979-smartStackTrace-wrongClassloader" ) - .failNever() - .executeTest(); + public void wrongClassloaderUSedInSmartStacktraceparser() { + OutputValidator outputValidator = unpack("surefire-979-smartStackTrace-wrongClassloader") + .failNever() + .executeTest(); outputValidator.verifyTextInLog( - "java.lang.NoClassDefFoundError: org/apache/commons/io/input/AutoCloseInputStream" ); + "java.lang.NoClassDefFoundError: org/apache/commons/io/input/AutoCloseInputStream"); } } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire985ParameterizedRunnerAndCategoriesIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire985ParameterizedRunnerAndCategoriesIT.java index 8d59cbe841..14b3e1df1c 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire985ParameterizedRunnerAndCategoriesIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire985ParameterizedRunnerAndCategoriesIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its.jiras; /* @@ -35,38 +53,30 @@ /** * */ -public class Surefire985ParameterizedRunnerAndCategoriesIT - extends SurefireJUnit4IntegrationTestCase -{ +public class Surefire985ParameterizedRunnerAndCategoriesIT extends SurefireJUnit4IntegrationTestCase { @Test - public void test() - throws Exception - { - OutputValidator validator = unpack( "surefire-985-parameterized-and-categories" ).maven().executeTest(); - validator.assertTestSuiteResults( 12, 0, 0, 0 ); + public void test() throws Exception { + OutputValidator validator = + unpack("surefire-985-parameterized-and-categories").maven().executeTest(); + validator.assertTestSuiteResults(12, 0, 0, 0); - assertFalse( validator.getSurefireReportsXmlFile( "TEST-sample.parameterized.Parameterized01Test.xml" ) - .exists() ); + assertFalse(validator + .getSurefireReportsXmlFile("TEST-sample.parameterized.Parameterized01Test.xml") + .exists()); - TestFile reportFile2 = - validator.getSurefireReportsXmlFile( "TEST-sample.parameterized.Parameterized02Test.xml" ); - assertTestCount( reportFile2, 4 ); - - TestFile reportFile3 = - validator.getSurefireReportsXmlFile( "TEST-sample.parameterized.Parameterized03Test.xml" ); - assertTestCount( reportFile3, 8 ); + TestFile reportFile2 = validator.getSurefireReportsXmlFile("TEST-sample.parameterized.Parameterized02Test.xml"); + assertTestCount(reportFile2, 4); + TestFile reportFile3 = validator.getSurefireReportsXmlFile("TEST-sample.parameterized.Parameterized03Test.xml"); + assertTestCount(reportFile3, 8); } - private void assertTestCount( TestFile reportFile, int tests ) - throws FileNotFoundException - { - assertTrue( reportFile.exists() ); + private void assertTestCount(TestFile reportFile, int tests) throws FileNotFoundException { + assertTrue(reportFile.exists()); - Xpp3Dom testResult = Xpp3DomBuilder.build( reportFile.getFileInputStream(), "UTF-8" ); - Xpp3Dom[] children = testResult.getChildren( "testcase" ); - assertEquals( tests, children.length ); + Xpp3Dom testResult = Xpp3DomBuilder.build(reportFile.getFileInputStream(), "UTF-8"); + Xpp3Dom[] children = testResult.getChildren("testcase"); + assertEquals(tests, children.length); } - } diff --git a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire995CategoryInheritanceIT.java b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire995CategoryInheritanceIT.java index 9e526729f1..8432257886 100644 --- a/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire995CategoryInheritanceIT.java +++ b/surefire-its/src/test/java/org/apache/maven/surefire/its/jiras/Surefire995CategoryInheritanceIT.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.its.jiras; /* @@ -33,130 +51,108 @@ * @see SUREFIRE-995 * @since 2.18.1 */ -public class Surefire995CategoryInheritanceIT extends SurefireJUnit4IntegrationTestCase -{ +public class Surefire995CategoryInheritanceIT extends SurefireJUnit4IntegrationTestCase { @Test - public void negativeTestShouldRunAllCategories() - { - unpack() - .setTestToRun( "Special*Test" ) - .executeTest() - .verifyErrorFree( 3 ); + public void negativeTestShouldRunAllCategories() { + unpack().setTestToRun("Special*Test").executeTest().verifyErrorFree(3); } @Test - public void junit411ShouldRunExplicitCategory() - { - final OutputValidator outputValidator = unpack() - .addGoal( "-Ppositive-tests" ) - .sysProp( "version.junit", "4.11" ) + public void junit411ShouldRunExplicitCategory() { + final OutputValidator outputValidator = unpack().addGoal("-Ppositive-tests") + .sysProp("version.junit", "4.11") .executeTest(); - outputValidator - .verifyErrorFree( 1 ) - .verifyTextInLog( "CategorizedTest#a" ); + outputValidator.verifyErrorFree(1).verifyTextInLog("CategorizedTest#a"); } @Test - public void junit411ShouldExcludeExplicitCategory() - { - final OutputValidator outputValidator = unpack() - .addGoal( "-Ppositive-tests-excluded-categories" ) - .sysProp( "version.junit", "4.11" ) + public void junit411ShouldExcludeExplicitCategory() { + final OutputValidator outputValidator = unpack().addGoal("-Ppositive-tests-excluded-categories") + .sysProp("version.junit", "4.11") .executeTest(); // SpecialCategorizedTest inherits the excluded annotation but should still run as // until junit 4.11, the Category annotation is not inherited - outputValidator - .verifyTextInLog( "SpecialCategorizedTest#b" ) - .verifyErrorFree( 16 ); + outputValidator.verifyTextInLog("SpecialCategorizedTest#b").verifyErrorFree(16); } @Test - public void junit412ShouldRunInheritedCategory() - { - unpack() - .setTestToRun( "Special*Test" ) - .addGoal( "-Ppositive-tests" ) + public void junit412ShouldRunInheritedCategory() { + unpack().setTestToRun("Special*Test") + .addGoal("-Ppositive-tests") .executeTest() - .verifyErrorFree( 2 ); + .verifyErrorFree(2); } @Test - public void junit412ShouldExcludeInheritedCategory() - { - unpack() - .setTestToRun( "Special*Test" ) - .addGoal( "-Ppositive-tests-excluded-categories" ) + public void junit412ShouldExcludeInheritedCategory() { + unpack().setTestToRun("Special*Test") + .addGoal("-Ppositive-tests-excluded-categories") .executeTest() - .verifyErrorFree( 1 ) - .verifyTextInLog( "SpecialNonCategoryTest#test" ); + .verifyErrorFree(1) + .verifyTextInLog("SpecialNonCategoryTest#test"); } @Test - public void junit411ShouldIgnoreInheritedCategories() throws VerificationException - { + public void junit411ShouldIgnoreInheritedCategories() throws VerificationException { // GIVEN a project using junit 4.11 - final OutputValidator outputValidator = unpack() - .addGoal( "-Ppositive-tests-included-and-excluded-categories" ) - .sysProp( "version.junit", "4.11" ) + final OutputValidator outputValidator = unpack().addGoal("-Ppositive-tests-included-and-excluded-categories") + .sysProp("version.junit", "4.11") // AND the tests marked with CategoryB are marked for execution - .setGroups( "jiras.surefire955.group.marker.CategoryB" ) + .setGroups("jiras.surefire955.group.marker.CategoryB") // WHEN the tests are executed .executeTest(); // THEN only the tests in classes directly annotated should be executed outputValidator // Test runs when the category is present in the concrete class - .verifyTextInLog( "Running jiras.surefire955.group.BBCTest" ) - .verifyTextInLog( "BBCTest#bbc" ) - .verifyTextInLog( "AbstractBCTest#pb" ) - .verifyTextInLog( "AbstractCTest#pc" ) - .verifyTextInLog( "Running jiras.surefire955.group.BTest" ) - .verifyTextInLog( "BTest#b" ) + .verifyTextInLog("Running jiras.surefire955.group.BBCTest") + .verifyTextInLog("BBCTest#bbc") + .verifyTextInLog("AbstractBCTest#pb") + .verifyTextInLog("AbstractCTest#pc") + .verifyTextInLog("Running jiras.surefire955.group.BTest") + .verifyTextInLog("BTest#b") // Test does not run when there is no category in the concrete class - .assertThatLogLine( containsString( "BCTest#bc" ), is( 0 ) ) - .assertThatLogLine( containsString( "ABCTest#abc" ), is( 0 ) ) - .verifyErrorFree( 4 ); + .assertThatLogLine(containsString("BCTest#bc"), is(0)) + .assertThatLogLine(containsString("ABCTest#abc"), is(0)) + .verifyErrorFree(4); } @Test - public void junit412ShouldExecuteInheritedCategories() - { + public void junit412ShouldExecuteInheritedCategories() { // GIVEN a project using junit 4.12 - final OutputValidator outputValidator = unpack() - .addGoal( "-Ppositive-tests-included-and-excluded-categories" ) - .sysProp( "version.junit", "4.12" ) + final OutputValidator outputValidator = unpack().addGoal("-Ppositive-tests-included-and-excluded-categories") + .sysProp("version.junit", "4.12") // AND the tests marked with CategoryB are marked for execution - .setGroups( "jiras.surefire955.group.marker.CategoryB" ) + .setGroups("jiras.surefire955.group.marker.CategoryB") // WHEN the tests are executed .executeTest(); // THEN the tests in classes directly marked with the CategoryB outputValidator - .verifyErrorFree( 10 ) - .verifyTextInLog( "Running jiras.surefire955.group.BBCTest" ) + .verifyErrorFree(10) + .verifyTextInLog("Running jiras.surefire955.group.BBCTest") // AND Test runs when an already existing category is added in the concrete class - .verifyTextInLog( "BBCTest#bbc" ) - .verifyTextInLog( "AbstractBCTest#pb" ) - .verifyTextInLog( "AbstractCTest#pc" ) - .verifyTextInLog( "Running jiras.surefire955.group.BTest" ) - .verifyTextInLog( "BTest#b" ) + .verifyTextInLog("BBCTest#bbc") + .verifyTextInLog("AbstractBCTest#pb") + .verifyTextInLog("AbstractCTest#pc") + .verifyTextInLog("Running jiras.surefire955.group.BTest") + .verifyTextInLog("BTest#b") // AND the tests in classes inheriting the CategoryB category should be executed - .verifyTextInLog( "Running jiras.surefire955.group.ABCTest" ) + .verifyTextInLog("Running jiras.surefire955.group.ABCTest") // AND Test runs when the concrete class has an additional (not excluded) category - .verifyTextInLog( "ABCTest#abc" ) - .verifyTextInLog( "AbstractBCTest#pb" ) - .verifyTextInLog( "AbstractCTest#pc" ) - .verifyTextInLog( "Running jiras.surefire955.group.BCTest" ) + .verifyTextInLog("ABCTest#abc") + .verifyTextInLog("AbstractBCTest#pb") + .verifyTextInLog("AbstractCTest#pc") + .verifyTextInLog("Running jiras.surefire955.group.BCTest") // AND Test runs when there is no category in the concrete class - .verifyTextInLog( "BCTest#bc" ) - .verifyTextInLog( "AbstractBCTest#pb" ) - .verifyTextInLog( "AbstractCTest#pc" ); + .verifyTextInLog("BCTest#bc") + .verifyTextInLog("AbstractBCTest#pb") + .verifyTextInLog("AbstractCTest#pc"); } - private SurefireLauncher unpack() - { - return unpack( "surefire-995-categoryInheritance" ); + private SurefireLauncher unpack() { + return unpack("surefire-995-categoryInheritance"); } } diff --git a/surefire-its/src/test/resources/SurefireToolchains/src/test/java/test/surefiretoolchains/AppTest.java b/surefire-its/src/test/resources/SurefireToolchains/src/test/java/test/surefiretoolchains/AppTest.java index 1c061d0caa..4b4cc49bdb 100644 --- a/surefire-its/src/test/resources/SurefireToolchains/src/test/java/test/surefiretoolchains/AppTest.java +++ b/surefire-its/src/test/resources/SurefireToolchains/src/test/java/test/surefiretoolchains/AppTest.java @@ -1,24 +1,5 @@ package test.surefiretoolchains; -/* - * 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.junit.Test; import static org.junit.Assert.*; diff --git a/surefire-its/src/test/resources/additional-classpath/src/test/java/additionalClasspath/BasicTest.java b/surefire-its/src/test/resources/additional-classpath/src/test/java/additionalClasspath/BasicTest.java index 43826b8175..1cc4cad9c5 100644 --- a/surefire-its/src/test/resources/additional-classpath/src/test/java/additionalClasspath/BasicTest.java +++ b/surefire-its/src/test/resources/additional-classpath/src/test/java/additionalClasspath/BasicTest.java @@ -1,24 +1,5 @@ package additionalClasspath; -/* - * 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 junit.framework.TestCase; public class BasicTest diff --git a/surefire-its/src/test/resources/aggregate-report/child1/src/test/java/aggregateReport/FailingTest.java b/surefire-its/src/test/resources/aggregate-report/child1/src/test/java/aggregateReport/FailingTest.java index 440ade7497..855efb6895 100644 --- a/surefire-its/src/test/resources/aggregate-report/child1/src/test/java/aggregateReport/FailingTest.java +++ b/surefire-its/src/test/resources/aggregate-report/child1/src/test/java/aggregateReport/FailingTest.java @@ -1,24 +1,5 @@ package aggregateReport; -/* - * 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 junit.framework.TestCase; public class FailingTest diff --git a/surefire-its/src/test/resources/aggregate-report/child2/src/test/java/aggregateReport/BasicTest.java b/surefire-its/src/test/resources/aggregate-report/child2/src/test/java/aggregateReport/BasicTest.java index 529e7caa77..70f5908300 100644 --- a/surefire-its/src/test/resources/aggregate-report/child2/src/test/java/aggregateReport/BasicTest.java +++ b/surefire-its/src/test/resources/aggregate-report/child2/src/test/java/aggregateReport/BasicTest.java @@ -1,24 +1,5 @@ package aggregateReport; -/* - * 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 junit.extensions.TestSetup; import junit.framework.Test; import junit.framework.TestCase; diff --git a/surefire-its/src/test/resources/ant-ignore/src/test/java/antignore/BasicTest.java b/surefire-its/src/test/resources/ant-ignore/src/test/java/antignore/BasicTest.java index 750bd6087d..487427a07a 100644 --- a/surefire-its/src/test/resources/ant-ignore/src/test/java/antignore/BasicTest.java +++ b/surefire-its/src/test/resources/ant-ignore/src/test/java/antignore/BasicTest.java @@ -1,24 +1,5 @@ package antignore; -/* - * 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.junit.Assert; import org.junit.Ignore; import org.junit.Test; diff --git a/surefire-its/src/test/resources/argLine-parameter/src/test/java/argLine/TestSurefireArgLine.java b/surefire-its/src/test/resources/argLine-parameter/src/test/java/argLine/TestSurefireArgLine.java index 1765c84127..7bd178488a 100644 --- a/surefire-its/src/test/resources/argLine-parameter/src/test/java/argLine/TestSurefireArgLine.java +++ b/surefire-its/src/test/resources/argLine-parameter/src/test/java/argLine/TestSurefireArgLine.java @@ -1,24 +1,5 @@ package argLine; -/* - * 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 junit.framework.TestCase; public class TestSurefireArgLine diff --git a/surefire-its/src/test/resources/argLine-properties/src/test/java/argLine-properties/TestSurefireArgLineProperties.java b/surefire-its/src/test/resources/argLine-properties/src/test/java/argLine-properties/TestSurefireArgLineProperties.java index a16fceba6a..333118caa2 100644 --- a/surefire-its/src/test/resources/argLine-properties/src/test/java/argLine-properties/TestSurefireArgLineProperties.java +++ b/surefire-its/src/test/resources/argLine-properties/src/test/java/argLine-properties/TestSurefireArgLineProperties.java @@ -1,24 +1,5 @@ package argLine; -/* - * 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.junit.Assert; import org.junit.Test; diff --git a/surefire-its/src/test/resources/classpath-filtering/src/test/java/classpathFiltering/BasicTest.java b/surefire-its/src/test/resources/classpath-filtering/src/test/java/classpathFiltering/BasicTest.java index 5f8b23afd4..f01ef0b299 100644 --- a/surefire-its/src/test/resources/classpath-filtering/src/test/java/classpathFiltering/BasicTest.java +++ b/surefire-its/src/test/resources/classpath-filtering/src/test/java/classpathFiltering/BasicTest.java @@ -1,24 +1,5 @@ package classpathFiltering; -/* - * 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 junit.framework.TestCase; public class BasicTest diff --git a/surefire-its/src/test/resources/classpath-order/src/test/java/it/BasicTest.java b/surefire-its/src/test/resources/classpath-order/src/test/java/it/BasicTest.java index 739e134c83..1593921931 100644 --- a/surefire-its/src/test/resources/classpath-order/src/test/java/it/BasicTest.java +++ b/surefire-its/src/test/resources/classpath-order/src/test/java/it/BasicTest.java @@ -1,24 +1,5 @@ package it; -/* - * 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 java.io.InputStream; import java.io.IOException; import java.util.Properties; diff --git a/surefire-its/src/test/resources/classpath-scope-filtering/src/test/java/classpathFiltering/BasicTest.java b/surefire-its/src/test/resources/classpath-scope-filtering/src/test/java/classpathFiltering/BasicTest.java index 5f8b23afd4..f01ef0b299 100644 --- a/surefire-its/src/test/resources/classpath-scope-filtering/src/test/java/classpathFiltering/BasicTest.java +++ b/surefire-its/src/test/resources/classpath-scope-filtering/src/test/java/classpathFiltering/BasicTest.java @@ -1,24 +1,5 @@ package classpathFiltering; -/* - * 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 junit.framework.TestCase; public class BasicTest diff --git a/surefire-its/src/test/resources/consoleOutput/src/test/java/consoleOutput/Test1.java b/surefire-its/src/test/resources/consoleOutput/src/test/java/consoleOutput/Test1.java index db74acf4af..de868f5ea2 100644 --- a/surefire-its/src/test/resources/consoleOutput/src/test/java/consoleOutput/Test1.java +++ b/surefire-its/src/test/resources/consoleOutput/src/test/java/consoleOutput/Test1.java @@ -1,24 +1,5 @@ package consoleOutput; -/* - * 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.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; diff --git a/surefire-its/src/test/resources/consoleOutputEncoding/src/test/java/consoleOutput/Test1.java b/surefire-its/src/test/resources/consoleOutputEncoding/src/test/java/consoleOutput/Test1.java index dfcfb9709e..ee60a854e0 100644 --- a/surefire-its/src/test/resources/consoleOutputEncoding/src/test/java/consoleOutput/Test1.java +++ b/surefire-its/src/test/resources/consoleOutputEncoding/src/test/java/consoleOutput/Test1.java @@ -1,24 +1,5 @@ package consoleOutput; -/* - * 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.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; diff --git a/surefire-its/src/test/resources/consoleoutput-noisy/src/test/java/consoleoutput_noisy/Test1.java b/surefire-its/src/test/resources/consoleoutput-noisy/src/test/java/consoleoutput_noisy/Test1.java index c7e562e2e2..a26f059d37 100644 --- a/surefire-its/src/test/resources/consoleoutput-noisy/src/test/java/consoleoutput_noisy/Test1.java +++ b/surefire-its/src/test/resources/consoleoutput-noisy/src/test/java/consoleoutput_noisy/Test1.java @@ -1,24 +1,5 @@ package consoleoutput_noisy; -/* - * 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.junit.Test; import org.junit.After; import org.junit.AfterClass; diff --git a/surefire-its/src/test/resources/consoleoutput-noisy/src/test/java/consoleoutput_noisy/Test2.java b/surefire-its/src/test/resources/consoleoutput-noisy/src/test/java/consoleoutput_noisy/Test2.java index 10f607fe6b..b4fc0744a7 100644 --- a/surefire-its/src/test/resources/consoleoutput-noisy/src/test/java/consoleoutput_noisy/Test2.java +++ b/surefire-its/src/test/resources/consoleoutput-noisy/src/test/java/consoleoutput_noisy/Test2.java @@ -1,24 +1,5 @@ package consoleoutput_noisy; -/* - * 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 junit.framework.TestCase; public class Test2 diff --git a/surefire-its/src/test/resources/consoleoutput-noisy/src/test/java/consoleoutput_noisy/Test3.java b/surefire-its/src/test/resources/consoleoutput-noisy/src/test/java/consoleoutput_noisy/Test3.java index 84c6198df3..db7058a716 100644 --- a/surefire-its/src/test/resources/consoleoutput-noisy/src/test/java/consoleoutput_noisy/Test3.java +++ b/surefire-its/src/test/resources/consoleoutput-noisy/src/test/java/consoleoutput_noisy/Test3.java @@ -1,24 +1,5 @@ package consoleoutput_noisy; -/* - * 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.junit.Test; import org.junit.After; import org.junit.AfterClass; diff --git a/surefire-its/src/test/resources/crash-detection/src/test/java/junit44/environment/BasicTest.java b/surefire-its/src/test/resources/crash-detection/src/test/java/junit44/environment/BasicTest.java index 2c97a7fd4f..c2157dcda0 100644 --- a/surefire-its/src/test/resources/crash-detection/src/test/java/junit44/environment/BasicTest.java +++ b/surefire-its/src/test/resources/crash-detection/src/test/java/junit44/environment/BasicTest.java @@ -1,24 +1,5 @@ package junit44.environment; -/* - * 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.junit.AfterClass; import org.junit.Test; diff --git a/surefire-its/src/test/resources/crash-during-test/src/test/java/junit44/environment/Test1CrashedTest.java b/surefire-its/src/test/resources/crash-during-test/src/test/java/junit44/environment/Test1CrashedTest.java index 446e930e26..e81596a57a 100644 --- a/surefire-its/src/test/resources/crash-during-test/src/test/java/junit44/environment/Test1CrashedTest.java +++ b/surefire-its/src/test/resources/crash-during-test/src/test/java/junit44/environment/Test1CrashedTest.java @@ -1,24 +1,5 @@ package junit44.environment; -/* - * 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 static java.util.concurrent.TimeUnit.MILLISECONDS; import static org.junit.Assert.*; import org.junit.Test; diff --git a/surefire-its/src/test/resources/crash-during-test/src/test/java/junit44/environment/Test2WaitingTest.java b/surefire-its/src/test/resources/crash-during-test/src/test/java/junit44/environment/Test2WaitingTest.java index dc3ce47dca..93e3d7b94a 100644 --- a/surefire-its/src/test/resources/crash-during-test/src/test/java/junit44/environment/Test2WaitingTest.java +++ b/surefire-its/src/test/resources/crash-during-test/src/test/java/junit44/environment/Test2WaitingTest.java @@ -1,24 +1,5 @@ package junit44.environment; -/* - * 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.junit.Test; import static java.util.concurrent.TimeUnit.MILLISECONDS; diff --git a/surefire-its/src/test/resources/crash-during-test/src/test/java/junit44/environment/Test3FastTest.java b/surefire-its/src/test/resources/crash-during-test/src/test/java/junit44/environment/Test3FastTest.java index 3a4d88e8bc..733adb6a92 100644 --- a/surefire-its/src/test/resources/crash-during-test/src/test/java/junit44/environment/Test3FastTest.java +++ b/surefire-its/src/test/resources/crash-during-test/src/test/java/junit44/environment/Test3FastTest.java @@ -1,24 +1,5 @@ package junit44.environment; -/* - * 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.junit.Test; public class Test3FastTest diff --git a/surefire-its/src/test/resources/default-configuration-abstract/src/test/java/abstractClasses/AbstractConcreteBasicTest.java b/surefire-its/src/test/resources/default-configuration-abstract/src/test/java/abstractClasses/AbstractConcreteBasicTest.java index d7a7fa52a6..93ced0e9b2 100644 --- a/surefire-its/src/test/resources/default-configuration-abstract/src/test/java/abstractClasses/AbstractConcreteBasicTest.java +++ b/surefire-its/src/test/resources/default-configuration-abstract/src/test/java/abstractClasses/AbstractConcreteBasicTest.java @@ -1,24 +1,5 @@ package abstractClasses; -/* - * 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 junit.extensions.TestSetup; import junit.framework.Test; import junit.framework.TestCase; diff --git a/surefire-its/src/test/resources/default-configuration-abstract/src/test/java/abstractClasses/NonInstantiableTest.java b/surefire-its/src/test/resources/default-configuration-abstract/src/test/java/abstractClasses/NonInstantiableTest.java index f08f888a57..47c177f2e9 100644 --- a/surefire-its/src/test/resources/default-configuration-abstract/src/test/java/abstractClasses/NonInstantiableTest.java +++ b/surefire-its/src/test/resources/default-configuration-abstract/src/test/java/abstractClasses/NonInstantiableTest.java @@ -1,24 +1,5 @@ package abstractClasses; -/* - * 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 junit.framework.TestCase; public abstract class NonInstantiableTest diff --git a/surefire-its/src/test/resources/default-configuration/src/test/java/defaultConfiguration/BasicTest.java b/surefire-its/src/test/resources/default-configuration/src/test/java/defaultConfiguration/BasicTest.java index 00d4ea2f99..236082ac77 100644 --- a/surefire-its/src/test/resources/default-configuration/src/test/java/defaultConfiguration/BasicTest.java +++ b/surefire-its/src/test/resources/default-configuration/src/test/java/defaultConfiguration/BasicTest.java @@ -1,24 +1,5 @@ package defaultConfiguration; -/* - * 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 junit.extensions.TestSetup; import junit.framework.Test; import junit.framework.TestCase; diff --git a/surefire-its/src/test/resources/environment-variables/src/test/java/environment/BasicTest.java b/surefire-its/src/test/resources/environment-variables/src/test/java/environment/BasicTest.java index e1a0f79d64..4cf51a89cb 100644 --- a/surefire-its/src/test/resources/environment-variables/src/test/java/environment/BasicTest.java +++ b/surefire-its/src/test/resources/environment-variables/src/test/java/environment/BasicTest.java @@ -1,24 +1,5 @@ package environment; -/* - * 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.hamcrest.core.IsNull; import org.junit.Assert; import org.junit.Test; diff --git a/surefire-its/src/test/resources/failingBuilds/src/test/java/failingbuilds/ExceptionsTest.java b/surefire-its/src/test/resources/failingBuilds/src/test/java/failingbuilds/ExceptionsTest.java index fe47279577..daa183928e 100644 --- a/surefire-its/src/test/resources/failingBuilds/src/test/java/failingbuilds/ExceptionsTest.java +++ b/surefire-its/src/test/resources/failingBuilds/src/test/java/failingbuilds/ExceptionsTest.java @@ -1,24 +1,5 @@ package failingbuilds; -/* - * 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.junit.Test; import static org.junit.Assert.assertTrue; @@ -35,4 +16,4 @@ public void testWithMultiLineExceptionBeingThrown() { throw new RuntimeException( "A very very long exception message indeed, which is to demonstrate truncation. It will be truncated somewhere\nA cat\nAnd a dog\nTried to make a\nParrot swim" ); } -} \ No newline at end of file +} diff --git a/surefire-its/src/test/resources/failure-result-counting/src/test/java/failureresultcounting/BeforeClassFailure.java b/surefire-its/src/test/resources/failure-result-counting/src/test/java/failureresultcounting/BeforeClassFailure.java index 62d51acc20..e24bc1632d 100644 --- a/surefire-its/src/test/resources/failure-result-counting/src/test/java/failureresultcounting/BeforeClassFailure.java +++ b/surefire-its/src/test/resources/failure-result-counting/src/test/java/failureresultcounting/BeforeClassFailure.java @@ -1,23 +1,4 @@ package failureresultcounting; -/* - * 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 junit.framework.Assert; import org.junit.BeforeClass; import org.junit.Test; @@ -40,4 +21,4 @@ public void ok() System.out.println( "failInBeforeClass run !!"); } -} \ No newline at end of file +} diff --git a/surefire-its/src/test/resources/failure-result-counting/src/test/java/failureresultcounting/BeforeError.java b/surefire-its/src/test/resources/failure-result-counting/src/test/java/failureresultcounting/BeforeError.java index 0798c80c51..fd6a49fdcc 100644 --- a/surefire-its/src/test/resources/failure-result-counting/src/test/java/failureresultcounting/BeforeError.java +++ b/surefire-its/src/test/resources/failure-result-counting/src/test/java/failureresultcounting/BeforeError.java @@ -1,23 +1,4 @@ package failureresultcounting; -/* - * 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.junit.Before; import org.junit.Test; @@ -45,4 +26,4 @@ public void ok2() System.out.println( "exceptionInBefore2 run!!"); } */ -} \ No newline at end of file +} diff --git a/surefire-its/src/test/resources/failure-result-counting/src/test/java/failureresultcounting/BeforeFailure.java b/surefire-its/src/test/resources/failure-result-counting/src/test/java/failureresultcounting/BeforeFailure.java index 174a448928..eff742fecb 100644 --- a/surefire-its/src/test/resources/failure-result-counting/src/test/java/failureresultcounting/BeforeFailure.java +++ b/surefire-its/src/test/resources/failure-result-counting/src/test/java/failureresultcounting/BeforeFailure.java @@ -1,23 +1,4 @@ package failureresultcounting; -/* - * 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 junit.framework.Assert; import org.junit.Before; import org.junit.Test; @@ -40,4 +21,4 @@ public void ok() System.out.println( "failInBEfore run !!"); } -} \ No newline at end of file +} diff --git a/surefire-its/src/test/resources/failure-result-counting/src/test/java/failureresultcounting/NoErrors.java b/surefire-its/src/test/resources/failure-result-counting/src/test/java/failureresultcounting/NoErrors.java index 245c9a65b6..2a3bca7e5f 100644 --- a/surefire-its/src/test/resources/failure-result-counting/src/test/java/failureresultcounting/NoErrors.java +++ b/surefire-its/src/test/resources/failure-result-counting/src/test/java/failureresultcounting/NoErrors.java @@ -1,23 +1,4 @@ package failureresultcounting; -/* - * 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.junit.Assert; import org.junit.Ignore; import org.junit.Test; @@ -40,4 +21,4 @@ public void allOk2() { } -} \ No newline at end of file +} diff --git a/surefire-its/src/test/resources/failure-result-counting/src/test/java/failureresultcounting/OrdinaryError.java b/surefire-its/src/test/resources/failure-result-counting/src/test/java/failureresultcounting/OrdinaryError.java index 7e6387aa8b..359f1f14b6 100644 --- a/surefire-its/src/test/resources/failure-result-counting/src/test/java/failureresultcounting/OrdinaryError.java +++ b/surefire-its/src/test/resources/failure-result-counting/src/test/java/failureresultcounting/OrdinaryError.java @@ -1,23 +1,4 @@ package failureresultcounting; -/* - * 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.junit.Assert; import org.junit.Test; @@ -39,4 +20,4 @@ public void ordinaryFailure() Assert.fail(); } -} \ No newline at end of file +} diff --git a/surefire-its/src/test/resources/failureOutput/src/test/java/forkConsoleOutput/Test1.java b/surefire-its/src/test/resources/failureOutput/src/test/java/forkConsoleOutput/Test1.java index af929523fd..66ba3a77de 100644 --- a/surefire-its/src/test/resources/failureOutput/src/test/java/forkConsoleOutput/Test1.java +++ b/surefire-its/src/test/resources/failureOutput/src/test/java/forkConsoleOutput/Test1.java @@ -1,24 +1,5 @@ package forkConsoleOutput; -/* - * 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.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; diff --git a/surefire-its/src/test/resources/failureOutput/src/test/java/forkConsoleOutput/Test2.java b/surefire-its/src/test/resources/failureOutput/src/test/java/forkConsoleOutput/Test2.java index f5c825eb82..5326963129 100644 --- a/surefire-its/src/test/resources/failureOutput/src/test/java/forkConsoleOutput/Test2.java +++ b/surefire-its/src/test/resources/failureOutput/src/test/java/forkConsoleOutput/Test2.java @@ -1,24 +1,5 @@ package forkConsoleOutput; -/* - * 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.junit.Test; public class Test2 diff --git a/surefire-its/src/test/resources/fork-consoleOutput/src/test/java/forkConsoleOutput/Test1.java b/surefire-its/src/test/resources/fork-consoleOutput/src/test/java/forkConsoleOutput/Test1.java index ad18954c34..4346b339d8 100644 --- a/surefire-its/src/test/resources/fork-consoleOutput/src/test/java/forkConsoleOutput/Test1.java +++ b/surefire-its/src/test/resources/fork-consoleOutput/src/test/java/forkConsoleOutput/Test1.java @@ -1,24 +1,5 @@ package forkConsoleOutput; -/* - * 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.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; diff --git a/surefire-its/src/test/resources/fork-consoleOutputWithErrors/src/test/java/forkConsoleOutput/Test1.java b/surefire-its/src/test/resources/fork-consoleOutputWithErrors/src/test/java/forkConsoleOutput/Test1.java index ad18954c34..4346b339d8 100644 --- a/surefire-its/src/test/resources/fork-consoleOutputWithErrors/src/test/java/forkConsoleOutput/Test1.java +++ b/surefire-its/src/test/resources/fork-consoleOutputWithErrors/src/test/java/forkConsoleOutput/Test1.java @@ -1,24 +1,5 @@ package forkConsoleOutput; -/* - * 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.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; diff --git a/surefire-its/src/test/resources/fork-consoleOutputWithErrors/src/test/java/forkConsoleOutput/Test2.java b/surefire-its/src/test/resources/fork-consoleOutputWithErrors/src/test/java/forkConsoleOutput/Test2.java index f5c825eb82..5326963129 100644 --- a/surefire-its/src/test/resources/fork-consoleOutputWithErrors/src/test/java/forkConsoleOutput/Test2.java +++ b/surefire-its/src/test/resources/fork-consoleOutputWithErrors/src/test/java/forkConsoleOutput/Test2.java @@ -1,24 +1,5 @@ package forkConsoleOutput; -/* - * 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.junit.Test; public class Test2 diff --git a/surefire-its/src/test/resources/fork-count-multimodule/module-a/src/test/java/forkCount/Test1.java b/surefire-its/src/test/resources/fork-count-multimodule/module-a/src/test/java/forkCount/Test1.java index fefe2ea1f8..3a98d37960 100644 --- a/surefire-its/src/test/resources/fork-count-multimodule/module-a/src/test/java/forkCount/Test1.java +++ b/surefire-its/src/test/resources/fork-count-multimodule/module-a/src/test/java/forkCount/Test1.java @@ -1,24 +1,5 @@ package forkCount; -/* - * 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 java.io.File; import java.io.FileWriter; import java.io.IOException; diff --git a/surefire-its/src/test/resources/fork-count-multimodule/module-a/src/test/java/forkCount/Test2.java b/surefire-its/src/test/resources/fork-count-multimodule/module-a/src/test/java/forkCount/Test2.java index abf068cf9e..b64be6e6da 100644 --- a/surefire-its/src/test/resources/fork-count-multimodule/module-a/src/test/java/forkCount/Test2.java +++ b/surefire-its/src/test/resources/fork-count-multimodule/module-a/src/test/java/forkCount/Test2.java @@ -1,24 +1,5 @@ package forkCount; -/* - * 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 java.io.IOException; import junit.framework.TestCase; diff --git a/surefire-its/src/test/resources/fork-count-multimodule/module-a/src/test/java/forkCount/Test3.java b/surefire-its/src/test/resources/fork-count-multimodule/module-a/src/test/java/forkCount/Test3.java index 1c024fac4e..47a081387c 100644 --- a/surefire-its/src/test/resources/fork-count-multimodule/module-a/src/test/java/forkCount/Test3.java +++ b/surefire-its/src/test/resources/fork-count-multimodule/module-a/src/test/java/forkCount/Test3.java @@ -1,24 +1,5 @@ package forkCount; -/* - * 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 java.io.IOException; import junit.framework.TestCase; diff --git a/surefire-its/src/test/resources/fork-count-multimodule/module-b/src/test/java/forkCount/Test1.java b/surefire-its/src/test/resources/fork-count-multimodule/module-b/src/test/java/forkCount/Test1.java index fefe2ea1f8..3a98d37960 100644 --- a/surefire-its/src/test/resources/fork-count-multimodule/module-b/src/test/java/forkCount/Test1.java +++ b/surefire-its/src/test/resources/fork-count-multimodule/module-b/src/test/java/forkCount/Test1.java @@ -1,24 +1,5 @@ package forkCount; -/* - * 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 java.io.File; import java.io.FileWriter; import java.io.IOException; diff --git a/surefire-its/src/test/resources/fork-count-multimodule/module-b/src/test/java/forkCount/Test2.java b/surefire-its/src/test/resources/fork-count-multimodule/module-b/src/test/java/forkCount/Test2.java index abf068cf9e..b64be6e6da 100644 --- a/surefire-its/src/test/resources/fork-count-multimodule/module-b/src/test/java/forkCount/Test2.java +++ b/surefire-its/src/test/resources/fork-count-multimodule/module-b/src/test/java/forkCount/Test2.java @@ -1,24 +1,5 @@ package forkCount; -/* - * 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 java.io.IOException; import junit.framework.TestCase; diff --git a/surefire-its/src/test/resources/fork-count-multimodule/module-b/src/test/java/forkCount/Test3.java b/surefire-its/src/test/resources/fork-count-multimodule/module-b/src/test/java/forkCount/Test3.java index 1c024fac4e..47a081387c 100644 --- a/surefire-its/src/test/resources/fork-count-multimodule/module-b/src/test/java/forkCount/Test3.java +++ b/surefire-its/src/test/resources/fork-count-multimodule/module-b/src/test/java/forkCount/Test3.java @@ -1,24 +1,5 @@ package forkCount; -/* - * 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 java.io.IOException; import junit.framework.TestCase; diff --git a/surefire-its/src/test/resources/fork-count-resource-loading/src/test/java/forkCount/ResourceLoadTest.java b/surefire-its/src/test/resources/fork-count-resource-loading/src/test/java/forkCount/ResourceLoadTest.java index 9083cde6d8..7d7c9397ac 100644 --- a/surefire-its/src/test/resources/fork-count-resource-loading/src/test/java/forkCount/ResourceLoadTest.java +++ b/surefire-its/src/test/resources/fork-count-resource-loading/src/test/java/forkCount/ResourceLoadTest.java @@ -1,24 +1,5 @@ package forkCount; -/* - * 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 junit.framework.TestCase; import java.io.IOException; diff --git a/surefire-its/src/test/resources/fork-count-testng/src/test/java/forkCount/Test1.java b/surefire-its/src/test/resources/fork-count-testng/src/test/java/forkCount/Test1.java index c4c982985b..182d9e003f 100644 --- a/surefire-its/src/test/resources/fork-count-testng/src/test/java/forkCount/Test1.java +++ b/surefire-its/src/test/resources/fork-count-testng/src/test/java/forkCount/Test1.java @@ -1,24 +1,5 @@ package forkCount; -/* - * 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 java.io.File; import java.io.FileWriter; import java.io.IOException; diff --git a/surefire-its/src/test/resources/fork-count-testng/src/test/java/forkCount/Test2.java b/surefire-its/src/test/resources/fork-count-testng/src/test/java/forkCount/Test2.java index 2c4aed447c..4661548207 100644 --- a/surefire-its/src/test/resources/fork-count-testng/src/test/java/forkCount/Test2.java +++ b/surefire-its/src/test/resources/fork-count-testng/src/test/java/forkCount/Test2.java @@ -1,24 +1,5 @@ package forkCount; -/* - * 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 java.io.IOException; import org.testng.annotations.Test; diff --git a/surefire-its/src/test/resources/fork-count-testng/src/test/java/forkCount/Test3.java b/surefire-its/src/test/resources/fork-count-testng/src/test/java/forkCount/Test3.java index 706622520d..b99ac883a3 100644 --- a/surefire-its/src/test/resources/fork-count-testng/src/test/java/forkCount/Test3.java +++ b/surefire-its/src/test/resources/fork-count-testng/src/test/java/forkCount/Test3.java @@ -1,24 +1,5 @@ package forkCount; -/* - * 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 java.io.IOException; import org.testng.annotations.Test; diff --git a/surefire-its/src/test/resources/fork-count/src/test/java/forkCount/Test1.java b/surefire-its/src/test/resources/fork-count/src/test/java/forkCount/Test1.java index 87f4cd0be5..a3e41ff199 100644 --- a/surefire-its/src/test/resources/fork-count/src/test/java/forkCount/Test1.java +++ b/surefire-its/src/test/resources/fork-count/src/test/java/forkCount/Test1.java @@ -1,24 +1,5 @@ package forkCount; -/* - * 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 java.io.File; import java.io.FileWriter; import java.io.IOException; diff --git a/surefire-its/src/test/resources/fork-count/src/test/java/forkCount/Test2.java b/surefire-its/src/test/resources/fork-count/src/test/java/forkCount/Test2.java index ce621a7c1f..412c062a4d 100644 --- a/surefire-its/src/test/resources/fork-count/src/test/java/forkCount/Test2.java +++ b/surefire-its/src/test/resources/fork-count/src/test/java/forkCount/Test2.java @@ -1,24 +1,5 @@ package forkCount; -/* - * 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 java.io.IOException; import junit.framework.TestCase; diff --git a/surefire-its/src/test/resources/fork-count/src/test/java/forkCount/Test3.java b/surefire-its/src/test/resources/fork-count/src/test/java/forkCount/Test3.java index c3c9d80837..ba73b167be 100644 --- a/surefire-its/src/test/resources/fork-count/src/test/java/forkCount/Test3.java +++ b/surefire-its/src/test/resources/fork-count/src/test/java/forkCount/Test3.java @@ -1,24 +1,5 @@ package forkCount; -/* - * 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 java.io.IOException; import junit.framework.TestCase; diff --git a/surefire-its/src/test/resources/fork-fail/src/test/java/forkCount/Test1.java b/surefire-its/src/test/resources/fork-fail/src/test/java/forkCount/Test1.java index 0aee23b5a9..7ec038a2b6 100644 --- a/surefire-its/src/test/resources/fork-fail/src/test/java/forkCount/Test1.java +++ b/surefire-its/src/test/resources/fork-fail/src/test/java/forkCount/Test1.java @@ -1,24 +1,5 @@ package forkCount; -/* - * 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 java.io.File; import java.io.FileWriter; import java.io.IOException; diff --git a/surefire-its/src/test/resources/fork-fail/src/test/java/forkCount/Test2.java b/surefire-its/src/test/resources/fork-fail/src/test/java/forkCount/Test2.java index e702ddf024..19be9ba01b 100644 --- a/surefire-its/src/test/resources/fork-fail/src/test/java/forkCount/Test2.java +++ b/surefire-its/src/test/resources/fork-fail/src/test/java/forkCount/Test2.java @@ -1,24 +1,5 @@ package forkCount; -/* - * 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 java.io.IOException; import junit.framework.TestCase; diff --git a/surefire-its/src/test/resources/fork-fail/src/test/java/forkCount/Test3.java b/surefire-its/src/test/resources/fork-fail/src/test/java/forkCount/Test3.java index 1c024fac4e..47a081387c 100644 --- a/surefire-its/src/test/resources/fork-fail/src/test/java/forkCount/Test3.java +++ b/surefire-its/src/test/resources/fork-fail/src/test/java/forkCount/Test3.java @@ -1,24 +1,5 @@ package forkCount; -/* - * 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 java.io.IOException; import junit.framework.TestCase; diff --git a/surefire-its/src/test/resources/fork-timeout/src/test/java/forktimeout/Test1.java b/surefire-its/src/test/resources/fork-timeout/src/test/java/forktimeout/Test1.java index d176fcec6d..6c4ab3d200 100644 --- a/surefire-its/src/test/resources/fork-timeout/src/test/java/forktimeout/Test1.java +++ b/surefire-its/src/test/resources/fork-timeout/src/test/java/forktimeout/Test1.java @@ -1,24 +1,5 @@ package forktimeout; -/* - * 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.junit.Test; public class Test1 @@ -31,4 +12,4 @@ public void test690() System.out.println( " with lots of output " ); System.err.println( "e with lots of output " ); } -} \ No newline at end of file +} diff --git a/surefire-its/src/test/resources/includes-excludes-from-file/src/test/java/org/test/DefaultTest.java b/surefire-its/src/test/resources/includes-excludes-from-file/src/test/java/org/test/DefaultTest.java index 4fd72966ee..2ba90a2124 100644 --- a/surefire-its/src/test/resources/includes-excludes-from-file/src/test/java/org/test/DefaultTest.java +++ b/surefire-its/src/test/resources/includes-excludes-from-file/src/test/java/org/test/DefaultTest.java @@ -1,24 +1,5 @@ package org.test; -/* - * 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 java.io.FileOutputStream; public class DefaultTest diff --git a/surefire-its/src/test/resources/includes-excludes-from-file/src/test/java/org/test/DontRunTest.java b/surefire-its/src/test/resources/includes-excludes-from-file/src/test/java/org/test/DontRunTest.java index 0cce390424..3d94c854a7 100644 --- a/surefire-its/src/test/resources/includes-excludes-from-file/src/test/java/org/test/DontRunTest.java +++ b/surefire-its/src/test/resources/includes-excludes-from-file/src/test/java/org/test/DontRunTest.java @@ -1,24 +1,5 @@ package org.test; -/* - * 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 junit.framework.TestCase; public class DontRunTest extends TestCase diff --git a/surefire-its/src/test/resources/includes-excludes-from-file/src/test/java/org/test/NotIncludedByDefault.java b/surefire-its/src/test/resources/includes-excludes-from-file/src/test/java/org/test/NotIncludedByDefault.java index 80c64f82c3..359e54934c 100644 --- a/surefire-its/src/test/resources/includes-excludes-from-file/src/test/java/org/test/NotIncludedByDefault.java +++ b/surefire-its/src/test/resources/includes-excludes-from-file/src/test/java/org/test/NotIncludedByDefault.java @@ -1,24 +1,5 @@ package org.test; -/* - * 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 java.io.FileOutputStream; public class NotIncludedByDefault diff --git a/surefire-its/src/test/resources/includes-excludes/src/test/java/org/test/DefaultTest.java b/surefire-its/src/test/resources/includes-excludes/src/test/java/org/test/DefaultTest.java index 4fd72966ee..2ba90a2124 100644 --- a/surefire-its/src/test/resources/includes-excludes/src/test/java/org/test/DefaultTest.java +++ b/surefire-its/src/test/resources/includes-excludes/src/test/java/org/test/DefaultTest.java @@ -1,24 +1,5 @@ package org.test; -/* - * 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 java.io.FileOutputStream; public class DefaultTest diff --git a/surefire-its/src/test/resources/includes-excludes/src/test/java/org/test/DontRunTest.java b/surefire-its/src/test/resources/includes-excludes/src/test/java/org/test/DontRunTest.java index 0cce390424..3d94c854a7 100644 --- a/surefire-its/src/test/resources/includes-excludes/src/test/java/org/test/DontRunTest.java +++ b/surefire-its/src/test/resources/includes-excludes/src/test/java/org/test/DontRunTest.java @@ -1,24 +1,5 @@ package org.test; -/* - * 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 junit.framework.TestCase; public class DontRunTest extends TestCase diff --git a/surefire-its/src/test/resources/includes-excludes/src/test/java/org/test/NotIncludedByDefault.java b/surefire-its/src/test/resources/includes-excludes/src/test/java/org/test/NotIncludedByDefault.java index 80c64f82c3..359e54934c 100644 --- a/surefire-its/src/test/resources/includes-excludes/src/test/java/org/test/NotIncludedByDefault.java +++ b/surefire-its/src/test/resources/includes-excludes/src/test/java/org/test/NotIncludedByDefault.java @@ -1,24 +1,5 @@ package org.test; -/* - * 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 java.io.FileOutputStream; public class NotIncludedByDefault diff --git a/surefire-its/src/test/resources/isolated-classloader/src/test/java/isolatedClassloader/BasicTest.java b/surefire-its/src/test/resources/isolated-classloader/src/test/java/isolatedClassloader/BasicTest.java index f293734025..550c00bd63 100644 --- a/surefire-its/src/test/resources/isolated-classloader/src/test/java/isolatedClassloader/BasicTest.java +++ b/surefire-its/src/test/resources/isolated-classloader/src/test/java/isolatedClassloader/BasicTest.java @@ -1,24 +1,5 @@ package isolatedClassloader; -/* - * 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 junit.extensions.TestSetup; import junit.framework.Test; import junit.framework.TestCase; diff --git a/surefire-its/src/test/resources/java9-full-api/src/test/java/java9/full/api/J9IT.java b/surefire-its/src/test/resources/java9-full-api/src/test/java/java9/full/api/J9IT.java index 9c8f976519..cefac4ceac 100644 --- a/surefire-its/src/test/resources/java9-full-api/src/test/java/java9/full/api/J9IT.java +++ b/surefire-its/src/test/resources/java9-full-api/src/test/java/java9/full/api/J9IT.java @@ -1,24 +1,5 @@ package java9.full.api; -/* - * 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.junit.Test; public class J9IT diff --git a/surefire-its/src/test/resources/java9-full-api/src/test/java/java9/full/api/J9Test.java b/surefire-its/src/test/resources/java9-full-api/src/test/java/java9/full/api/J9Test.java index 71e645f65a..ef90dcd7e4 100644 --- a/surefire-its/src/test/resources/java9-full-api/src/test/java/java9/full/api/J9Test.java +++ b/surefire-its/src/test/resources/java9-full-api/src/test/java/java9/full/api/J9Test.java @@ -1,24 +1,5 @@ package java9.full.api; -/* - * 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.junit.Test; public class J9Test diff --git a/surefire-its/src/test/resources/junit-ignore/src/test/java/junit/ignore/ClassAndMethodIgnoreNothingToRunTest.java b/surefire-its/src/test/resources/junit-ignore/src/test/java/junit/ignore/ClassAndMethodIgnoreNothingToRunTest.java index 66e858edaf..15f05f97cb 100644 --- a/surefire-its/src/test/resources/junit-ignore/src/test/java/junit/ignore/ClassAndMethodIgnoreNothingToRunTest.java +++ b/surefire-its/src/test/resources/junit-ignore/src/test/java/junit/ignore/ClassAndMethodIgnoreNothingToRunTest.java @@ -1,24 +1,5 @@ package junit.ignore; -/* - * 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.junit.Assert; import org.junit.Ignore; import org.junit.Test; diff --git a/surefire-its/src/test/resources/junit-ignore/src/test/java/junit/ignore/ClassLevelIgnore1WithMethodThatIsNormalTest.java b/surefire-its/src/test/resources/junit-ignore/src/test/java/junit/ignore/ClassLevelIgnore1WithMethodThatIsNormalTest.java index 7012f87caa..7570f7f88e 100644 --- a/surefire-its/src/test/resources/junit-ignore/src/test/java/junit/ignore/ClassLevelIgnore1WithMethodThatIsNormalTest.java +++ b/surefire-its/src/test/resources/junit-ignore/src/test/java/junit/ignore/ClassLevelIgnore1WithMethodThatIsNormalTest.java @@ -1,24 +1,5 @@ package junit.ignore; -/* - * 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.junit.Assert; import org.junit.Ignore; import org.junit.Test; diff --git a/surefire-its/src/test/resources/junit-ignore/src/test/java/junit/ignore/ClassLevelIgnore2WithMethodThatIsNormalTest.java b/surefire-its/src/test/resources/junit-ignore/src/test/java/junit/ignore/ClassLevelIgnore2WithMethodThatIsNormalTest.java index ee64317196..b6cbcf63df 100644 --- a/surefire-its/src/test/resources/junit-ignore/src/test/java/junit/ignore/ClassLevelIgnore2WithMethodThatIsNormalTest.java +++ b/surefire-its/src/test/resources/junit-ignore/src/test/java/junit/ignore/ClassLevelIgnore2WithMethodThatIsNormalTest.java @@ -1,24 +1,5 @@ package junit.ignore; -/* - * 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.junit.Assert; import org.junit.Ignore; import org.junit.Test; diff --git a/surefire-its/src/test/resources/junit-ignore/src/test/java/junit/ignore/NormalClassWithThreeIgnoredMethodsAnd1AssumptionFailureTest.java b/surefire-its/src/test/resources/junit-ignore/src/test/java/junit/ignore/NormalClassWithThreeIgnoredMethodsAnd1AssumptionFailureTest.java index cc50d1d980..765eb8a120 100644 --- a/surefire-its/src/test/resources/junit-ignore/src/test/java/junit/ignore/NormalClassWithThreeIgnoredMethodsAnd1AssumptionFailureTest.java +++ b/surefire-its/src/test/resources/junit-ignore/src/test/java/junit/ignore/NormalClassWithThreeIgnoredMethodsAnd1AssumptionFailureTest.java @@ -1,24 +1,5 @@ package junit.ignore; -/* - * 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.junit.Assume; import org.junit.Ignore; import org.junit.Test; diff --git a/surefire-its/src/test/resources/junit-innerClass/src/test/java/junit/innerClass/BasicTest.java b/surefire-its/src/test/resources/junit-innerClass/src/test/java/junit/innerClass/BasicTest.java index 81be27e9cf..2f17817760 100644 --- a/surefire-its/src/test/resources/junit-innerClass/src/test/java/junit/innerClass/BasicTest.java +++ b/surefire-its/src/test/resources/junit-innerClass/src/test/java/junit/innerClass/BasicTest.java @@ -1,24 +1,5 @@ package junit.innerClass; -/* - * 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 junit.framework.TestCase; public class BasicTest diff --git a/surefire-its/src/test/resources/junit-notExtendingTestCase/src/test/java/junit/notExtendingTestCase/SuiteTest.java b/surefire-its/src/test/resources/junit-notExtendingTestCase/src/test/java/junit/notExtendingTestCase/SuiteTest.java index 69fa59a01e..631db854e7 100644 --- a/surefire-its/src/test/resources/junit-notExtendingTestCase/src/test/java/junit/notExtendingTestCase/SuiteTest.java +++ b/surefire-its/src/test/resources/junit-notExtendingTestCase/src/test/java/junit/notExtendingTestCase/SuiteTest.java @@ -1,24 +1,5 @@ package junit.notExtendingTestCase; -/* - * 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 junit.framework.Test; import junit.framework.TestResult; import junit.framework.TestSuite; diff --git a/surefire-its/src/test/resources/junit-pathWithUmlaut/src/test/java/umlautTest/BasicTest.java b/surefire-its/src/test/resources/junit-pathWithUmlaut/src/test/java/umlautTest/BasicTest.java index 0c27bb5c70..a031cbaae5 100644 --- a/surefire-its/src/test/resources/junit-pathWithUmlaut/src/test/java/umlautTest/BasicTest.java +++ b/surefire-its/src/test/resources/junit-pathWithUmlaut/src/test/java/umlautTest/BasicTest.java @@ -1,25 +1,6 @@ package umlautTest; -/* - * 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 junit.extensions.TestSetup; import junit.framework.Test; import junit.framework.TestCase; diff --git a/surefire-its/src/test/resources/junit-platform-engine-jqwik/src/test/java/junitplatformenginejqwik/BasicJQwikTest.java b/surefire-its/src/test/resources/junit-platform-engine-jqwik/src/test/java/junitplatformenginejqwik/BasicJQwikTest.java index 27120ee00e..cdcfe62ea2 100644 --- a/surefire-its/src/test/resources/junit-platform-engine-jqwik/src/test/java/junitplatformenginejqwik/BasicJQwikTest.java +++ b/surefire-its/src/test/resources/junit-platform-engine-jqwik/src/test/java/junitplatformenginejqwik/BasicJQwikTest.java @@ -1,24 +1,5 @@ package junitplatformenginejqwik; -/* - * 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 net.jqwik.api.Example; class BasicJQwikTest diff --git a/surefire-its/src/test/resources/junit-platform-engine-jupiter/src/test/java/junitplatformenginejupiter/BasicJupiterTest.java b/surefire-its/src/test/resources/junit-platform-engine-jupiter/src/test/java/junitplatformenginejupiter/BasicJupiterTest.java index d85db86dc5..f7de8645e5 100644 --- a/surefire-its/src/test/resources/junit-platform-engine-jupiter/src/test/java/junitplatformenginejupiter/BasicJupiterTest.java +++ b/surefire-its/src/test/resources/junit-platform-engine-jupiter/src/test/java/junitplatformenginejupiter/BasicJupiterTest.java @@ -1,24 +1,5 @@ package junitplatformenginejupiter; -/* - * 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 static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; diff --git a/surefire-its/src/test/resources/junit-platform-engine-jupiter/src/test/java/junitplatformenginejupiter/DisplayNameTest.java b/surefire-its/src/test/resources/junit-platform-engine-jupiter/src/test/java/junitplatformenginejupiter/DisplayNameTest.java index a6401e3092..c1e2cc4d68 100644 --- a/surefire-its/src/test/resources/junit-platform-engine-jupiter/src/test/java/junitplatformenginejupiter/DisplayNameTest.java +++ b/surefire-its/src/test/resources/junit-platform-engine-jupiter/src/test/java/junitplatformenginejupiter/DisplayNameTest.java @@ -1,24 +1,5 @@ package junitplatformenginejupiter; -/* - * 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.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; diff --git a/surefire-its/src/test/resources/junit-platform-engine-vintage/src/test/java/junitplatformenginevintage/BasicVintageTest.java b/surefire-its/src/test/resources/junit-platform-engine-vintage/src/test/java/junitplatformenginevintage/BasicVintageTest.java index 04e9aafa45..f613a350d4 100644 --- a/surefire-its/src/test/resources/junit-platform-engine-vintage/src/test/java/junitplatformenginevintage/BasicVintageTest.java +++ b/surefire-its/src/test/resources/junit-platform-engine-vintage/src/test/java/junitplatformenginevintage/BasicVintageTest.java @@ -1,24 +1,5 @@ package junitplatformenginevintage; -/* - * 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.junit.After; import org.junit.AfterClass; import org.junit.Assert; diff --git a/surefire-its/src/test/resources/junit-platform-multiple-engines/src/test/java/junitplatformenginejqwik/BasicJQwikTest.java b/surefire-its/src/test/resources/junit-platform-multiple-engines/src/test/java/junitplatformenginejqwik/BasicJQwikTest.java index 27120ee00e..cdcfe62ea2 100644 --- a/surefire-its/src/test/resources/junit-platform-multiple-engines/src/test/java/junitplatformenginejqwik/BasicJQwikTest.java +++ b/surefire-its/src/test/resources/junit-platform-multiple-engines/src/test/java/junitplatformenginejqwik/BasicJQwikTest.java @@ -1,24 +1,5 @@ package junitplatformenginejqwik; -/* - * 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 net.jqwik.api.Example; class BasicJQwikTest diff --git a/surefire-its/src/test/resources/junit-platform-multiple-engines/src/test/java/junitplatformenginejupiter/BasicJupiterTest.java b/surefire-its/src/test/resources/junit-platform-multiple-engines/src/test/java/junitplatformenginejupiter/BasicJupiterTest.java index d85db86dc5..f7de8645e5 100644 --- a/surefire-its/src/test/resources/junit-platform-multiple-engines/src/test/java/junitplatformenginejupiter/BasicJupiterTest.java +++ b/surefire-its/src/test/resources/junit-platform-multiple-engines/src/test/java/junitplatformenginejupiter/BasicJupiterTest.java @@ -1,24 +1,5 @@ package junitplatformenginejupiter; -/* - * 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 static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; diff --git a/surefire-its/src/test/resources/junit-platform-multiple-engines/src/test/java/junitplatformenginevintage/BasicVintageTest.java b/surefire-its/src/test/resources/junit-platform-multiple-engines/src/test/java/junitplatformenginevintage/BasicVintageTest.java index 04e9aafa45..f613a350d4 100644 --- a/surefire-its/src/test/resources/junit-platform-multiple-engines/src/test/java/junitplatformenginevintage/BasicVintageTest.java +++ b/surefire-its/src/test/resources/junit-platform-multiple-engines/src/test/java/junitplatformenginevintage/BasicVintageTest.java @@ -1,24 +1,5 @@ package junitplatformenginevintage; -/* - * 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.junit.After; import org.junit.AfterClass; import org.junit.Assert; diff --git a/surefire-its/src/test/resources/junit-platform-rerun-failing-tests/src/test/java/junitplatform/FlakyFirstTimeTest.java b/surefire-its/src/test/resources/junit-platform-rerun-failing-tests/src/test/java/junitplatform/FlakyFirstTimeTest.java index 5c53d6d78e..58e71ab349 100644 --- a/surefire-its/src/test/resources/junit-platform-rerun-failing-tests/src/test/java/junitplatform/FlakyFirstTimeTest.java +++ b/surefire-its/src/test/resources/junit-platform-rerun-failing-tests/src/test/java/junitplatform/FlakyFirstTimeTest.java @@ -1,24 +1,5 @@ package junitplatform; -/* - * 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.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.fail; diff --git a/surefire-its/src/test/resources/junit-platform-rerun-failing-tests/src/test/java/junitplatform/ParametersTest.java b/surefire-its/src/test/resources/junit-platform-rerun-failing-tests/src/test/java/junitplatform/ParametersTest.java index a4e4e381e4..210ff5b511 100644 --- a/surefire-its/src/test/resources/junit-platform-rerun-failing-tests/src/test/java/junitplatform/ParametersTest.java +++ b/surefire-its/src/test/resources/junit-platform-rerun-failing-tests/src/test/java/junitplatform/ParametersTest.java @@ -1,24 +1,5 @@ package junitplatform; -/* - * 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.junit.jupiter.api.Test; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assumptions; diff --git a/surefire-its/src/test/resources/junit-platform-rerun-failing-tests/src/test/java/junitplatform/PassingTest.java b/surefire-its/src/test/resources/junit-platform-rerun-failing-tests/src/test/java/junitplatform/PassingTest.java index 4f80f9fea0..cc48ef4fb8 100644 --- a/surefire-its/src/test/resources/junit-platform-rerun-failing-tests/src/test/java/junitplatform/PassingTest.java +++ b/surefire-its/src/test/resources/junit-platform-rerun-failing-tests/src/test/java/junitplatform/PassingTest.java @@ -1,24 +1,5 @@ package junitplatform; -/* - * 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.junit.jupiter.api.Test; diff --git a/surefire-its/src/test/resources/junit-platform-tags/src/test/java/tags/JUnitPlatformWithTagsTest.java b/surefire-its/src/test/resources/junit-platform-tags/src/test/java/tags/JUnitPlatformWithTagsTest.java index 789c9e2fbf..d6f2957ee1 100644 --- a/surefire-its/src/test/resources/junit-platform-tags/src/test/java/tags/JUnitPlatformWithTagsTest.java +++ b/surefire-its/src/test/resources/junit-platform-tags/src/test/java/tags/JUnitPlatformWithTagsTest.java @@ -1,24 +1,5 @@ package tags; -/* - * 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 static org.junit.jupiter.api.Assertions.fail; import org.junit.jupiter.api.Tag; diff --git a/surefire-its/src/test/resources/junit-platform/src/test/java/junitplatform/JUnitPlatformTest.java b/surefire-its/src/test/resources/junit-platform/src/test/java/junitplatform/JUnitPlatformTest.java index 68bbe0289f..a0677d3476 100644 --- a/surefire-its/src/test/resources/junit-platform/src/test/java/junitplatform/JUnitPlatformTest.java +++ b/surefire-its/src/test/resources/junit-platform/src/test/java/junitplatform/JUnitPlatformTest.java @@ -1,24 +1,5 @@ package junitplatform_1_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. - */ - import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; diff --git a/surefire-its/src/test/resources/junit-twoTestCaseSuite/src/test/java/junit/twoTestCaseSuite/TestTwo.java b/surefire-its/src/test/resources/junit-twoTestCaseSuite/src/test/java/junit/twoTestCaseSuite/TestTwo.java index f4038190d5..0e9467ae88 100644 --- a/surefire-its/src/test/resources/junit-twoTestCaseSuite/src/test/java/junit/twoTestCaseSuite/TestTwo.java +++ b/surefire-its/src/test/resources/junit-twoTestCaseSuite/src/test/java/junit/twoTestCaseSuite/TestTwo.java @@ -1,24 +1,5 @@ package junit.twoTestCaseSuite; -/* - * 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 junit.framework.TestCase; diff --git a/surefire-its/src/test/resources/junit-twoTestCaseSuite/src/test/java/junit/twoTestCaseSuite/WrapperTestSuite.java b/surefire-its/src/test/resources/junit-twoTestCaseSuite/src/test/java/junit/twoTestCaseSuite/WrapperTestSuite.java index 9bd71b5c89..a2dfc08bf7 100644 --- a/surefire-its/src/test/resources/junit-twoTestCaseSuite/src/test/java/junit/twoTestCaseSuite/WrapperTestSuite.java +++ b/surefire-its/src/test/resources/junit-twoTestCaseSuite/src/test/java/junit/twoTestCaseSuite/WrapperTestSuite.java @@ -1,25 +1,6 @@ package junit.twoTestCaseSuite; -/* - * 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 junit.framework.Test; import junit.framework.TestSuite; diff --git a/surefire-its/src/test/resources/junit-twoTestCases/src/test/java/junit/twoTestCases/BasicTest.java b/surefire-its/src/test/resources/junit-twoTestCases/src/test/java/junit/twoTestCases/BasicTest.java index 2efc5ed2af..e3ce320ba8 100644 --- a/surefire-its/src/test/resources/junit-twoTestCases/src/test/java/junit/twoTestCases/BasicTest.java +++ b/surefire-its/src/test/resources/junit-twoTestCases/src/test/java/junit/twoTestCases/BasicTest.java @@ -1,24 +1,5 @@ package junit.twoTestCases; -/* - * 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 junit.extensions.TestSetup; import junit.framework.Test; import junit.framework.TestCase; diff --git a/surefire-its/src/test/resources/junit-twoTestCases/src/test/java/junit/twoTestCases/TestTwo.java b/surefire-its/src/test/resources/junit-twoTestCases/src/test/java/junit/twoTestCases/TestTwo.java index 9af4558751..e6377b63e7 100644 --- a/surefire-its/src/test/resources/junit-twoTestCases/src/test/java/junit/twoTestCases/TestTwo.java +++ b/surefire-its/src/test/resources/junit-twoTestCases/src/test/java/junit/twoTestCases/TestTwo.java @@ -1,24 +1,5 @@ package junit.twoTestCases; -/* - * 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 junit.framework.TestCase; diff --git a/surefire-its/src/test/resources/junit4-forkAlways-staticInit/src/test/java/junit4/App2Test.java b/surefire-its/src/test/resources/junit4-forkAlways-staticInit/src/test/java/junit4/App2Test.java index 90f56d4531..5f822bb704 100644 --- a/surefire-its/src/test/resources/junit4-forkAlways-staticInit/src/test/java/junit4/App2Test.java +++ b/surefire-its/src/test/resources/junit4-forkAlways-staticInit/src/test/java/junit4/App2Test.java @@ -1,24 +1,5 @@ package junit4; -/* - * 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 java.util.Properties; import junit.framework.TestCase; diff --git a/surefire-its/src/test/resources/junit4-forkAlways-staticInit/src/test/java/junit4/AppTest.java b/surefire-its/src/test/resources/junit4-forkAlways-staticInit/src/test/java/junit4/AppTest.java index 4b2b0d7680..1ea02dccd3 100644 --- a/surefire-its/src/test/resources/junit4-forkAlways-staticInit/src/test/java/junit4/AppTest.java +++ b/surefire-its/src/test/resources/junit4-forkAlways-staticInit/src/test/java/junit4/AppTest.java @@ -1,24 +1,5 @@ package junit4; -/* - * 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 java.util.Properties; import junit.framework.TestCase; diff --git a/surefire-its/src/test/resources/junit4-rerun-failing-tests/src/test/java/junit4/FlakyFirstTimeTest.java b/surefire-its/src/test/resources/junit4-rerun-failing-tests/src/test/java/junit4/FlakyFirstTimeTest.java index 264462c5e2..d254d76d55 100644 --- a/surefire-its/src/test/resources/junit4-rerun-failing-tests/src/test/java/junit4/FlakyFirstTimeTest.java +++ b/surefire-its/src/test/resources/junit4-rerun-failing-tests/src/test/java/junit4/FlakyFirstTimeTest.java @@ -1,24 +1,5 @@ package junit4; -/* - * 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.junit.Assert; import org.junit.Test; diff --git a/surefire-its/src/test/resources/junit4-rerun-failing-tests/src/test/java/junit4/PassingTest.java b/surefire-its/src/test/resources/junit4-rerun-failing-tests/src/test/java/junit4/PassingTest.java index 7cb0b572d8..ee3f4e3a63 100644 --- a/surefire-its/src/test/resources/junit4-rerun-failing-tests/src/test/java/junit4/PassingTest.java +++ b/surefire-its/src/test/resources/junit4-rerun-failing-tests/src/test/java/junit4/PassingTest.java @@ -1,24 +1,5 @@ package junit4; -/* - * 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.junit.Assert; import org.junit.Test; diff --git a/surefire-its/src/test/resources/junit4-runlistener/src/test/java/runListener/EchoingRunListener.java b/surefire-its/src/test/resources/junit4-runlistener/src/test/java/runListener/EchoingRunListener.java index 305c65688f..bd9eefbf5c 100644 --- a/surefire-its/src/test/resources/junit4-runlistener/src/test/java/runListener/EchoingRunListener.java +++ b/surefire-its/src/test/resources/junit4-runlistener/src/test/java/runListener/EchoingRunListener.java @@ -1,24 +1,5 @@ package runListener; -/* - * 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.junit.runner.Description; import org.junit.runner.Result; import org.junit.runner.notification.Failure; diff --git a/surefire-its/src/test/resources/junit4-runlistener/src/test/java/runListener/FileHelper.java b/surefire-its/src/test/resources/junit4-runlistener/src/test/java/runListener/FileHelper.java index 5387390997..e1e0b1cfe5 100644 --- a/surefire-its/src/test/resources/junit4-runlistener/src/test/java/runListener/FileHelper.java +++ b/surefire-its/src/test/resources/junit4-runlistener/src/test/java/runListener/FileHelper.java @@ -1,24 +1,5 @@ package runListener; -/* - * 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 java.io.File; import java.io.FileWriter; import java.io.IOException; diff --git a/surefire-its/src/test/resources/junit4-runlistener/src/test/java/runListener/FileWritingRunListener1.java b/surefire-its/src/test/resources/junit4-runlistener/src/test/java/runListener/FileWritingRunListener1.java index 24f479dff3..a9f7d69e17 100644 --- a/surefire-its/src/test/resources/junit4-runlistener/src/test/java/runListener/FileWritingRunListener1.java +++ b/surefire-its/src/test/resources/junit4-runlistener/src/test/java/runListener/FileWritingRunListener1.java @@ -1,24 +1,5 @@ package runListener; -/* - * 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.junit.runner.Description; import org.junit.runner.notification.RunListener; diff --git a/surefire-its/src/test/resources/junit4-runlistener/src/test/java/runListener/FileWritingRunListener2.java b/surefire-its/src/test/resources/junit4-runlistener/src/test/java/runListener/FileWritingRunListener2.java index 49c282414e..885dcd7c2b 100644 --- a/surefire-its/src/test/resources/junit4-runlistener/src/test/java/runListener/FileWritingRunListener2.java +++ b/surefire-its/src/test/resources/junit4-runlistener/src/test/java/runListener/FileWritingRunListener2.java @@ -1,24 +1,5 @@ package runListener; -/* - * 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.junit.runner.Description; import org.junit.runner.notification.RunListener; diff --git a/surefire-its/src/test/resources/junit4-runlistener/src/test/java/runListener/JUnit4RunListenerTest.java b/surefire-its/src/test/resources/junit4-runlistener/src/test/java/runListener/JUnit4RunListenerTest.java index 12c32ac5a2..bff902a468 100644 --- a/surefire-its/src/test/resources/junit4-runlistener/src/test/java/runListener/JUnit4RunListenerTest.java +++ b/surefire-its/src/test/resources/junit4-runlistener/src/test/java/runListener/JUnit4RunListenerTest.java @@ -1,24 +1,5 @@ package runListener; -/* - * 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.junit.Assert; import org.junit.Test; diff --git a/surefire-its/src/test/resources/junit4-twoTestCaseSuite/src/test/java/twoTestCaseSuite/BasicTest.java b/surefire-its/src/test/resources/junit4-twoTestCaseSuite/src/test/java/twoTestCaseSuite/BasicTest.java index a7936108f6..f0a4377ae4 100644 --- a/surefire-its/src/test/resources/junit4-twoTestCaseSuite/src/test/java/twoTestCaseSuite/BasicTest.java +++ b/surefire-its/src/test/resources/junit4-twoTestCaseSuite/src/test/java/twoTestCaseSuite/BasicTest.java @@ -1,24 +1,5 @@ package twoTestCaseSuite; -/* - * 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.junit.After; import org.junit.AfterClass; import org.junit.Assert; diff --git a/surefire-its/src/test/resources/junit4-twoTestCaseSuite/src/test/java/twoTestCaseSuite/Junit4TestSuite.java b/surefire-its/src/test/resources/junit4-twoTestCaseSuite/src/test/java/twoTestCaseSuite/Junit4TestSuite.java index 011c70edb4..46aed6f138 100644 --- a/surefire-its/src/test/resources/junit4-twoTestCaseSuite/src/test/java/twoTestCaseSuite/Junit4TestSuite.java +++ b/surefire-its/src/test/resources/junit4-twoTestCaseSuite/src/test/java/twoTestCaseSuite/Junit4TestSuite.java @@ -1,24 +1,5 @@ package twoTestCaseSuite; -/* - * 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.junit.runner.RunWith; import org.junit.runners.Suite; diff --git a/surefire-its/src/test/resources/junit4-twoTestCaseSuite/src/test/java/twoTestCaseSuite/Junit4TestTwo.java b/surefire-its/src/test/resources/junit4-twoTestCaseSuite/src/test/java/twoTestCaseSuite/Junit4TestTwo.java index 849e64b461..b97d6474d7 100644 --- a/surefire-its/src/test/resources/junit4-twoTestCaseSuite/src/test/java/twoTestCaseSuite/Junit4TestTwo.java +++ b/surefire-its/src/test/resources/junit4-twoTestCaseSuite/src/test/java/twoTestCaseSuite/Junit4TestTwo.java @@ -1,24 +1,5 @@ package twoTestCaseSuite; -/* - * 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.junit.Test; public class Junit4TestTwo diff --git a/surefire-its/src/test/resources/junit4/src/test/java/junit4/BasicTest.java b/surefire-its/src/test/resources/junit4/src/test/java/junit4/BasicTest.java index 144df7422b..e2dbd65d06 100644 --- a/surefire-its/src/test/resources/junit4/src/test/java/junit4/BasicTest.java +++ b/surefire-its/src/test/resources/junit4/src/test/java/junit4/BasicTest.java @@ -1,24 +1,5 @@ package junit4; -/* - * 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.junit.After; import org.junit.AfterClass; import org.junit.Assert; diff --git a/surefire-its/src/test/resources/junit44-dep/src/test/java/junit44Dep/BasicTest.java b/surefire-its/src/test/resources/junit44-dep/src/test/java/junit44Dep/BasicTest.java index 219b8dafc4..1e4ccb74da 100644 --- a/surefire-its/src/test/resources/junit44-dep/src/test/java/junit44Dep/BasicTest.java +++ b/surefire-its/src/test/resources/junit44-dep/src/test/java/junit44Dep/BasicTest.java @@ -1,24 +1,5 @@ package junit44Dep; -/* - * 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.hamcrest.core.Is; import org.junit.After; import org.junit.AfterClass; diff --git a/surefire-its/src/test/resources/junit44-environment/src/test/java/junit44/environment/BasicTest.java b/surefire-its/src/test/resources/junit44-environment/src/test/java/junit44/environment/BasicTest.java index ee20aa681b..7cea25d622 100644 --- a/surefire-its/src/test/resources/junit44-environment/src/test/java/junit44/environment/BasicTest.java +++ b/surefire-its/src/test/resources/junit44-environment/src/test/java/junit44/environment/BasicTest.java @@ -1,24 +1,5 @@ package junit44.environment; -/* - * 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 static org.hamcrest.core.Is.*; import static org.hamcrest.core.IsNull.*; import org.junit.Assert; diff --git a/surefire-its/src/test/resources/junit44-hamcrest/src/test/java/junit44/hamcrest/BasicTest.java b/surefire-its/src/test/resources/junit44-hamcrest/src/test/java/junit44/hamcrest/BasicTest.java index b84767567f..f7c590007b 100644 --- a/surefire-its/src/test/resources/junit44-hamcrest/src/test/java/junit44/hamcrest/BasicTest.java +++ b/surefire-its/src/test/resources/junit44-hamcrest/src/test/java/junit44/hamcrest/BasicTest.java @@ -1,24 +1,5 @@ package junit44.hamcrest; -/* - * 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.hamcrest.core.Is; import org.junit.After; import org.junit.AfterClass; diff --git a/surefire-its/src/test/resources/junit44-method-pattern/src/test/java/junit4/BasicTest.java b/surefire-its/src/test/resources/junit44-method-pattern/src/test/java/junit4/BasicTest.java index 925d9b5749..73f3fb40e8 100644 --- a/surefire-its/src/test/resources/junit44-method-pattern/src/test/java/junit4/BasicTest.java +++ b/surefire-its/src/test/resources/junit44-method-pattern/src/test/java/junit4/BasicTest.java @@ -1,24 +1,5 @@ package junit4; -/* - * 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.junit.After; import org.junit.AfterClass; import org.junit.Assert; diff --git a/surefire-its/src/test/resources/junit44-multiple-methods/src/test/java/junit4/BasicTest.java b/surefire-its/src/test/resources/junit44-multiple-methods/src/test/java/junit4/BasicTest.java index 4b31b9e5b7..7627eee955 100644 --- a/surefire-its/src/test/resources/junit44-multiple-methods/src/test/java/junit4/BasicTest.java +++ b/surefire-its/src/test/resources/junit44-multiple-methods/src/test/java/junit4/BasicTest.java @@ -1,24 +1,5 @@ package junit4; -/* - * 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.junit.After; import org.junit.AfterClass; import org.junit.Assert; diff --git a/surefire-its/src/test/resources/junit44-multiple-methods/src/test/java/junit4/TestThree.java b/surefire-its/src/test/resources/junit44-multiple-methods/src/test/java/junit4/TestThree.java index 16bc283b1d..e4b6f2b324 100644 --- a/surefire-its/src/test/resources/junit44-multiple-methods/src/test/java/junit4/TestThree.java +++ b/surefire-its/src/test/resources/junit44-multiple-methods/src/test/java/junit4/TestThree.java @@ -1,24 +1,5 @@ package junit4; -/* - * 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.junit.After; import org.junit.AfterClass; import org.junit.Assert; diff --git a/surefire-its/src/test/resources/junit44-multiple-methods/src/test/java/junit4/TestTwo.java b/surefire-its/src/test/resources/junit44-multiple-methods/src/test/java/junit4/TestTwo.java index 620cf23d00..d0d749b68c 100644 --- a/surefire-its/src/test/resources/junit44-multiple-methods/src/test/java/junit4/TestTwo.java +++ b/surefire-its/src/test/resources/junit44-multiple-methods/src/test/java/junit4/TestTwo.java @@ -1,24 +1,5 @@ package junit4; -/* - * 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.junit.After; import org.junit.AfterClass; import org.junit.Assert; diff --git a/surefire-its/src/test/resources/junit44-single-method/src/test/java/junit4/BasicTest.java b/surefire-its/src/test/resources/junit44-single-method/src/test/java/junit4/BasicTest.java index 027917d928..1f14889ed8 100644 --- a/surefire-its/src/test/resources/junit44-single-method/src/test/java/junit4/BasicTest.java +++ b/surefire-its/src/test/resources/junit44-single-method/src/test/java/junit4/BasicTest.java @@ -1,24 +1,5 @@ package junit4; -/* - * 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.junit.After; import org.junit.AfterClass; import org.junit.Assert; diff --git a/surefire-its/src/test/resources/junit47-concurrency/src/test/java/junit47/BasicTest.java b/surefire-its/src/test/resources/junit47-concurrency/src/test/java/junit47/BasicTest.java index 1f110605d1..dbcb2f02d2 100644 --- a/surefire-its/src/test/resources/junit47-concurrency/src/test/java/junit47/BasicTest.java +++ b/surefire-its/src/test/resources/junit47-concurrency/src/test/java/junit47/BasicTest.java @@ -1,24 +1,5 @@ package concurrentjunit47.src.test.java.junit47; -/* - * 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.junit.*; import java.util.concurrent.TimeUnit; @@ -68,4 +49,4 @@ public static void oneTimeTearDown() } -} \ No newline at end of file +} diff --git a/surefire-its/src/test/resources/junit47-parallel-nts/src/test/java/surefireparallelnts/ParallelTest.java b/surefire-its/src/test/resources/junit47-parallel-nts/src/test/java/surefireparallelnts/ParallelTest.java index b59c51b9a8..f166d959db 100644 --- a/surefire-its/src/test/resources/junit47-parallel-nts/src/test/java/surefireparallelnts/ParallelTest.java +++ b/surefire-its/src/test/resources/junit47-parallel-nts/src/test/java/surefireparallelnts/ParallelTest.java @@ -1,24 +1,5 @@ package surefireparallelnts; -/* - * 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.junit.Test; /** @@ -34,4 +15,4 @@ public void test() String name = Thread.currentThread().getName(); System.out.println( "maven-surefire-plugin@NotThreadSafe".equals( name ) ? "wrong-thread" : "expected-thread" ); } -} \ No newline at end of file +} diff --git a/surefire-its/src/test/resources/junit47-parallel-nts/src/test/java/surefireparallelnts/RunningInSequenceTest.java b/surefire-its/src/test/resources/junit47-parallel-nts/src/test/java/surefireparallelnts/RunningInSequenceTest.java index 7ec56edf67..0ab31382e3 100644 --- a/surefire-its/src/test/resources/junit47-parallel-nts/src/test/java/surefireparallelnts/RunningInSequenceTest.java +++ b/surefire-its/src/test/resources/junit47-parallel-nts/src/test/java/surefireparallelnts/RunningInSequenceTest.java @@ -1,24 +1,5 @@ package surefireparallelnts; -/* - * 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.junit.Test; /** @@ -34,4 +15,4 @@ public void test() { System.out.println( "xxx-" + Thread.currentThread().getName() ); } -} \ No newline at end of file +} diff --git a/surefire-its/src/test/resources/junit47-parallel-with-suite/src/test/java/surefire747/SuiteTest1.java b/surefire-its/src/test/resources/junit47-parallel-with-suite/src/test/java/surefire747/SuiteTest1.java index 9ac0b90378..a277cd9558 100644 --- a/surefire-its/src/test/resources/junit47-parallel-with-suite/src/test/java/surefire747/SuiteTest1.java +++ b/surefire-its/src/test/resources/junit47-parallel-with-suite/src/test/java/surefire747/SuiteTest1.java @@ -1,24 +1,5 @@ package surefire747; -/* - * 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.junit.After; import org.junit.AfterClass; import org.junit.Before; diff --git a/surefire-its/src/test/resources/junit47-parallel-with-suite/src/test/java/surefire747/SuiteTest2.java b/surefire-its/src/test/resources/junit47-parallel-with-suite/src/test/java/surefire747/SuiteTest2.java index 99ad7cdd8b..53f05df2fe 100644 --- a/surefire-its/src/test/resources/junit47-parallel-with-suite/src/test/java/surefire747/SuiteTest2.java +++ b/surefire-its/src/test/resources/junit47-parallel-with-suite/src/test/java/surefire747/SuiteTest2.java @@ -1,24 +1,5 @@ package surefire747; -/* - * 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.junit.After; import org.junit.AfterClass; import org.junit.Before; diff --git a/surefire-its/src/test/resources/junit47-parallel-with-suite/src/test/java/surefire747/TestSuite.java b/surefire-its/src/test/resources/junit47-parallel-with-suite/src/test/java/surefire747/TestSuite.java index 4e9548196f..499ab1b504 100644 --- a/surefire-its/src/test/resources/junit47-parallel-with-suite/src/test/java/surefire747/TestSuite.java +++ b/surefire-its/src/test/resources/junit47-parallel-with-suite/src/test/java/surefire747/TestSuite.java @@ -1,24 +1,5 @@ package surefire747; -/* - * 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.junit.AfterClass; import org.junit.BeforeClass; import org.junit.runner.RunWith; diff --git a/surefire-its/src/test/resources/junit47-parallel/src/test/java/surefireparallel/Suite1Test.java b/surefire-its/src/test/resources/junit47-parallel/src/test/java/surefireparallel/Suite1Test.java index 99419fe04a..36b99808fd 100644 --- a/surefire-its/src/test/resources/junit47-parallel/src/test/java/surefireparallel/Suite1Test.java +++ b/surefire-its/src/test/resources/junit47-parallel/src/test/java/surefireparallel/Suite1Test.java @@ -1,24 +1,5 @@ package surefireparallel; -/* - * 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.junit.runner.RunWith; import org.junit.runners.Suite; diff --git a/surefire-its/src/test/resources/junit47-parallel/src/test/java/surefireparallel/Suite2Test.java b/surefire-its/src/test/resources/junit47-parallel/src/test/java/surefireparallel/Suite2Test.java index 32814ff724..e3a4aa2307 100644 --- a/surefire-its/src/test/resources/junit47-parallel/src/test/java/surefireparallel/Suite2Test.java +++ b/surefire-its/src/test/resources/junit47-parallel/src/test/java/surefireparallel/Suite2Test.java @@ -1,24 +1,5 @@ package surefireparallel; -/* - * 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.junit.runner.RunWith; import org.junit.runners.Suite; diff --git a/surefire-its/src/test/resources/junit47-parallel/src/test/java/surefireparallel/TestClass.java b/surefire-its/src/test/resources/junit47-parallel/src/test/java/surefireparallel/TestClass.java index 36484437f0..bc7cfd2b43 100644 --- a/surefire-its/src/test/resources/junit47-parallel/src/test/java/surefireparallel/TestClass.java +++ b/surefire-its/src/test/resources/junit47-parallel/src/test/java/surefireparallel/TestClass.java @@ -1,24 +1,5 @@ package surefireparallel; -/* - * 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.junit.Test; /** @@ -47,4 +28,4 @@ public void c() { Thread.sleep( 5000L ); } -} \ No newline at end of file +} diff --git a/surefire-its/src/test/resources/junit47-parallel/src/test/java/surefireparallel/Waiting1Test.java b/surefire-its/src/test/resources/junit47-parallel/src/test/java/surefireparallel/Waiting1Test.java index 1d58841281..30644f9052 100644 --- a/surefire-its/src/test/resources/junit47-parallel/src/test/java/surefireparallel/Waiting1Test.java +++ b/surefire-its/src/test/resources/junit47-parallel/src/test/java/surefireparallel/Waiting1Test.java @@ -1,24 +1,5 @@ package surefireparallel; -/* - * 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.junit.Test; /** @@ -47,4 +28,4 @@ public void c() { Thread.sleep( 300L ); } -} \ No newline at end of file +} diff --git a/surefire-its/src/test/resources/junit47-parallel/src/test/java/surefireparallel/Waiting2Test.java b/surefire-its/src/test/resources/junit47-parallel/src/test/java/surefireparallel/Waiting2Test.java index 55da77266d..b5b9ab4a97 100644 --- a/surefire-its/src/test/resources/junit47-parallel/src/test/java/surefireparallel/Waiting2Test.java +++ b/surefire-its/src/test/resources/junit47-parallel/src/test/java/surefireparallel/Waiting2Test.java @@ -1,24 +1,5 @@ package surefireparallel; -/* - * 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.junit.Test; /** @@ -47,4 +28,4 @@ public void c() { Thread.sleep( 300L ); } -} \ No newline at end of file +} diff --git a/surefire-its/src/test/resources/junit47-parallel/src/test/java/surefireparallel/Waiting3Test.java b/surefire-its/src/test/resources/junit47-parallel/src/test/java/surefireparallel/Waiting3Test.java index 5098fd452b..fe91c1b31a 100644 --- a/surefire-its/src/test/resources/junit47-parallel/src/test/java/surefireparallel/Waiting3Test.java +++ b/surefire-its/src/test/resources/junit47-parallel/src/test/java/surefireparallel/Waiting3Test.java @@ -1,24 +1,5 @@ package surefireparallel; -/* - * 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.junit.Test; /** @@ -47,4 +28,4 @@ public void c() { Thread.sleep( 300L ); } -} \ No newline at end of file +} diff --git a/surefire-its/src/test/resources/junit47-parallel/src/test/java/surefireparallel/Waiting4Test.java b/surefire-its/src/test/resources/junit47-parallel/src/test/java/surefireparallel/Waiting4Test.java index 8418448636..558ef724d8 100644 --- a/surefire-its/src/test/resources/junit47-parallel/src/test/java/surefireparallel/Waiting4Test.java +++ b/surefire-its/src/test/resources/junit47-parallel/src/test/java/surefireparallel/Waiting4Test.java @@ -1,24 +1,5 @@ package surefireparallel; -/* - * 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.junit.Test; /** @@ -47,4 +28,4 @@ public void c() { Thread.sleep( 300L ); } -} \ No newline at end of file +} diff --git a/surefire-its/src/test/resources/junit47-parallel/src/test/java/surefireparallel/Waiting5Test.java b/surefire-its/src/test/resources/junit47-parallel/src/test/java/surefireparallel/Waiting5Test.java index 2b9916061b..1624d61a6e 100644 --- a/surefire-its/src/test/resources/junit47-parallel/src/test/java/surefireparallel/Waiting5Test.java +++ b/surefire-its/src/test/resources/junit47-parallel/src/test/java/surefireparallel/Waiting5Test.java @@ -1,24 +1,5 @@ package surefireparallel; -/* - * 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.junit.Test; /** @@ -47,4 +28,4 @@ public void c() { Thread.sleep( 300L ); } -} \ No newline at end of file +} diff --git a/surefire-its/src/test/resources/junit47-parallel/src/test/java/surefireparallel/Waiting6Test.java b/surefire-its/src/test/resources/junit47-parallel/src/test/java/surefireparallel/Waiting6Test.java index 9ae9c012aa..299c8bc09b 100644 --- a/surefire-its/src/test/resources/junit47-parallel/src/test/java/surefireparallel/Waiting6Test.java +++ b/surefire-its/src/test/resources/junit47-parallel/src/test/java/surefireparallel/Waiting6Test.java @@ -1,24 +1,5 @@ package surefireparallel; -/* - * 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.junit.Test; /** @@ -47,4 +28,4 @@ public void c() { Thread.sleep( 300L ); } -} \ No newline at end of file +} diff --git a/surefire-its/src/test/resources/junit47-parallel/src/test/java/surefireparallel/Waiting7Test.java b/surefire-its/src/test/resources/junit47-parallel/src/test/java/surefireparallel/Waiting7Test.java index ca00a6af86..7e78a62fdc 100644 --- a/surefire-its/src/test/resources/junit47-parallel/src/test/java/surefireparallel/Waiting7Test.java +++ b/surefire-its/src/test/resources/junit47-parallel/src/test/java/surefireparallel/Waiting7Test.java @@ -1,24 +1,5 @@ package surefireparallel; -/* - * 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.junit.Test; /** @@ -47,4 +28,4 @@ public void c() { Thread.sleep( 300L ); } -} \ No newline at end of file +} diff --git a/surefire-its/src/test/resources/junit47-parallel/src/test/java/surefireparallel/Waiting8Test.java b/surefire-its/src/test/resources/junit47-parallel/src/test/java/surefireparallel/Waiting8Test.java index 96d1c668b3..88f69c2a67 100644 --- a/surefire-its/src/test/resources/junit47-parallel/src/test/java/surefireparallel/Waiting8Test.java +++ b/surefire-its/src/test/resources/junit47-parallel/src/test/java/surefireparallel/Waiting8Test.java @@ -1,24 +1,5 @@ package surefireparallel; -/* - * 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.junit.Test; /** @@ -47,4 +28,4 @@ public void c() { Thread.sleep( 300L ); } -} \ No newline at end of file +} diff --git a/surefire-its/src/test/resources/junit47-redirect-output/src/test/java/junit47ConsoleOutput/Test0.java b/surefire-its/src/test/resources/junit47-redirect-output/src/test/java/junit47ConsoleOutput/Test0.java index 102faaa5b7..66d1022b6c 100644 --- a/surefire-its/src/test/resources/junit47-redirect-output/src/test/java/junit47ConsoleOutput/Test0.java +++ b/surefire-its/src/test/resources/junit47-redirect-output/src/test/java/junit47ConsoleOutput/Test0.java @@ -1,24 +1,5 @@ package junit47ConsoleOutput; -/* - * 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.junit.After; import org.junit.AfterClass; import org.junit.Before; @@ -60,4 +41,4 @@ public void setUp() throws Exception { public void tearDown() throws Exception { System.out.println("tearDown"); } -} \ No newline at end of file +} diff --git a/surefire-its/src/test/resources/junit47-redirect-output/src/test/java/junit47ConsoleOutput/Test1.java b/surefire-its/src/test/resources/junit47-redirect-output/src/test/java/junit47ConsoleOutput/Test1.java index 40e084eaed..ed8ba2aa43 100644 --- a/surefire-its/src/test/resources/junit47-redirect-output/src/test/java/junit47ConsoleOutput/Test1.java +++ b/surefire-its/src/test/resources/junit47-redirect-output/src/test/java/junit47ConsoleOutput/Test1.java @@ -1,24 +1,5 @@ package junit47ConsoleOutput; -/* - * 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.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; diff --git a/surefire-its/src/test/resources/junit47-redirect-output/src/test/java/junit47ConsoleOutput/Test2.java b/surefire-its/src/test/resources/junit47-redirect-output/src/test/java/junit47ConsoleOutput/Test2.java index 1a14fc7252..27d07c8ad4 100644 --- a/surefire-its/src/test/resources/junit47-redirect-output/src/test/java/junit47ConsoleOutput/Test2.java +++ b/surefire-its/src/test/resources/junit47-redirect-output/src/test/java/junit47ConsoleOutput/Test2.java @@ -1,24 +1,5 @@ package junit47ConsoleOutput; -/* - * 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.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; diff --git a/surefire-its/src/test/resources/junit47-redirect-output/src/test/java/junit47ConsoleOutput/Test3.java b/surefire-its/src/test/resources/junit47-redirect-output/src/test/java/junit47ConsoleOutput/Test3.java index 35b0032c24..3753f5cc5d 100644 --- a/surefire-its/src/test/resources/junit47-redirect-output/src/test/java/junit47ConsoleOutput/Test3.java +++ b/surefire-its/src/test/resources/junit47-redirect-output/src/test/java/junit47ConsoleOutput/Test3.java @@ -1,24 +1,5 @@ package junit47ConsoleOutput; -/* - * 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.junit.Test; public class Test3 diff --git a/surefire-its/src/test/resources/junit47-static-inner-class-tests/src/test/java/junit4/BasicTest.java b/surefire-its/src/test/resources/junit47-static-inner-class-tests/src/test/java/junit4/BasicTest.java index f11de6d8a8..4085990eb2 100644 --- a/surefire-its/src/test/resources/junit47-static-inner-class-tests/src/test/java/junit4/BasicTest.java +++ b/surefire-its/src/test/resources/junit47-static-inner-class-tests/src/test/java/junit4/BasicTest.java @@ -1,24 +1,5 @@ package junit4; -/* - * 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.junit.Test; import org.junit.experimental.runners.Enclosed; import org.junit.runner.RunWith; diff --git a/surefire-its/src/test/resources/junit47-static-inner-class-tests/src/test/java/junit4/TopLevelAbstractClassTest.java b/surefire-its/src/test/resources/junit47-static-inner-class-tests/src/test/java/junit4/TopLevelAbstractClassTest.java index b47e755b1d..afb286a75b 100644 --- a/surefire-its/src/test/resources/junit47-static-inner-class-tests/src/test/java/junit4/TopLevelAbstractClassTest.java +++ b/surefire-its/src/test/resources/junit47-static-inner-class-tests/src/test/java/junit4/TopLevelAbstractClassTest.java @@ -1,24 +1,5 @@ package junit4; -/* - * 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.junit.Test; import org.junit.experimental.runners.Enclosed; import org.junit.runner.RunWith; diff --git a/surefire-its/src/test/resources/junit47-static-inner-class-tests/src/test/java/junit4/TopLevelInterfaceTest.java b/surefire-its/src/test/resources/junit47-static-inner-class-tests/src/test/java/junit4/TopLevelInterfaceTest.java index eaa67569d3..6dd75730af 100644 --- a/surefire-its/src/test/resources/junit47-static-inner-class-tests/src/test/java/junit4/TopLevelInterfaceTest.java +++ b/surefire-its/src/test/resources/junit47-static-inner-class-tests/src/test/java/junit4/TopLevelInterfaceTest.java @@ -1,24 +1,5 @@ package junit4; -/* - * 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.junit.Test; import org.junit.experimental.runners.Enclosed; import org.junit.runner.RunWith; diff --git a/surefire-its/src/test/resources/junit48-categories/src/test/java/junit4/BasicTest.java b/surefire-its/src/test/resources/junit48-categories/src/test/java/junit4/BasicTest.java index 3108e1a65d..0106717abe 100644 --- a/surefire-its/src/test/resources/junit48-categories/src/test/java/junit4/BasicTest.java +++ b/surefire-its/src/test/resources/junit48-categories/src/test/java/junit4/BasicTest.java @@ -1,23 +1,4 @@ package junit4; -/* - * 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.junit.AfterClass; import org.junit.Test; import org.junit.experimental.categories.Category; diff --git a/surefire-its/src/test/resources/junit48-categories/src/test/java/junit4/CategoryCTest.java b/surefire-its/src/test/resources/junit48-categories/src/test/java/junit4/CategoryCTest.java index af88bc8ae0..6081374eca 100644 --- a/surefire-its/src/test/resources/junit48-categories/src/test/java/junit4/CategoryCTest.java +++ b/surefire-its/src/test/resources/junit48-categories/src/test/java/junit4/CategoryCTest.java @@ -1,23 +1,4 @@ package junit4; -/* - * 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.junit.AfterClass; import org.junit.Test; import org.junit.experimental.categories.Category; diff --git a/surefire-its/src/test/resources/junit48-categories/src/test/java/junit4/NoCategoryTest.java b/surefire-its/src/test/resources/junit48-categories/src/test/java/junit4/NoCategoryTest.java index f08f40f195..8cb62d1107 100644 --- a/surefire-its/src/test/resources/junit48-categories/src/test/java/junit4/NoCategoryTest.java +++ b/surefire-its/src/test/resources/junit48-categories/src/test/java/junit4/NoCategoryTest.java @@ -1,23 +1,4 @@ package junit4; -/* - * 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.junit.AfterClass; import org.junit.Test; diff --git a/surefire-its/src/test/resources/junit48-method-pattern/src/test/java/junit4/BasicTest.java b/surefire-its/src/test/resources/junit48-method-pattern/src/test/java/junit4/BasicTest.java index 218488ccaa..5d842a8b27 100644 --- a/surefire-its/src/test/resources/junit48-method-pattern/src/test/java/junit4/BasicTest.java +++ b/surefire-its/src/test/resources/junit48-method-pattern/src/test/java/junit4/BasicTest.java @@ -1,24 +1,5 @@ package junit4; -/* - * 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.junit.After; import org.junit.AfterClass; import org.junit.Assert; diff --git a/surefire-its/src/test/resources/junit48-multiple-method-patterns/src/test/java/jiras/surefire745/BasicTest.java b/surefire-its/src/test/resources/junit48-multiple-method-patterns/src/test/java/jiras/surefire745/BasicTest.java index 44d5978776..430820311e 100644 --- a/surefire-its/src/test/resources/junit48-multiple-method-patterns/src/test/java/jiras/surefire745/BasicTest.java +++ b/surefire-its/src/test/resources/junit48-multiple-method-patterns/src/test/java/jiras/surefire745/BasicTest.java @@ -1,25 +1,6 @@ package jiras.surefire745; -/* - * 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.junit.Rule; import org.junit.Test; import org.junit.rules.TestName; diff --git a/surefire-its/src/test/resources/junit48-multiple-method-patterns/src/test/java/jiras/surefire745/TestFive.java b/surefire-its/src/test/resources/junit48-multiple-method-patterns/src/test/java/jiras/surefire745/TestFive.java index 7d88f705a8..ef3d5ebeaa 100644 --- a/surefire-its/src/test/resources/junit48-multiple-method-patterns/src/test/java/jiras/surefire745/TestFive.java +++ b/surefire-its/src/test/resources/junit48-multiple-method-patterns/src/test/java/jiras/surefire745/TestFive.java @@ -1,24 +1,5 @@ package jiras.surefire745; -/* - * 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.junit.Rule; import org.junit.Test; import org.junit.rules.TestName; diff --git a/surefire-its/src/test/resources/junit48-multiple-method-patterns/src/test/java/jiras/surefire745/TestFour.java b/surefire-its/src/test/resources/junit48-multiple-method-patterns/src/test/java/jiras/surefire745/TestFour.java index 824b0d53e8..8d7b230eca 100644 --- a/surefire-its/src/test/resources/junit48-multiple-method-patterns/src/test/java/jiras/surefire745/TestFour.java +++ b/surefire-its/src/test/resources/junit48-multiple-method-patterns/src/test/java/jiras/surefire745/TestFour.java @@ -1,24 +1,5 @@ package jiras.surefire745; -/* - * 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.junit.Rule; import org.junit.Test; import org.junit.rules.TestName; diff --git a/surefire-its/src/test/resources/junit48-multiple-method-patterns/src/test/java/jiras/surefire745/TestThree.java b/surefire-its/src/test/resources/junit48-multiple-method-patterns/src/test/java/jiras/surefire745/TestThree.java index a868e7c3df..593777c628 100644 --- a/surefire-its/src/test/resources/junit48-multiple-method-patterns/src/test/java/jiras/surefire745/TestThree.java +++ b/surefire-its/src/test/resources/junit48-multiple-method-patterns/src/test/java/jiras/surefire745/TestThree.java @@ -1,24 +1,5 @@ package jiras.surefire745; -/* - * 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.junit.Rule; import org.junit.Test; import org.junit.rules.TestName; diff --git a/surefire-its/src/test/resources/junit48-multiple-method-patterns/src/test/java/jiras/surefire745/TestTwo.java b/surefire-its/src/test/resources/junit48-multiple-method-patterns/src/test/java/jiras/surefire745/TestTwo.java index 5f1182d507..7bf4de7932 100644 --- a/surefire-its/src/test/resources/junit48-multiple-method-patterns/src/test/java/jiras/surefire745/TestTwo.java +++ b/surefire-its/src/test/resources/junit48-multiple-method-patterns/src/test/java/jiras/surefire745/TestTwo.java @@ -1,24 +1,5 @@ package jiras.surefire745; -/* - * 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.junit.Rule; import org.junit.Test; import org.junit.rules.TestName; diff --git a/surefire-its/src/test/resources/junit48-multiple-methods/src/test/java/junit4/TestThree.java b/surefire-its/src/test/resources/junit48-multiple-methods/src/test/java/junit4/TestThree.java index 16bc283b1d..e4b6f2b324 100644 --- a/surefire-its/src/test/resources/junit48-multiple-methods/src/test/java/junit4/TestThree.java +++ b/surefire-its/src/test/resources/junit48-multiple-methods/src/test/java/junit4/TestThree.java @@ -1,24 +1,5 @@ package junit4; -/* - * 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.junit.After; import org.junit.AfterClass; import org.junit.Assert; diff --git a/surefire-its/src/test/resources/junit5-modulepath/src/main/java/com/app/Main.java b/surefire-its/src/test/resources/junit5-modulepath/src/main/java/com/app/Main.java index 51e145bbb8..4873f6ad04 100644 --- a/surefire-its/src/test/resources/junit5-modulepath/src/main/java/com/app/Main.java +++ b/surefire-its/src/test/resources/junit5-modulepath/src/main/java/com/app/Main.java @@ -1,24 +1,5 @@ package com.app; -/* - * 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.joda.time.DateTime; public class Main diff --git a/surefire-its/src/test/resources/junit5-modulepath/src/test/java/com/app/AppTest.java b/surefire-its/src/test/resources/junit5-modulepath/src/test/java/com/app/AppTest.java index 8f2d3f537f..9b93fb9636 100644 --- a/surefire-its/src/test/resources/junit5-modulepath/src/test/java/com/app/AppTest.java +++ b/surefire-its/src/test/resources/junit5-modulepath/src/test/java/com/app/AppTest.java @@ -1,24 +1,5 @@ package com.app; -/* - * 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.junit.jupiter.api.Test; public class AppTest diff --git a/surefire-its/src/test/resources/junit5-suite/src/test/java/pkg/JUnit5Tests.java b/surefire-its/src/test/resources/junit5-suite/src/test/java/pkg/JUnit5Tests.java index a9cb8d63f6..801b0668bf 100644 --- a/surefire-its/src/test/resources/junit5-suite/src/test/java/pkg/JUnit5Tests.java +++ b/surefire-its/src/test/resources/junit5-suite/src/test/java/pkg/JUnit5Tests.java @@ -1,24 +1,5 @@ package pkg; -/* - * 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.junit.platform.suite.api.SelectClasses; import org.junit.platform.suite.api.Suite; diff --git a/surefire-its/src/test/resources/junit5-suite/src/test/java/pkg/domain/AxTest.java b/surefire-its/src/test/resources/junit5-suite/src/test/java/pkg/domain/AxTest.java index ca7c26c807..50e0b6c5d8 100644 --- a/surefire-its/src/test/resources/junit5-suite/src/test/java/pkg/domain/AxTest.java +++ b/surefire-its/src/test/resources/junit5-suite/src/test/java/pkg/domain/AxTest.java @@ -1,24 +1,5 @@ package pkg.domain; -/* - * 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.junit.jupiter.api.Test; public class AxTest diff --git a/surefire-its/src/test/resources/junit5-suite/src/test/java/pkg/domain/BxTest.java b/surefire-its/src/test/resources/junit5-suite/src/test/java/pkg/domain/BxTest.java index 767ec07d6d..09b16cdfbe 100644 --- a/surefire-its/src/test/resources/junit5-suite/src/test/java/pkg/domain/BxTest.java +++ b/surefire-its/src/test/resources/junit5-suite/src/test/java/pkg/domain/BxTest.java @@ -1,24 +1,5 @@ package pkg.domain; -/* - * 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.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.fail; diff --git a/surefire-its/src/test/resources/large-test-results/src/test/java/largeTestResults/BasicTest.java b/surefire-its/src/test/resources/large-test-results/src/test/java/largeTestResults/BasicTest.java index bdeeb04976..f2af9bbb8b 100644 --- a/surefire-its/src/test/resources/large-test-results/src/test/java/largeTestResults/BasicTest.java +++ b/surefire-its/src/test/resources/large-test-results/src/test/java/largeTestResults/BasicTest.java @@ -1,24 +1,5 @@ package largeTestResults; -/* - * 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 junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; diff --git a/surefire-its/src/test/resources/long-windows-path/src/test/java/longwindowspath/BasicTest.java b/surefire-its/src/test/resources/long-windows-path/src/test/java/longwindowspath/BasicTest.java index bd9cf36d40..ef80a0f62d 100644 --- a/surefire-its/src/test/resources/long-windows-path/src/test/java/longwindowspath/BasicTest.java +++ b/surefire-its/src/test/resources/long-windows-path/src/test/java/longwindowspath/BasicTest.java @@ -1,24 +1,5 @@ package longwindowspath; -/* - * 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.junit.Test; public class BasicTest diff --git a/surefire-its/src/test/resources/maven-multimodule-project-with-jpms/com.foo.impl/src/main/java/com/foo/impl/Bar.java b/surefire-its/src/test/resources/maven-multimodule-project-with-jpms/com.foo.impl/src/main/java/com/foo/impl/Bar.java index 50009e3bdc..0d7e25213c 100644 --- a/surefire-its/src/test/resources/maven-multimodule-project-with-jpms/com.foo.impl/src/main/java/com/foo/impl/Bar.java +++ b/surefire-its/src/test/resources/maven-multimodule-project-with-jpms/com.foo.impl/src/main/java/com/foo/impl/Bar.java @@ -1,24 +1,5 @@ package com.foo.impl; -/* - * 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 com.foo.api.SomeInterface; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/surefire-its/src/test/resources/maven-multimodule-project-with-jpms/com.foo.impl/src/test/java/com/foo/implt/BarIT.java b/surefire-its/src/test/resources/maven-multimodule-project-with-jpms/com.foo.impl/src/test/java/com/foo/implt/BarIT.java index acb4c7f273..7b1ce6dc34 100644 --- a/surefire-its/src/test/resources/maven-multimodule-project-with-jpms/com.foo.impl/src/test/java/com/foo/implt/BarIT.java +++ b/surefire-its/src/test/resources/maven-multimodule-project-with-jpms/com.foo.impl/src/test/java/com/foo/implt/BarIT.java @@ -1,24 +1,5 @@ package com.foo.implt; -/* - * 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 com.foo.impl.Bar; import org.junit.jupiter.api.Test; diff --git a/surefire-its/src/test/resources/maven-multimodule-project-with-jpms/com.foo.impl/src/test/java/com/foo/implt/BarTest.java b/surefire-its/src/test/resources/maven-multimodule-project-with-jpms/com.foo.impl/src/test/java/com/foo/implt/BarTest.java index f63919874f..249966a482 100644 --- a/surefire-its/src/test/resources/maven-multimodule-project-with-jpms/com.foo.impl/src/test/java/com/foo/implt/BarTest.java +++ b/surefire-its/src/test/resources/maven-multimodule-project-with-jpms/com.foo.impl/src/test/java/com/foo/implt/BarTest.java @@ -1,24 +1,5 @@ package com.foo.implt; -/* - * 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 com.foo.impl.Bar; import org.junit.jupiter.api.Test; diff --git a/surefire-its/src/test/resources/modulepath/src/main/java/com/app/Main.java b/surefire-its/src/test/resources/modulepath/src/main/java/com/app/Main.java index 6a44492657..dc36bbc604 100644 --- a/surefire-its/src/test/resources/modulepath/src/main/java/com/app/Main.java +++ b/surefire-its/src/test/resources/modulepath/src/main/java/com/app/Main.java @@ -1,24 +1,5 @@ package com.app; -/* - * 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.joda.time.DateTime; public class Main diff --git a/surefire-its/src/test/resources/modulepath/src/test/java/com/app/AppTest.java b/surefire-its/src/test/resources/modulepath/src/test/java/com/app/AppTest.java index aa836a4157..f42b97cbf1 100644 --- a/surefire-its/src/test/resources/modulepath/src/test/java/com/app/AppTest.java +++ b/surefire-its/src/test/resources/modulepath/src/test/java/com/app/AppTest.java @@ -1,24 +1,5 @@ package com.app; -/* - * 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.testng.annotations.Test; @Test diff --git a/surefire-its/src/test/resources/norunnableTests/src/test/java/junit/norunnabletests/BasicTest.java b/surefire-its/src/test/resources/norunnableTests/src/test/java/junit/norunnabletests/BasicTest.java index 30acd3eb09..b269d5d461 100644 --- a/surefire-its/src/test/resources/norunnableTests/src/test/java/junit/norunnabletests/BasicTest.java +++ b/surefire-its/src/test/resources/norunnableTests/src/test/java/junit/norunnabletests/BasicTest.java @@ -1,25 +1,6 @@ package junit.norunnabletests; -/* - * 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 junit.framework.TestCase; diff --git a/surefire-its/src/test/resources/parallel-runtime/src/test/java/runorder/parallel/Test1.java b/surefire-its/src/test/resources/parallel-runtime/src/test/java/runorder/parallel/Test1.java index 3b6abf3368..9de2c619a2 100755 --- a/surefire-its/src/test/resources/parallel-runtime/src/test/java/runorder/parallel/Test1.java +++ b/surefire-its/src/test/resources/parallel-runtime/src/test/java/runorder/parallel/Test1.java @@ -1,23 +1,4 @@ package runorder.parallel; -/* - * 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.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; @@ -66,4 +47,4 @@ public void testSleep4() { Test1.sleep( ms ); } -} \ No newline at end of file +} diff --git a/surefire-its/src/test/resources/parallel-runtime/src/test/java/runorder/parallel/Test2.java b/surefire-its/src/test/resources/parallel-runtime/src/test/java/runorder/parallel/Test2.java index f72c49973c..7d80983c0c 100644 --- a/surefire-its/src/test/resources/parallel-runtime/src/test/java/runorder/parallel/Test2.java +++ b/surefire-its/src/test/resources/parallel-runtime/src/test/java/runorder/parallel/Test2.java @@ -1,24 +1,5 @@ package runorder.parallel; -/* - * 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.junit.Test; /** @@ -51,4 +32,4 @@ public void testSleep4() Test1.sleep( Test1.ms ); } -} \ No newline at end of file +} diff --git a/surefire-its/src/test/resources/parallel-runtime/src/test/java/runorder/parallel/Test3.java b/surefire-its/src/test/resources/parallel-runtime/src/test/java/runorder/parallel/Test3.java index 3557667eb5..489f48223d 100644 --- a/surefire-its/src/test/resources/parallel-runtime/src/test/java/runorder/parallel/Test3.java +++ b/surefire-its/src/test/resources/parallel-runtime/src/test/java/runorder/parallel/Test3.java @@ -1,24 +1,5 @@ package runorder.parallel; -/* - * 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.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; @@ -52,4 +33,4 @@ public void testSleep4() Test1.sleep( Test1.ms ); } -} \ No newline at end of file +} diff --git a/surefire-its/src/test/resources/plain-old-java-classpath/src/test/java/plainOldJavaClasspath/BasicTest.java b/surefire-its/src/test/resources/plain-old-java-classpath/src/test/java/plainOldJavaClasspath/BasicTest.java index e458631782..e9097dd090 100644 --- a/surefire-its/src/test/resources/plain-old-java-classpath/src/test/java/plainOldJavaClasspath/BasicTest.java +++ b/surefire-its/src/test/resources/plain-old-java-classpath/src/test/java/plainOldJavaClasspath/BasicTest.java @@ -1,24 +1,5 @@ package plainOldJavaClasspath; -/* - * 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 junit.extensions.TestSetup; import junit.framework.Test; import junit.framework.TestCase; diff --git a/surefire-its/src/test/resources/plexus-conflict/src/main/java/plexusConflict/CommandlineExtender.java b/surefire-its/src/test/resources/plexus-conflict/src/main/java/plexusConflict/CommandlineExtender.java index 98f2615fa0..bfaa6c8a3f 100644 --- a/surefire-its/src/test/resources/plexus-conflict/src/main/java/plexusConflict/CommandlineExtender.java +++ b/surefire-its/src/test/resources/plexus-conflict/src/main/java/plexusConflict/CommandlineExtender.java @@ -1,24 +1,5 @@ package plexusConflict; -/* - * 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.codehaus.plexus.util.cli.Commandline; /** diff --git a/surefire-its/src/test/resources/plexus-conflict/src/test/java/plexusConflict/BasicTest.java b/surefire-its/src/test/resources/plexus-conflict/src/test/java/plexusConflict/BasicTest.java index 96f1bbaa7c..eabc1f5585 100644 --- a/surefire-its/src/test/resources/plexus-conflict/src/test/java/plexusConflict/BasicTest.java +++ b/surefire-its/src/test/resources/plexus-conflict/src/test/java/plexusConflict/BasicTest.java @@ -1,25 +1,6 @@ package plexusConflict; -/* - * 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 junit.extensions.TestSetup; import junit.framework.Test; import junit.framework.TestCase; diff --git a/surefire-its/src/test/resources/reporters/src/test/java/reporters/Test1.java b/surefire-its/src/test/resources/reporters/src/test/java/reporters/Test1.java index e783db5050..629d3d2a32 100644 --- a/surefire-its/src/test/resources/reporters/src/test/java/reporters/Test1.java +++ b/surefire-its/src/test/resources/reporters/src/test/java/reporters/Test1.java @@ -1,24 +1,5 @@ package reporters; -/* - * 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 junit.framework.TestCase; public class Test1 extends TestCase diff --git a/surefire-its/src/test/resources/result-counting/src/test/java/resultcounting/MySuiteTest1.java b/surefire-its/src/test/resources/result-counting/src/test/java/resultcounting/MySuiteTest1.java index 137fdee610..0e0794598e 100644 --- a/surefire-its/src/test/resources/result-counting/src/test/java/resultcounting/MySuiteTest1.java +++ b/surefire-its/src/test/resources/result-counting/src/test/java/resultcounting/MySuiteTest1.java @@ -1,24 +1,5 @@ package resultcounting; -/* - * 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 junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; diff --git a/surefire-its/src/test/resources/result-counting/src/test/java/resultcounting/MySuiteTest2.java b/surefire-its/src/test/resources/result-counting/src/test/java/resultcounting/MySuiteTest2.java index 9188290ac3..0c44f044c7 100644 --- a/surefire-its/src/test/resources/result-counting/src/test/java/resultcounting/MySuiteTest2.java +++ b/surefire-its/src/test/resources/result-counting/src/test/java/resultcounting/MySuiteTest2.java @@ -1,24 +1,5 @@ package resultcounting; -/* - * 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 junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; diff --git a/surefire-its/src/test/resources/result-counting/src/test/java/resultcounting/MySuiteTest3.java b/surefire-its/src/test/resources/result-counting/src/test/java/resultcounting/MySuiteTest3.java index 35c6e5bba0..4c08224661 100644 --- a/surefire-its/src/test/resources/result-counting/src/test/java/resultcounting/MySuiteTest3.java +++ b/surefire-its/src/test/resources/result-counting/src/test/java/resultcounting/MySuiteTest3.java @@ -1,24 +1,5 @@ package resultcounting; -/* - * 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 junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; diff --git a/surefire-its/src/test/resources/result-counting/src/test/java/resultcounting/Test1.java b/surefire-its/src/test/resources/result-counting/src/test/java/resultcounting/Test1.java index c3283d2be6..9d587a4b9c 100644 --- a/surefire-its/src/test/resources/result-counting/src/test/java/resultcounting/Test1.java +++ b/surefire-its/src/test/resources/result-counting/src/test/java/resultcounting/Test1.java @@ -1,23 +1,4 @@ package resultcounting; -/* - * 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.junit.Test; import static org.junit.Assert.assertTrue; @@ -73,4 +54,4 @@ public void testWithFailingAssumption14() { public void testWithFailingAssumption15() { assumeThat( 2, is(3)); } -} \ No newline at end of file +} diff --git a/surefire-its/src/test/resources/result-counting/src/test/java/resultcounting/Test2.java b/surefire-its/src/test/resources/result-counting/src/test/java/resultcounting/Test2.java index e5d5f5305f..9686fecb0d 100644 --- a/surefire-its/src/test/resources/result-counting/src/test/java/resultcounting/Test2.java +++ b/surefire-its/src/test/resources/result-counting/src/test/java/resultcounting/Test2.java @@ -1,24 +1,5 @@ package resultcounting; -/* - * 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.junit.Ignore; import org.junit.Test; @@ -124,4 +105,4 @@ public void testWithException8() throw new RuntimeException( "We expect this" ); } -} \ No newline at end of file +} diff --git a/surefire-its/src/test/resources/runOrder/src/test/java/junit/runOrder/TestA.java b/surefire-its/src/test/resources/runOrder/src/test/java/junit/runOrder/TestA.java index cbf15e05a2..9dd1b30091 100644 --- a/surefire-its/src/test/resources/runOrder/src/test/java/junit/runOrder/TestA.java +++ b/surefire-its/src/test/resources/runOrder/src/test/java/junit/runOrder/TestA.java @@ -1,24 +1,5 @@ package junit.runOrder; -/* - * 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 junit.framework.TestCase; public class TestA diff --git a/surefire-its/src/test/resources/runOrder/src/test/java/junit/runOrder/TestB.java b/surefire-its/src/test/resources/runOrder/src/test/java/junit/runOrder/TestB.java index 96da722e51..88bb480b0a 100644 --- a/surefire-its/src/test/resources/runOrder/src/test/java/junit/runOrder/TestB.java +++ b/surefire-its/src/test/resources/runOrder/src/test/java/junit/runOrder/TestB.java @@ -1,24 +1,5 @@ package junit.runOrder; -/* - * 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 junit.framework.TestCase; public class TestB diff --git a/surefire-its/src/test/resources/runOrder/src/test/java/junit/runOrder/TestC.java b/surefire-its/src/test/resources/runOrder/src/test/java/junit/runOrder/TestC.java index 4ac63c2371..b5f4c8aea9 100644 --- a/surefire-its/src/test/resources/runOrder/src/test/java/junit/runOrder/TestC.java +++ b/surefire-its/src/test/resources/runOrder/src/test/java/junit/runOrder/TestC.java @@ -1,24 +1,5 @@ package junit.runOrder; -/* - * 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 junit.framework.TestCase; public class TestC diff --git a/surefire-its/src/test/resources/runorder-parallel/src/test/java/runorder/parallel/Test1.java b/surefire-its/src/test/resources/runorder-parallel/src/test/java/runorder/parallel/Test1.java index d11f48a655..02e5e4f87d 100755 --- a/surefire-its/src/test/resources/runorder-parallel/src/test/java/runorder/parallel/Test1.java +++ b/surefire-its/src/test/resources/runorder-parallel/src/test/java/runorder/parallel/Test1.java @@ -1,24 +1,5 @@ package runorder.parallel; -/* - * 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.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; @@ -89,4 +70,4 @@ public static void tearDownAfterClass() } -} \ No newline at end of file +} diff --git a/surefire-its/src/test/resources/runorder-parallel/src/test/java/runorder/parallel/Test2.java b/surefire-its/src/test/resources/runorder-parallel/src/test/java/runorder/parallel/Test2.java index dfa4f4fb89..bfb702a97f 100644 --- a/surefire-its/src/test/resources/runorder-parallel/src/test/java/runorder/parallel/Test2.java +++ b/surefire-its/src/test/resources/runorder-parallel/src/test/java/runorder/parallel/Test2.java @@ -1,24 +1,5 @@ package runorder.parallel; -/* - * 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.junit.Test; /** @@ -47,4 +28,4 @@ public void testSleep5000() System.out.println( "Test2.sleep5000 started @ " + System.currentTimeMillis() ); Test1.sleep( 5000 ); } -} \ No newline at end of file +} diff --git a/surefire-its/src/test/resources/runorder-parallel/src/test/java/runorder/parallel/Test3.java b/surefire-its/src/test/resources/runorder-parallel/src/test/java/runorder/parallel/Test3.java index 0dbc57efc5..285b46cc1d 100644 --- a/surefire-its/src/test/resources/runorder-parallel/src/test/java/runorder/parallel/Test3.java +++ b/surefire-its/src/test/resources/runorder-parallel/src/test/java/runorder/parallel/Test3.java @@ -1,24 +1,5 @@ package runorder.parallel; -/* - * 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.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; @@ -80,4 +61,4 @@ public static void tearDownAfterClass() Thread.sleep( 175 ); } -} \ No newline at end of file +} diff --git a/surefire-its/src/test/resources/small-result-counting/src/test/java/smallresultcounting/Test1.java b/surefire-its/src/test/resources/small-result-counting/src/test/java/smallresultcounting/Test1.java index c79f7466bc..18447da585 100644 --- a/surefire-its/src/test/resources/small-result-counting/src/test/java/smallresultcounting/Test1.java +++ b/surefire-its/src/test/resources/small-result-counting/src/test/java/smallresultcounting/Test1.java @@ -1,24 +1,5 @@ package smallresultcounting; -/* - * 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.junit.Test; import static org.hamcrest.CoreMatchers.is; @@ -63,4 +44,4 @@ public void testWithFailingAssumption5() { assumeThat( 2, is( 3 ) ); } -} \ No newline at end of file +} diff --git a/surefire-its/src/test/resources/small-result-counting/src/test/java/smallresultcounting/Test2.java b/surefire-its/src/test/resources/small-result-counting/src/test/java/smallresultcounting/Test2.java index 5b3494f04d..009ac4b683 100644 --- a/surefire-its/src/test/resources/small-result-counting/src/test/java/smallresultcounting/Test2.java +++ b/surefire-its/src/test/resources/small-result-counting/src/test/java/smallresultcounting/Test2.java @@ -1,24 +1,5 @@ package smallresultcounting; -/* - * 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.junit.Ignore; import org.junit.Test; @@ -104,4 +85,4 @@ public void testAllok4() { } -} \ No newline at end of file +} diff --git a/surefire-its/src/test/resources/surefire-1004-RunTestFromDependencyJarsTypeAndClassifier/surefire-1004-module1/src/test/java/org/acme/tests/ClasspathTestA.java b/surefire-its/src/test/resources/surefire-1004-RunTestFromDependencyJarsTypeAndClassifier/surefire-1004-module1/src/test/java/org/acme/tests/ClasspathTestA.java index eb73da5df7..6b72cbb9a2 100644 --- a/surefire-its/src/test/resources/surefire-1004-RunTestFromDependencyJarsTypeAndClassifier/surefire-1004-module1/src/test/java/org/acme/tests/ClasspathTestA.java +++ b/surefire-its/src/test/resources/surefire-1004-RunTestFromDependencyJarsTypeAndClassifier/surefire-1004-module1/src/test/java/org/acme/tests/ClasspathTestA.java @@ -1,24 +1,5 @@ package org.acme.tests; -/* - * 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.junit.Test; public class ClasspathTestA diff --git a/surefire-its/src/test/resources/surefire-1004-RunTestFromDependencyJarsTypeAndClassifier/surefire-1004-testjar/src/test/java/org/acme/classifiedtests/ClassifiedTestA.java b/surefire-its/src/test/resources/surefire-1004-RunTestFromDependencyJarsTypeAndClassifier/surefire-1004-testjar/src/test/java/org/acme/classifiedtests/ClassifiedTestA.java index a794470f01..60d1d1b6fd 100644 --- a/surefire-its/src/test/resources/surefire-1004-RunTestFromDependencyJarsTypeAndClassifier/surefire-1004-testjar/src/test/java/org/acme/classifiedtests/ClassifiedTestA.java +++ b/surefire-its/src/test/resources/surefire-1004-RunTestFromDependencyJarsTypeAndClassifier/surefire-1004-testjar/src/test/java/org/acme/classifiedtests/ClassifiedTestA.java @@ -1,24 +1,5 @@ package org.acme.classifiedtests; -/* - * 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.junit.Test; public class ClassifiedTestA diff --git a/surefire-its/src/test/resources/surefire-1004-RunTestFromDependencyJarsTypeAndClassifier/surefire-1004-testjar/src/test/java/org/acme/othertests/OtherTestA.java b/surefire-its/src/test/resources/surefire-1004-RunTestFromDependencyJarsTypeAndClassifier/surefire-1004-testjar/src/test/java/org/acme/othertests/OtherTestA.java index 4f479cac16..7d18b2436b 100644 --- a/surefire-its/src/test/resources/surefire-1004-RunTestFromDependencyJarsTypeAndClassifier/surefire-1004-testjar/src/test/java/org/acme/othertests/OtherTestA.java +++ b/surefire-its/src/test/resources/surefire-1004-RunTestFromDependencyJarsTypeAndClassifier/surefire-1004-testjar/src/test/java/org/acme/othertests/OtherTestA.java @@ -1,24 +1,5 @@ package org.acme.othertests; -/* - * 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 static org.junit.Assert.*; import org.junit.Test; diff --git a/surefire-its/src/test/resources/surefire-1004-RunTestFromDependencyJarsTypeAndClassifier/surefire-1004-testjar/src/test/java/org/acme/tests/TestA.java b/surefire-its/src/test/resources/surefire-1004-RunTestFromDependencyJarsTypeAndClassifier/surefire-1004-testjar/src/test/java/org/acme/tests/TestA.java index efcb95698c..0ba9833338 100644 --- a/surefire-its/src/test/resources/surefire-1004-RunTestFromDependencyJarsTypeAndClassifier/surefire-1004-testjar/src/test/java/org/acme/tests/TestA.java +++ b/surefire-its/src/test/resources/surefire-1004-RunTestFromDependencyJarsTypeAndClassifier/surefire-1004-testjar/src/test/java/org/acme/tests/TestA.java @@ -1,24 +1,5 @@ package org.acme.tests; -/* - * 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.junit.Test; public class TestA diff --git a/surefire-its/src/test/resources/surefire-1004-RunTestFromDependencyJarsTypeAndClassifier/surefire-1004-testjar/src/test/java/org/acme/tests/TestB.java b/surefire-its/src/test/resources/surefire-1004-RunTestFromDependencyJarsTypeAndClassifier/surefire-1004-testjar/src/test/java/org/acme/tests/TestB.java index ce620c9e38..1a528dd1d9 100644 --- a/surefire-its/src/test/resources/surefire-1004-RunTestFromDependencyJarsTypeAndClassifier/surefire-1004-testjar/src/test/java/org/acme/tests/TestB.java +++ b/surefire-its/src/test/resources/surefire-1004-RunTestFromDependencyJarsTypeAndClassifier/surefire-1004-testjar/src/test/java/org/acme/tests/TestB.java @@ -1,24 +1,5 @@ package org.acme.tests; -/* - * 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.junit.Test; public class TestB diff --git a/surefire-its/src/test/resources/surefire-1028-unable-to-run-single-test/src/test/java/jiras/surefire1028/SomeTest.java b/surefire-its/src/test/resources/surefire-1028-unable-to-run-single-test/src/test/java/jiras/surefire1028/SomeTest.java index 71cc102a28..a1135513ce 100644 --- a/surefire-its/src/test/resources/surefire-1028-unable-to-run-single-test/src/test/java/jiras/surefire1028/SomeTest.java +++ b/surefire-its/src/test/resources/surefire-1028-unable-to-run-single-test/src/test/java/jiras/surefire1028/SomeTest.java @@ -1,24 +1,5 @@ package jiras.surefire1028; -/* - * 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.junit.Assert; import org.junit.Test; diff --git a/surefire-its/src/test/resources/surefire-1036-NonFilterableJUnitRunnerWithCategories/src/test/java/jiras/surefire1036/TestSomeIntegration.java b/surefire-its/src/test/resources/surefire-1036-NonFilterableJUnitRunnerWithCategories/src/test/java/jiras/surefire1036/TestSomeIntegration.java index 64dc71e5d8..3a7540890a 100644 --- a/surefire-its/src/test/resources/surefire-1036-NonFilterableJUnitRunnerWithCategories/src/test/java/jiras/surefire1036/TestSomeIntegration.java +++ b/surefire-its/src/test/resources/surefire-1036-NonFilterableJUnitRunnerWithCategories/src/test/java/jiras/surefire1036/TestSomeIntegration.java @@ -1,24 +1,5 @@ package jiras.surefire1036; -/* - * 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 static org.junit.Assert.*; import org.junit.Test; diff --git a/surefire-its/src/test/resources/surefire-1036-NonFilterableJUnitRunnerWithCategories/src/test/java/jiras/surefire1036/TestSomeUnit.java b/surefire-its/src/test/resources/surefire-1036-NonFilterableJUnitRunnerWithCategories/src/test/java/jiras/surefire1036/TestSomeUnit.java index 1ea26e8454..c054a21d23 100644 --- a/surefire-its/src/test/resources/surefire-1036-NonFilterableJUnitRunnerWithCategories/src/test/java/jiras/surefire1036/TestSomeUnit.java +++ b/surefire-its/src/test/resources/surefire-1036-NonFilterableJUnitRunnerWithCategories/src/test/java/jiras/surefire1036/TestSomeUnit.java @@ -1,24 +1,5 @@ package jiras.surefire1036; -/* - * 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.junit.Test; import static org.junit.Assert.fail; diff --git a/surefire-its/src/test/resources/surefire-1036-NonFilterableJUnitRunnerWithCategories/src/test/java/jiras/surefire1036/TestSomethingWithMockitoRunner.java b/surefire-its/src/test/resources/surefire-1036-NonFilterableJUnitRunnerWithCategories/src/test/java/jiras/surefire1036/TestSomethingWithMockitoRunner.java index 5122bca767..849be86f5a 100644 --- a/surefire-its/src/test/resources/surefire-1036-NonFilterableJUnitRunnerWithCategories/src/test/java/jiras/surefire1036/TestSomethingWithMockitoRunner.java +++ b/surefire-its/src/test/resources/surefire-1036-NonFilterableJUnitRunnerWithCategories/src/test/java/jiras/surefire1036/TestSomethingWithMockitoRunner.java @@ -1,24 +1,5 @@ package jiras.surefire1036; -/* - * 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.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/surefire-its/src/test/resources/surefire-1041-exception-in-junit-runner/src/test/java/test/AppTest.java b/surefire-its/src/test/resources/surefire-1041-exception-in-junit-runner/src/test/java/test/AppTest.java index 978da1aea1..3e79244a91 100644 --- a/surefire-its/src/test/resources/surefire-1041-exception-in-junit-runner/src/test/java/test/AppTest.java +++ b/surefire-its/src/test/resources/surefire-1041-exception-in-junit-runner/src/test/java/test/AppTest.java @@ -1,24 +1,5 @@ package test; -/* - * 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.junit.Test; import org.junit.runner.RunWith; diff --git a/surefire-its/src/test/resources/surefire-1041-exception-in-junit-runner/src/test/java/test/BadRunner.java b/surefire-its/src/test/resources/surefire-1041-exception-in-junit-runner/src/test/java/test/BadRunner.java index 759c0f4728..6c9c5a920c 100644 --- a/surefire-its/src/test/resources/surefire-1041-exception-in-junit-runner/src/test/java/test/BadRunner.java +++ b/surefire-its/src/test/resources/surefire-1041-exception-in-junit-runner/src/test/java/test/BadRunner.java @@ -1,24 +1,5 @@ package test; -/* - * 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.junit.runner.notification.RunNotifier; import org.junit.runners.BlockJUnit4ClassRunner; import org.junit.runners.model.InitializationError; diff --git a/surefire-its/src/test/resources/surefire-1053-system-properties/src/test/java/jiras/surefire1053/ATest.java b/surefire-its/src/test/resources/surefire-1053-system-properties/src/test/java/jiras/surefire1053/ATest.java index 367adc586d..1bea6d2f09 100644 --- a/surefire-its/src/test/resources/surefire-1053-system-properties/src/test/java/jiras/surefire1053/ATest.java +++ b/surefire-its/src/test/resources/surefire-1053-system-properties/src/test/java/jiras/surefire1053/ATest.java @@ -1,24 +1,5 @@ package jiras.surefire1053; -/* - * 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.junit.Test; public final class ATest { diff --git a/surefire-its/src/test/resources/surefire-1080-parallel-fork-double-test/src/test/java/com/cal/HelloWorldFlakyCotTest.java b/surefire-its/src/test/resources/surefire-1080-parallel-fork-double-test/src/test/java/com/cal/HelloWorldFlakyCotTest.java index 1147ecdc01..c67dae8cd7 100644 --- a/surefire-its/src/test/resources/surefire-1080-parallel-fork-double-test/src/test/java/com/cal/HelloWorldFlakyCotTest.java +++ b/surefire-its/src/test/resources/surefire-1080-parallel-fork-double-test/src/test/java/com/cal/HelloWorldFlakyCotTest.java @@ -1,24 +1,5 @@ package com.cal; -/* - * 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.junit.Test; public class HelloWorldFlakyCotTest diff --git a/surefire-its/src/test/resources/surefire-1080-parallel-fork-double-test/src/test/java/com/cal/HelloWorldFlakyErrorTest.java b/surefire-its/src/test/resources/surefire-1080-parallel-fork-double-test/src/test/java/com/cal/HelloWorldFlakyErrorTest.java index 9856fc8ff4..3cc67912b8 100644 --- a/surefire-its/src/test/resources/surefire-1080-parallel-fork-double-test/src/test/java/com/cal/HelloWorldFlakyErrorTest.java +++ b/surefire-its/src/test/resources/surefire-1080-parallel-fork-double-test/src/test/java/com/cal/HelloWorldFlakyErrorTest.java @@ -1,24 +1,5 @@ package com.cal; -/* - * 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.junit.Test; public class HelloWorldFlakyErrorTest diff --git a/surefire-its/src/test/resources/surefire-1080-parallel-fork-double-test/src/test/java/com/cal/HelloWorldTest.java b/surefire-its/src/test/resources/surefire-1080-parallel-fork-double-test/src/test/java/com/cal/HelloWorldTest.java index 0bd3aca803..d66b8a7e34 100644 --- a/surefire-its/src/test/resources/surefire-1080-parallel-fork-double-test/src/test/java/com/cal/HelloWorldTest.java +++ b/surefire-its/src/test/resources/surefire-1080-parallel-fork-double-test/src/test/java/com/cal/HelloWorldTest.java @@ -1,24 +1,5 @@ package com.cal; -/* - * 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.junit.Test; public class HelloWorldTest diff --git a/surefire-its/src/test/resources/surefire-1080-parallel-fork-double-test/src/test/java/com/cal/SimpleTest.java b/surefire-its/src/test/resources/surefire-1080-parallel-fork-double-test/src/test/java/com/cal/SimpleTest.java index 02cd79b657..aa240ac81b 100644 --- a/surefire-its/src/test/resources/surefire-1080-parallel-fork-double-test/src/test/java/com/cal/SimpleTest.java +++ b/surefire-its/src/test/resources/surefire-1080-parallel-fork-double-test/src/test/java/com/cal/SimpleTest.java @@ -1,24 +1,5 @@ package com.cal; -/* - * 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.junit.Test; import static org.junit.Assert.assertEquals; diff --git a/surefire-its/src/test/resources/surefire-1082-parallel-junit-parameterized/src/test/java/jiras/surefire1082/Jira1082Test.java b/surefire-its/src/test/resources/surefire-1082-parallel-junit-parameterized/src/test/java/jiras/surefire1082/Jira1082Test.java index e8cef992da..3cbff84d09 100644 --- a/surefire-its/src/test/resources/surefire-1082-parallel-junit-parameterized/src/test/java/jiras/surefire1082/Jira1082Test.java +++ b/surefire-its/src/test/resources/surefire-1082-parallel-junit-parameterized/src/test/java/jiras/surefire1082/Jira1082Test.java @@ -1,24 +1,5 @@ package jiras.surefire1082; -/* - * 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.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; diff --git a/surefire-its/src/test/resources/surefire-1082-parallel-junit-parameterized/src/test/java/jiras/surefire1082/Jira1264Test.java b/surefire-its/src/test/resources/surefire-1082-parallel-junit-parameterized/src/test/java/jiras/surefire1082/Jira1264Test.java index 56e7644010..57977a1ac8 100644 --- a/surefire-its/src/test/resources/surefire-1082-parallel-junit-parameterized/src/test/java/jiras/surefire1082/Jira1264Test.java +++ b/surefire-its/src/test/resources/surefire-1082-parallel-junit-parameterized/src/test/java/jiras/surefire1082/Jira1264Test.java @@ -1,24 +1,5 @@ package jiras.surefire1082; -/* - * 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.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; diff --git a/surefire-its/src/test/resources/surefire-1095-npe-in-runlistener/src/test/java/jiras/surefire1095/Listener.java b/surefire-its/src/test/resources/surefire-1095-npe-in-runlistener/src/test/java/jiras/surefire1095/Listener.java index f16c04af18..2e409fd689 100644 --- a/surefire-its/src/test/resources/surefire-1095-npe-in-runlistener/src/test/java/jiras/surefire1095/Listener.java +++ b/surefire-its/src/test/resources/surefire-1095-npe-in-runlistener/src/test/java/jiras/surefire1095/Listener.java @@ -1,24 +1,5 @@ package jiras.surefire1095; -/* - * 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.junit.runner.Description; import org.junit.runner.notification.RunListener; diff --git a/surefire-its/src/test/resources/surefire-1095-npe-in-runlistener/src/test/java/jiras/surefire1095/SomeTest.java b/surefire-its/src/test/resources/surefire-1095-npe-in-runlistener/src/test/java/jiras/surefire1095/SomeTest.java index 923917a0b4..ec2a0549e7 100644 --- a/surefire-its/src/test/resources/surefire-1095-npe-in-runlistener/src/test/java/jiras/surefire1095/SomeTest.java +++ b/surefire-its/src/test/resources/surefire-1095-npe-in-runlistener/src/test/java/jiras/surefire1095/SomeTest.java @@ -1,24 +1,5 @@ package jiras.surefire1095; -/* - * 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 junit.runner.Version; import org.junit.Test; diff --git a/surefire-its/src/test/resources/surefire-1098-balanced-runorder/src/test/java/jiras/surefire1098/ATest.java b/surefire-its/src/test/resources/surefire-1098-balanced-runorder/src/test/java/jiras/surefire1098/ATest.java index 3acb9cd8a7..42b8803869 100644 --- a/surefire-its/src/test/resources/surefire-1098-balanced-runorder/src/test/java/jiras/surefire1098/ATest.java +++ b/surefire-its/src/test/resources/surefire-1098-balanced-runorder/src/test/java/jiras/surefire1098/ATest.java @@ -1,24 +1,5 @@ package jiras.surefire1098; -/* - * 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.junit.Test; public final class ATest { diff --git a/surefire-its/src/test/resources/surefire-1098-balanced-runorder/src/test/java/jiras/surefire1098/BTest.java b/surefire-its/src/test/resources/surefire-1098-balanced-runorder/src/test/java/jiras/surefire1098/BTest.java index d9073c67a8..0a8c2a8186 100644 --- a/surefire-its/src/test/resources/surefire-1098-balanced-runorder/src/test/java/jiras/surefire1098/BTest.java +++ b/surefire-its/src/test/resources/surefire-1098-balanced-runorder/src/test/java/jiras/surefire1098/BTest.java @@ -1,24 +1,5 @@ package jiras.surefire1098; -/* - * 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.junit.Test; public final class BTest { diff --git a/surefire-its/src/test/resources/surefire-1098-balanced-runorder/src/test/java/jiras/surefire1098/CTest.java b/surefire-its/src/test/resources/surefire-1098-balanced-runorder/src/test/java/jiras/surefire1098/CTest.java index b02b7b89e4..19f61f0e56 100644 --- a/surefire-its/src/test/resources/surefire-1098-balanced-runorder/src/test/java/jiras/surefire1098/CTest.java +++ b/surefire-its/src/test/resources/surefire-1098-balanced-runorder/src/test/java/jiras/surefire1098/CTest.java @@ -1,24 +1,5 @@ package jiras.surefire1098; -/* - * 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.junit.Test; public final class CTest { diff --git a/surefire-its/src/test/resources/surefire-1098-balanced-runorder/src/test/java/jiras/surefire1098/DTest.java b/surefire-its/src/test/resources/surefire-1098-balanced-runorder/src/test/java/jiras/surefire1098/DTest.java index b5b029d036..a8c8439647 100644 --- a/surefire-its/src/test/resources/surefire-1098-balanced-runorder/src/test/java/jiras/surefire1098/DTest.java +++ b/surefire-its/src/test/resources/surefire-1098-balanced-runorder/src/test/java/jiras/surefire1098/DTest.java @@ -1,24 +1,5 @@ package jiras.surefire1098; -/* - * 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.junit.Test; import java.util.concurrent.TimeUnit; diff --git a/surefire-its/src/test/resources/surefire-1098-balanced-runorder/src/test/java/jiras/surefire1098/Locker.java b/surefire-its/src/test/resources/surefire-1098-balanced-runorder/src/test/java/jiras/surefire1098/Locker.java index 4f0bc557e1..4932661800 100644 --- a/surefire-its/src/test/resources/surefire-1098-balanced-runorder/src/test/java/jiras/surefire1098/Locker.java +++ b/surefire-its/src/test/resources/surefire-1098-balanced-runorder/src/test/java/jiras/surefire1098/Locker.java @@ -1,24 +1,5 @@ package jiras.surefire1098; -/* - * 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 java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; diff --git a/surefire-its/src/test/resources/surefire-1122-parallel-and-flakyTests/src/test/java/test/FlakyTest.java b/surefire-its/src/test/resources/surefire-1122-parallel-and-flakyTests/src/test/java/test/FlakyTest.java index fc7b443740..1c403ef107 100644 --- a/surefire-its/src/test/resources/surefire-1122-parallel-and-flakyTests/src/test/java/test/FlakyTest.java +++ b/surefire-its/src/test/resources/surefire-1122-parallel-and-flakyTests/src/test/java/test/FlakyTest.java @@ -1,24 +1,5 @@ package test; -/* - * 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.junit.Test; public class FlakyTest diff --git a/surefire-its/src/test/resources/surefire-1136-cwd-propagation-in-forked-mode/src/test/java/cwd/CurrentWorkingDirectoryInForkedModeTest.java b/surefire-its/src/test/resources/surefire-1136-cwd-propagation-in-forked-mode/src/test/java/cwd/CurrentWorkingDirectoryInForkedModeTest.java index 6a82ee3e5c..a579eee1fb 100644 --- a/surefire-its/src/test/resources/surefire-1136-cwd-propagation-in-forked-mode/src/test/java/cwd/CurrentWorkingDirectoryInForkedModeTest.java +++ b/surefire-its/src/test/resources/surefire-1136-cwd-propagation-in-forked-mode/src/test/java/cwd/CurrentWorkingDirectoryInForkedModeTest.java @@ -1,24 +1,5 @@ package cwd; -/* - * 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.junit.Test; import java.io.File; diff --git a/surefire-its/src/test/resources/surefire-1144-xml-runtime/src/test/java/surefire1144/Test1.java b/surefire-its/src/test/resources/surefire-1144-xml-runtime/src/test/java/surefire1144/Test1.java index 047a741297..3cedf8fe98 100644 --- a/surefire-its/src/test/resources/surefire-1144-xml-runtime/src/test/java/surefire1144/Test1.java +++ b/surefire-its/src/test/resources/surefire-1144-xml-runtime/src/test/java/surefire1144/Test1.java @@ -1,24 +1,5 @@ package surefire1144; -/* - * 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.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; diff --git a/surefire-its/src/test/resources/surefire-1146-rerunFailingTests-with-Parameterized/src/test/java/jiras/surefire1146/CustomDescriptionParameterizedTest.java b/surefire-its/src/test/resources/surefire-1146-rerunFailingTests-with-Parameterized/src/test/java/jiras/surefire1146/CustomDescriptionParameterizedTest.java index ffdfa878f5..3bc621cb1c 100644 --- a/surefire-its/src/test/resources/surefire-1146-rerunFailingTests-with-Parameterized/src/test/java/jiras/surefire1146/CustomDescriptionParameterizedTest.java +++ b/surefire-its/src/test/resources/surefire-1146-rerunFailingTests-with-Parameterized/src/test/java/jiras/surefire1146/CustomDescriptionParameterizedTest.java @@ -1,24 +1,5 @@ package jiras.surefire1146; -/* - * 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 java.util.ArrayList; import java.util.List; diff --git a/surefire-its/src/test/resources/surefire-1146-rerunFailingTests-with-Parameterized/src/test/java/jiras/surefire1146/CustomDescriptionWithCommaParameterizedTest.java b/surefire-its/src/test/resources/surefire-1146-rerunFailingTests-with-Parameterized/src/test/java/jiras/surefire1146/CustomDescriptionWithCommaParameterizedTest.java index 39563dfb2b..0eae5a75bd 100644 --- a/surefire-its/src/test/resources/surefire-1146-rerunFailingTests-with-Parameterized/src/test/java/jiras/surefire1146/CustomDescriptionWithCommaParameterizedTest.java +++ b/surefire-its/src/test/resources/surefire-1146-rerunFailingTests-with-Parameterized/src/test/java/jiras/surefire1146/CustomDescriptionWithCommaParameterizedTest.java @@ -1,24 +1,5 @@ package jiras.surefire1146; -/* - * 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 java.util.ArrayList; import java.util.List; diff --git a/surefire-its/src/test/resources/surefire-1146-rerunFailingTests-with-Parameterized/src/test/java/jiras/surefire1146/SimpleParameterizedTest.java b/surefire-its/src/test/resources/surefire-1146-rerunFailingTests-with-Parameterized/src/test/java/jiras/surefire1146/SimpleParameterizedTest.java index f278c347b0..5b798ecd58 100644 --- a/surefire-its/src/test/resources/surefire-1146-rerunFailingTests-with-Parameterized/src/test/java/jiras/surefire1146/SimpleParameterizedTest.java +++ b/surefire-its/src/test/resources/surefire-1146-rerunFailingTests-with-Parameterized/src/test/java/jiras/surefire1146/SimpleParameterizedTest.java @@ -1,24 +1,5 @@ package jiras.surefire1146; -/* - * 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 java.util.ArrayList; import java.util.List; diff --git a/surefire-its/src/test/resources/surefire-1146-rerunFailingTests-with-Parameterized/src/test/java/jiras/surefire1146/StandardTest.java b/surefire-its/src/test/resources/surefire-1146-rerunFailingTests-with-Parameterized/src/test/java/jiras/surefire1146/StandardTest.java index f96cdd8fa7..bf9990056c 100644 --- a/surefire-its/src/test/resources/surefire-1146-rerunFailingTests-with-Parameterized/src/test/java/jiras/surefire1146/StandardTest.java +++ b/surefire-its/src/test/resources/surefire-1146-rerunFailingTests-with-Parameterized/src/test/java/jiras/surefire1146/StandardTest.java @@ -1,24 +1,5 @@ package jiras.surefire1146; -/* - * 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 junit.runner.Version; import org.junit.Test; diff --git a/surefire-its/src/test/resources/surefire-1152-rerunFailingTestsCount-suite/src/test/java/jiras/surefire1152/FlakyIT.java b/surefire-its/src/test/resources/surefire-1152-rerunFailingTestsCount-suite/src/test/java/jiras/surefire1152/FlakyIT.java index 27d5b5f500..438f920808 100644 --- a/surefire-its/src/test/resources/surefire-1152-rerunFailingTestsCount-suite/src/test/java/jiras/surefire1152/FlakyIT.java +++ b/surefire-its/src/test/resources/surefire-1152-rerunFailingTestsCount-suite/src/test/java/jiras/surefire1152/FlakyIT.java @@ -1,24 +1,5 @@ package jiras.surefire1152; -/* - * 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.junit.Test; import static org.junit.Assert.fail; diff --git a/surefire-its/src/test/resources/surefire-1152-rerunFailingTestsCount-suite/src/test/java/jiras/surefire1152/FlakyITSuite.java b/surefire-its/src/test/resources/surefire-1152-rerunFailingTestsCount-suite/src/test/java/jiras/surefire1152/FlakyITSuite.java index 0ebd03cb05..37e0d45b88 100644 --- a/surefire-its/src/test/resources/surefire-1152-rerunFailingTestsCount-suite/src/test/java/jiras/surefire1152/FlakyITSuite.java +++ b/surefire-its/src/test/resources/surefire-1152-rerunFailingTestsCount-suite/src/test/java/jiras/surefire1152/FlakyITSuite.java @@ -1,24 +1,5 @@ package jiras.surefire1152; -/* - * 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.junit.runner.RunWith; import org.junit.runners.Suite; diff --git a/surefire-its/src/test/resources/surefire-1152-rerunFailingTestsCount-suite/src/test/java/jiras/surefire1152/FlakyParent.java b/surefire-its/src/test/resources/surefire-1152-rerunFailingTestsCount-suite/src/test/java/jiras/surefire1152/FlakyParent.java index eae008f708..6038ecbba6 100644 --- a/surefire-its/src/test/resources/surefire-1152-rerunFailingTestsCount-suite/src/test/java/jiras/surefire1152/FlakyParent.java +++ b/surefire-its/src/test/resources/surefire-1152-rerunFailingTestsCount-suite/src/test/java/jiras/surefire1152/FlakyParent.java @@ -1,24 +1,5 @@ package jiras.surefire1152; -/* - * 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.junit.Test; import java.util.HashSet; diff --git a/surefire-its/src/test/resources/surefire-1152-rerunFailingTestsCount-suite/src/test/java/jiras/surefire1152/FlakyTest.java b/surefire-its/src/test/resources/surefire-1152-rerunFailingTestsCount-suite/src/test/java/jiras/surefire1152/FlakyTest.java index ee20f9eb43..61cfd6450e 100644 --- a/surefire-its/src/test/resources/surefire-1152-rerunFailingTestsCount-suite/src/test/java/jiras/surefire1152/FlakyTest.java +++ b/surefire-its/src/test/resources/surefire-1152-rerunFailingTestsCount-suite/src/test/java/jiras/surefire1152/FlakyTest.java @@ -1,24 +1,5 @@ package jiras.surefire1152; -/* - * 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.junit.Test; import static org.junit.Assert.fail; diff --git a/surefire-its/src/test/resources/surefire-1152-rerunFailingTestsCount-suite/src/test/java/jiras/surefire1152/FlakyTestSuite.java b/surefire-its/src/test/resources/surefire-1152-rerunFailingTestsCount-suite/src/test/java/jiras/surefire1152/FlakyTestSuite.java index f4a7d6773a..7f77eea612 100644 --- a/surefire-its/src/test/resources/surefire-1152-rerunFailingTestsCount-suite/src/test/java/jiras/surefire1152/FlakyTestSuite.java +++ b/surefire-its/src/test/resources/surefire-1152-rerunFailingTestsCount-suite/src/test/java/jiras/surefire1152/FlakyTestSuite.java @@ -1,24 +1,5 @@ package jiras.surefire1152; -/* - * 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.junit.runner.RunWith; import org.junit.runners.Suite; diff --git a/surefire-its/src/test/resources/surefire-1153-includesAndSpecifiedTest/src/test/java/jiras/surefire1153/IncludedUT.java b/surefire-its/src/test/resources/surefire-1153-includesAndSpecifiedTest/src/test/java/jiras/surefire1153/IncludedUT.java index 042cf373be..27c354d0b0 100644 --- a/surefire-its/src/test/resources/surefire-1153-includesAndSpecifiedTest/src/test/java/jiras/surefire1153/IncludedUT.java +++ b/surefire-its/src/test/resources/surefire-1153-includesAndSpecifiedTest/src/test/java/jiras/surefire1153/IncludedUT.java @@ -1,24 +1,5 @@ package jiras.surefire1153; -/* - * 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.junit.Test; public class IncludedUT diff --git a/surefire-its/src/test/resources/surefire-1153-includesAndSpecifiedTest/src/test/java/jiras/surefire1153/NotIncludedTest.java b/surefire-its/src/test/resources/surefire-1153-includesAndSpecifiedTest/src/test/java/jiras/surefire1153/NotIncludedTest.java index b03d0aff85..39328bfe46 100644 --- a/surefire-its/src/test/resources/surefire-1153-includesAndSpecifiedTest/src/test/java/jiras/surefire1153/NotIncludedTest.java +++ b/surefire-its/src/test/resources/surefire-1153-includesAndSpecifiedTest/src/test/java/jiras/surefire1153/NotIncludedTest.java @@ -1,24 +1,5 @@ package jiras.surefire1153; -/* - * 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.junit.Test; public class NotIncludedTest diff --git a/surefire-its/src/test/resources/surefire-1158-remove-info-lines/src/test/java/jira1158/JUnitTest.java b/surefire-its/src/test/resources/surefire-1158-remove-info-lines/src/test/java/jira1158/JUnitTest.java index 5bfb83457d..1d1c23f57b 100644 --- a/surefire-its/src/test/resources/surefire-1158-remove-info-lines/src/test/java/jira1158/JUnitTest.java +++ b/surefire-its/src/test/resources/surefire-1158-remove-info-lines/src/test/java/jira1158/JUnitTest.java @@ -1,24 +1,5 @@ package jira1158; -/* - * 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.junit.Test; public class JUnitTest { diff --git a/surefire-its/src/test/resources/surefire-1158-remove-info-lines/src/test/java/jira1158/TestNGSuiteTest.java b/surefire-its/src/test/resources/surefire-1158-remove-info-lines/src/test/java/jira1158/TestNGSuiteTest.java index 65cc8c40d3..00fa52a8b2 100644 --- a/surefire-its/src/test/resources/surefire-1158-remove-info-lines/src/test/java/jira1158/TestNGSuiteTest.java +++ b/surefire-its/src/test/resources/surefire-1158-remove-info-lines/src/test/java/jira1158/TestNGSuiteTest.java @@ -1,24 +1,5 @@ package jira1158; -/* - * 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.testng.annotations.Test; diff --git a/surefire-its/src/test/resources/surefire-1185/src/test/java/pkg/RunningTest.java b/surefire-its/src/test/resources/surefire-1185/src/test/java/pkg/RunningTest.java index 2469bd3155..2da109d8eb 100644 --- a/surefire-its/src/test/resources/surefire-1185/src/test/java/pkg/RunningTest.java +++ b/surefire-its/src/test/resources/surefire-1185/src/test/java/pkg/RunningTest.java @@ -1,24 +1,5 @@ package pkg; -/* - * 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.junit.Test; public class RunningTest { diff --git a/surefire-its/src/test/resources/surefire-1185/src/test/java/pkg/UnlistedTest.java b/surefire-its/src/test/resources/surefire-1185/src/test/java/pkg/UnlistedTest.java index 8348673163..48a8c9f46a 100644 --- a/surefire-its/src/test/resources/surefire-1185/src/test/java/pkg/UnlistedTest.java +++ b/surefire-its/src/test/resources/surefire-1185/src/test/java/pkg/UnlistedTest.java @@ -1,24 +1,5 @@ package pkg; -/* - * 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.junit.Test; public class UnlistedTest { diff --git a/surefire-its/src/test/resources/surefire-1202-rerun-and-failfast/src/test/java/pkg/ATest.java b/surefire-its/src/test/resources/surefire-1202-rerun-and-failfast/src/test/java/pkg/ATest.java index cbe3f6f541..46535aa3dc 100644 --- a/surefire-its/src/test/resources/surefire-1202-rerun-and-failfast/src/test/java/pkg/ATest.java +++ b/surefire-its/src/test/resources/surefire-1202-rerun-and-failfast/src/test/java/pkg/ATest.java @@ -1,24 +1,5 @@ package pkg; -/* - * 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.junit.Test; import static java.util.concurrent.TimeUnit.MILLISECONDS; @@ -42,4 +23,4 @@ public void testA() } SECONDS.sleep( 5 ); } -} \ No newline at end of file +} diff --git a/surefire-its/src/test/resources/surefire-1202-rerun-and-failfast/src/test/java/pkg/BTest.java b/surefire-its/src/test/resources/surefire-1202-rerun-and-failfast/src/test/java/pkg/BTest.java index f44d396da5..8a7efead7b 100644 --- a/surefire-its/src/test/resources/surefire-1202-rerun-and-failfast/src/test/java/pkg/BTest.java +++ b/surefire-its/src/test/resources/surefire-1202-rerun-and-failfast/src/test/java/pkg/BTest.java @@ -1,24 +1,5 @@ package pkg; -/* - * 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.junit.Test; import static java.util.concurrent.TimeUnit.SECONDS; diff --git a/surefire-its/src/test/resources/surefire-1202-rerun-and-failfast/src/test/java/pkg/CTest.java b/surefire-its/src/test/resources/surefire-1202-rerun-and-failfast/src/test/java/pkg/CTest.java index e51a29d2a4..18f6ec547c 100644 --- a/surefire-its/src/test/resources/surefire-1202-rerun-and-failfast/src/test/java/pkg/CTest.java +++ b/surefire-its/src/test/resources/surefire-1202-rerun-and-failfast/src/test/java/pkg/CTest.java @@ -1,24 +1,5 @@ package pkg; -/* - * 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.junit.Test; import static java.util.concurrent.TimeUnit.MILLISECONDS; diff --git a/surefire-its/src/test/resources/surefire-1202-rerun-and-failfast/src/test/java/pkg/DTest.java b/surefire-its/src/test/resources/surefire-1202-rerun-and-failfast/src/test/java/pkg/DTest.java index 85bc666093..64d5a66aaf 100644 --- a/surefire-its/src/test/resources/surefire-1202-rerun-and-failfast/src/test/java/pkg/DTest.java +++ b/surefire-its/src/test/resources/surefire-1202-rerun-and-failfast/src/test/java/pkg/DTest.java @@ -1,24 +1,5 @@ package pkg; -/* - * 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.junit.Test; import static java.util.concurrent.TimeUnit.MILLISECONDS; diff --git a/surefire-its/src/test/resources/surefire-1202-rerun-and-failfast/src/test/java/pkg/ETest.java b/surefire-its/src/test/resources/surefire-1202-rerun-and-failfast/src/test/java/pkg/ETest.java index a74e73482e..192ab20254 100644 --- a/surefire-its/src/test/resources/surefire-1202-rerun-and-failfast/src/test/java/pkg/ETest.java +++ b/surefire-its/src/test/resources/surefire-1202-rerun-and-failfast/src/test/java/pkg/ETest.java @@ -1,24 +1,5 @@ package pkg; -/* - * 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.junit.Test; public class ETest diff --git a/surefire-its/src/test/resources/surefire-1209-rerun-and-forkcount/src/test/java/pkg/ATest.java b/surefire-its/src/test/resources/surefire-1209-rerun-and-forkcount/src/test/java/pkg/ATest.java index cbe3f6f541..46535aa3dc 100644 --- a/surefire-its/src/test/resources/surefire-1209-rerun-and-forkcount/src/test/java/pkg/ATest.java +++ b/surefire-its/src/test/resources/surefire-1209-rerun-and-forkcount/src/test/java/pkg/ATest.java @@ -1,24 +1,5 @@ package pkg; -/* - * 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.junit.Test; import static java.util.concurrent.TimeUnit.MILLISECONDS; @@ -42,4 +23,4 @@ public void testA() } SECONDS.sleep( 5 ); } -} \ No newline at end of file +} diff --git a/surefire-its/src/test/resources/surefire-1209-rerun-and-forkcount/src/test/java/pkg/BTest.java b/surefire-its/src/test/resources/surefire-1209-rerun-and-forkcount/src/test/java/pkg/BTest.java index f44d396da5..8a7efead7b 100644 --- a/surefire-its/src/test/resources/surefire-1209-rerun-and-forkcount/src/test/java/pkg/BTest.java +++ b/surefire-its/src/test/resources/surefire-1209-rerun-and-forkcount/src/test/java/pkg/BTest.java @@ -1,24 +1,5 @@ package pkg; -/* - * 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.junit.Test; import static java.util.concurrent.TimeUnit.SECONDS; diff --git a/surefire-its/src/test/resources/surefire-1209-rerun-and-forkcount/src/test/java/pkg/CTest.java b/surefire-its/src/test/resources/surefire-1209-rerun-and-forkcount/src/test/java/pkg/CTest.java index e51a29d2a4..18f6ec547c 100644 --- a/surefire-its/src/test/resources/surefire-1209-rerun-and-forkcount/src/test/java/pkg/CTest.java +++ b/surefire-its/src/test/resources/surefire-1209-rerun-and-forkcount/src/test/java/pkg/CTest.java @@ -1,24 +1,5 @@ package pkg; -/* - * 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.junit.Test; import static java.util.concurrent.TimeUnit.MILLISECONDS; diff --git a/surefire-its/src/test/resources/surefire-1209-rerun-and-forkcount/src/test/java/pkg/DTest.java b/surefire-its/src/test/resources/surefire-1209-rerun-and-forkcount/src/test/java/pkg/DTest.java index 85bc666093..64d5a66aaf 100644 --- a/surefire-its/src/test/resources/surefire-1209-rerun-and-forkcount/src/test/java/pkg/DTest.java +++ b/surefire-its/src/test/resources/surefire-1209-rerun-and-forkcount/src/test/java/pkg/DTest.java @@ -1,24 +1,5 @@ package pkg; -/* - * 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.junit.Test; import static java.util.concurrent.TimeUnit.MILLISECONDS; diff --git a/surefire-its/src/test/resources/surefire-1209-rerun-and-forkcount/src/test/java/pkg/ETest.java b/surefire-its/src/test/resources/surefire-1209-rerun-and-forkcount/src/test/java/pkg/ETest.java index a74e73482e..192ab20254 100644 --- a/surefire-its/src/test/resources/surefire-1209-rerun-and-forkcount/src/test/java/pkg/ETest.java +++ b/surefire-its/src/test/resources/surefire-1209-rerun-and-forkcount/src/test/java/pkg/ETest.java @@ -1,24 +1,5 @@ package pkg; -/* - * 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.junit.Test; public class ETest diff --git a/surefire-its/src/test/resources/surefire-1211/src/test/java/jira1211/JUnitTest.java b/surefire-its/src/test/resources/surefire-1211/src/test/java/jira1211/JUnitTest.java index 1580e8a538..4c264d0dbd 100644 --- a/surefire-its/src/test/resources/surefire-1211/src/test/java/jira1211/JUnitTest.java +++ b/surefire-its/src/test/resources/surefire-1211/src/test/java/jira1211/JUnitTest.java @@ -1,24 +1,5 @@ package jira1211; -/* - * 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.junit.Test; public class JUnitTest { diff --git a/surefire-its/src/test/resources/surefire-1211/src/test/java/jira1211/TestNGSuiteTest.java b/surefire-its/src/test/resources/surefire-1211/src/test/java/jira1211/TestNGSuiteTest.java index 46959c75c0..99a571c99c 100644 --- a/surefire-its/src/test/resources/surefire-1211/src/test/java/jira1211/TestNGSuiteTest.java +++ b/surefire-its/src/test/resources/surefire-1211/src/test/java/jira1211/TestNGSuiteTest.java @@ -1,24 +1,5 @@ package jira1211; -/* - * 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.testng.annotations.Test; diff --git a/surefire-its/src/test/resources/surefire-1260-new-tests-pattern/src/test/java/pkg/JUnit3Tests.java b/surefire-its/src/test/resources/surefire-1260-new-tests-pattern/src/test/java/pkg/JUnit3Tests.java index d607a3bc96..9e88755069 100644 --- a/surefire-its/src/test/resources/surefire-1260-new-tests-pattern/src/test/java/pkg/JUnit3Tests.java +++ b/surefire-its/src/test/resources/surefire-1260-new-tests-pattern/src/test/java/pkg/JUnit3Tests.java @@ -1,24 +1,5 @@ package pkg; -/* - * 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 junit.framework.TestCase; public class JUnit3Tests extends TestCase diff --git a/surefire-its/src/test/resources/surefire-1260-new-tests-pattern/src/test/java/pkg/JUnit4Tests.java b/surefire-its/src/test/resources/surefire-1260-new-tests-pattern/src/test/java/pkg/JUnit4Tests.java index f34aee7dca..ed1c56154a 100644 --- a/surefire-its/src/test/resources/surefire-1260-new-tests-pattern/src/test/java/pkg/JUnit4Tests.java +++ b/surefire-its/src/test/resources/surefire-1260-new-tests-pattern/src/test/java/pkg/JUnit4Tests.java @@ -1,24 +1,5 @@ package pkg; -/* - * 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.junit.Test; public class JUnit4Tests diff --git a/surefire-its/src/test/resources/surefire-1278-group-name-ending/src/test/java/pkg/ATest.java b/surefire-its/src/test/resources/surefire-1278-group-name-ending/src/test/java/pkg/ATest.java index 28c7e30059..281a02867b 100644 --- a/surefire-its/src/test/resources/surefire-1278-group-name-ending/src/test/java/pkg/ATest.java +++ b/surefire-its/src/test/resources/surefire-1278-group-name-ending/src/test/java/pkg/ATest.java @@ -1,24 +1,5 @@ package pkg; -/* - * 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.testng.Assert; import org.testng.annotations.Test; diff --git a/surefire-its/src/test/resources/surefire-1364/src/test/java/FirstTest.java b/surefire-its/src/test/resources/surefire-1364/src/test/java/FirstTest.java index f2a9e66b32..2099f0df35 100644 --- a/surefire-its/src/test/resources/surefire-1364/src/test/java/FirstTest.java +++ b/surefire-its/src/test/resources/surefire-1364/src/test/java/FirstTest.java @@ -1,22 +1,3 @@ -/* - * 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 junit.framework.TestCase; import org.junit.Test; diff --git a/surefire-its/src/test/resources/surefire-1364/src/test/java/SecondTest.java b/surefire-its/src/test/resources/surefire-1364/src/test/java/SecondTest.java index cfd9b51ed8..07c5a2c656 100644 --- a/surefire-its/src/test/resources/surefire-1364/src/test/java/SecondTest.java +++ b/surefire-its/src/test/resources/surefire-1364/src/test/java/SecondTest.java @@ -1,22 +1,3 @@ -/* - * 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 junit.framework.TestCase; import org.junit.Test; diff --git a/surefire-its/src/test/resources/surefire-1364/src/test/java/ThirdTest.java b/surefire-its/src/test/resources/surefire-1364/src/test/java/ThirdTest.java index f3633d6a23..fd97274f2d 100644 --- a/surefire-its/src/test/resources/surefire-1364/src/test/java/ThirdTest.java +++ b/surefire-its/src/test/resources/surefire-1364/src/test/java/ThirdTest.java @@ -1,22 +1,3 @@ -/* - * 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.testng.annotations.Test; @@ -27,4 +8,4 @@ public void test() throws InterruptedException { Thread.sleep( 100 ); } -} \ No newline at end of file +} diff --git a/surefire-its/src/test/resources/surefire-1367/src/test/java/ATest.java b/surefire-its/src/test/resources/surefire-1367/src/test/java/ATest.java index df5231e7ec..0c4a54c2f0 100644 --- a/surefire-its/src/test/resources/surefire-1367/src/test/java/ATest.java +++ b/surefire-its/src/test/resources/surefire-1367/src/test/java/ATest.java @@ -1,22 +1,3 @@ -/* - * 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.junit.Test; import static org.junit.Assume.assumeTrue; diff --git a/surefire-its/src/test/resources/surefire-1367/src/test/java/BTest.java b/surefire-its/src/test/resources/surefire-1367/src/test/java/BTest.java index bec4da8cd4..4a33929a0a 100644 --- a/surefire-its/src/test/resources/surefire-1367/src/test/java/BTest.java +++ b/surefire-its/src/test/resources/surefire-1367/src/test/java/BTest.java @@ -1,22 +1,3 @@ -/* - * 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.junit.Test; import static org.junit.Assume.assumeTrue; diff --git a/surefire-its/src/test/resources/surefire-1383/runner/src/main/java/pkg/DynamicRunningTest.java b/surefire-its/src/test/resources/surefire-1383/runner/src/main/java/pkg/DynamicRunningTest.java index 1b37af5c14..ef486b759b 100644 --- a/surefire-its/src/test/resources/surefire-1383/runner/src/main/java/pkg/DynamicRunningTest.java +++ b/surefire-its/src/test/resources/surefire-1383/runner/src/main/java/pkg/DynamicRunningTest.java @@ -1,23 +1,4 @@ package pkg; -/* - * 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.testng.annotations.Test; @Test diff --git a/surefire-its/src/test/resources/surefire-1396-pluggableproviders-classpath-provider/src/main/java/org/apache/maven/surefire/testprovider/ClassPathTestProvider.java b/surefire-its/src/test/resources/surefire-1396-pluggableproviders-classpath-provider/src/main/java/org/apache/maven/surefire/testprovider/ClassPathTestProvider.java index 5d9d44809f..46b9850318 100644 --- a/surefire-its/src/test/resources/surefire-1396-pluggableproviders-classpath-provider/src/main/java/org/apache/maven/surefire/testprovider/ClassPathTestProvider.java +++ b/surefire-its/src/test/resources/surefire-1396-pluggableproviders-classpath-provider/src/main/java/org/apache/maven/surefire/testprovider/ClassPathTestProvider.java @@ -1,24 +1,5 @@ package org.apache.maven.surefire.testprovider; -/* - * 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 java.lang.reflect.InvocationTargetException; import java.util.Collections; import java.util.Map.Entry; diff --git a/surefire-its/src/test/resources/surefire-141-pluggableproviders-provider/src/main/java/org/apache/maven/surefire/testprovider/TestProvider.java b/surefire-its/src/test/resources/surefire-141-pluggableproviders-provider/src/main/java/org/apache/maven/surefire/testprovider/TestProvider.java index 85a1f141c3..01842f6246 100644 --- a/surefire-its/src/test/resources/surefire-141-pluggableproviders-provider/src/main/java/org/apache/maven/surefire/testprovider/TestProvider.java +++ b/surefire-its/src/test/resources/surefire-141-pluggableproviders-provider/src/main/java/org/apache/maven/surefire/testprovider/TestProvider.java @@ -1,24 +1,5 @@ package org.apache.maven.surefire.testprovider; -/* - * 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.maven.surefire.api.provider.AbstractProvider; import org.apache.maven.surefire.api.provider.ProviderParameters; import org.apache.maven.surefire.api.report.ReporterException; diff --git a/surefire-its/src/test/resources/surefire-141-pluggableproviders/src/test/java/surefire141/BasicTest.java b/surefire-its/src/test/resources/surefire-141-pluggableproviders/src/test/java/surefire141/BasicTest.java index acf8bb3f00..dab0f556e7 100644 --- a/surefire-its/src/test/resources/surefire-141-pluggableproviders/src/test/java/surefire141/BasicTest.java +++ b/surefire-its/src/test/resources/surefire-141-pluggableproviders/src/test/java/surefire141/BasicTest.java @@ -1,24 +1,5 @@ package surefire141; -/* - * 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 junit.extensions.TestSetup; import junit.framework.Test; import junit.framework.TestCase; diff --git a/surefire-its/src/test/resources/surefire-141-pluggableproviders/src/test/java/surefire141/TestTwo.java b/surefire-its/src/test/resources/surefire-141-pluggableproviders/src/test/java/surefire141/TestTwo.java index 1768daf9bf..21e89966d9 100644 --- a/surefire-its/src/test/resources/surefire-141-pluggableproviders/src/test/java/surefire141/TestTwo.java +++ b/surefire-its/src/test/resources/surefire-141-pluggableproviders/src/test/java/surefire141/TestTwo.java @@ -1,24 +1,5 @@ package surefire141; -/* - * 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 junit.framework.TestCase; diff --git a/surefire-its/src/test/resources/surefire-146-forkPerTestNoSetup/src/test/java/forkPerTestNoSetup/TestSurefire2.java b/surefire-its/src/test/resources/surefire-146-forkPerTestNoSetup/src/test/java/forkPerTestNoSetup/TestSurefire2.java index 5810572141..146299511d 100644 --- a/surefire-its/src/test/resources/surefire-146-forkPerTestNoSetup/src/test/java/forkPerTestNoSetup/TestSurefire2.java +++ b/surefire-its/src/test/resources/surefire-146-forkPerTestNoSetup/src/test/java/forkPerTestNoSetup/TestSurefire2.java @@ -1,24 +1,5 @@ package forkPerTestNoSetup; -/* - * 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 junit.extensions.TestSetup; import junit.framework.Test; import junit.framework.TestCase; diff --git a/surefire-its/src/test/resources/surefire-1490/src/test/java/it/Surefire1490IT.java b/surefire-its/src/test/resources/surefire-1490/src/test/java/it/Surefire1490IT.java index 2a6818dcdf..399409dc65 100644 --- a/surefire-its/src/test/resources/surefire-1490/src/test/java/it/Surefire1490IT.java +++ b/surefire-its/src/test/resources/surefire-1490/src/test/java/it/Surefire1490IT.java @@ -1,24 +1,5 @@ package it; -/* - * 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.junit.Test; public class Surefire1490IT diff --git a/surefire-its/src/test/resources/surefire-1490/src/test/java/it/Surefire1490Test.java b/surefire-its/src/test/resources/surefire-1490/src/test/java/it/Surefire1490Test.java index 26de27f7c3..7f0b60e1cb 100644 --- a/surefire-its/src/test/resources/surefire-1490/src/test/java/it/Surefire1490Test.java +++ b/surefire-its/src/test/resources/surefire-1490/src/test/java/it/Surefire1490Test.java @@ -1,24 +1,5 @@ package it; -/* - * 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.junit.Test; public class Surefire1490Test diff --git a/surefire-its/src/test/resources/surefire-1535-parallel-testng/src/test/java/it/ParallelTest1.java b/surefire-its/src/test/resources/surefire-1535-parallel-testng/src/test/java/it/ParallelTest1.java index 0590851d30..d23bb277cf 100644 --- a/surefire-its/src/test/resources/surefire-1535-parallel-testng/src/test/java/it/ParallelTest1.java +++ b/surefire-its/src/test/resources/surefire-1535-parallel-testng/src/test/java/it/ParallelTest1.java @@ -1,24 +1,5 @@ package it; -/* - * 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.testng.Assert; import org.testng.annotations.Test; diff --git a/surefire-its/src/test/resources/surefire-1535-parallel-testng/src/test/java/it/ParallelTest2.java b/surefire-its/src/test/resources/surefire-1535-parallel-testng/src/test/java/it/ParallelTest2.java index 8467ea77a3..17b7837fbd 100644 --- a/surefire-its/src/test/resources/surefire-1535-parallel-testng/src/test/java/it/ParallelTest2.java +++ b/surefire-its/src/test/resources/surefire-1535-parallel-testng/src/test/java/it/ParallelTest2.java @@ -1,24 +1,5 @@ package it; -/* - * 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.testng.Assert; import org.testng.annotations.Test; diff --git a/surefire-its/src/test/resources/surefire-1570/com.foo.impl/src/main/java/com/foo/impl/Bar.java b/surefire-its/src/test/resources/surefire-1570/com.foo.impl/src/main/java/com/foo/impl/Bar.java index 50009e3bdc..0d7e25213c 100644 --- a/surefire-its/src/test/resources/surefire-1570/com.foo.impl/src/main/java/com/foo/impl/Bar.java +++ b/surefire-its/src/test/resources/surefire-1570/com.foo.impl/src/main/java/com/foo/impl/Bar.java @@ -1,24 +1,5 @@ package com.foo.impl; -/* - * 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 com.foo.api.SomeInterface; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/surefire-its/src/test/resources/surefire-1570/com.foo.impl/src/test/java/com/foo/impl/BarIT.java b/surefire-its/src/test/resources/surefire-1570/com.foo.impl/src/test/java/com/foo/impl/BarIT.java index 43596b76af..5d928a5e3d 100644 --- a/surefire-its/src/test/resources/surefire-1570/com.foo.impl/src/test/java/com/foo/impl/BarIT.java +++ b/surefire-its/src/test/resources/surefire-1570/com.foo.impl/src/test/java/com/foo/impl/BarIT.java @@ -1,24 +1,5 @@ package com.foo.impl; -/* - * 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.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/surefire-its/src/test/resources/surefire-1570/com.foo.impl/src/test/java/com/foo/impl/BarTest.java b/surefire-its/src/test/resources/surefire-1570/com.foo.impl/src/test/java/com/foo/impl/BarTest.java index 6e392b684b..6c268a4754 100644 --- a/surefire-its/src/test/resources/surefire-1570/com.foo.impl/src/test/java/com/foo/impl/BarTest.java +++ b/surefire-its/src/test/resources/surefire-1570/com.foo.impl/src/test/java/com/foo/impl/BarTest.java @@ -1,24 +1,5 @@ package com.foo.impl; -/* - * 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.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/surefire-its/src/test/resources/surefire-1585-junit4-vintage/src/test/java/JUnit4Test.java b/surefire-its/src/test/resources/surefire-1585-junit4-vintage/src/test/java/JUnit4Test.java index d0c1ff46c9..fd78db63e9 100644 --- a/surefire-its/src/test/resources/surefire-1585-junit4-vintage/src/test/java/JUnit4Test.java +++ b/surefire-its/src/test/resources/surefire-1585-junit4-vintage/src/test/java/JUnit4Test.java @@ -1,22 +1,3 @@ -/* - * 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.junit.Test; public class JUnit4Test diff --git a/surefire-its/src/test/resources/surefire-1585-jupiter-api/src/test/java/JupiterTest.java b/surefire-its/src/test/resources/surefire-1585-jupiter-api/src/test/java/JupiterTest.java index 398141c659..0f9de19f92 100644 --- a/surefire-its/src/test/resources/surefire-1585-jupiter-api/src/test/java/JupiterTest.java +++ b/surefire-its/src/test/resources/surefire-1585-jupiter-api/src/test/java/JupiterTest.java @@ -1,22 +1,3 @@ -/* - * 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 static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; diff --git a/surefire-its/src/test/resources/surefire-162-charsetProvider/src/test/java/charsetProvider/MSUREFIRE77TestCase.java b/surefire-its/src/test/resources/surefire-162-charsetProvider/src/test/java/charsetProvider/MSUREFIRE77TestCase.java index ef492dc83e..3a3ddb4bcc 100644 --- a/surefire-its/src/test/resources/surefire-162-charsetProvider/src/test/java/charsetProvider/MSUREFIRE77TestCase.java +++ b/surefire-its/src/test/resources/surefire-162-charsetProvider/src/test/java/charsetProvider/MSUREFIRE77TestCase.java @@ -1,24 +1,5 @@ package charsetProvider; -/* - * 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 java.io.UnsupportedEncodingException; import junit.framework.TestCase; diff --git a/surefire-its/src/test/resources/surefire-1688/src/test/java/jira1688/FailingBeforeAllJupiterTest.java b/surefire-its/src/test/resources/surefire-1688/src/test/java/jira1688/FailingBeforeAllJupiterTest.java index 2159a52134..3dd7fb4d4e 100644 --- a/surefire-its/src/test/resources/surefire-1688/src/test/java/jira1688/FailingBeforeAllJupiterTest.java +++ b/surefire-its/src/test/resources/surefire-1688/src/test/java/jira1688/FailingBeforeAllJupiterTest.java @@ -1,24 +1,5 @@ package jira1688; -/* - * 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 static org.junit.jupiter.api.Assertions.fail; import org.junit.jupiter.api.BeforeAll; diff --git a/surefire-its/src/test/resources/surefire-1712-extracted-modulename-without-asm/src/test/java/wtf/g4s8/oot/test/FooTest.java b/surefire-its/src/test/resources/surefire-1712-extracted-modulename-without-asm/src/test/java/wtf/g4s8/oot/test/FooTest.java index d8aa49dc38..03a63c4c49 100644 --- a/surefire-its/src/test/resources/surefire-1712-extracted-modulename-without-asm/src/test/java/wtf/g4s8/oot/test/FooTest.java +++ b/surefire-its/src/test/resources/surefire-1712-extracted-modulename-without-asm/src/test/java/wtf/g4s8/oot/test/FooTest.java @@ -1,24 +1,5 @@ package wtf.g4s8.oot.test; -/* - * 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.hamcrest.Matchers; import org.junit.jupiter.api.Test; import wtf.g4s8.oot.Foo; diff --git a/surefire-its/src/test/resources/surefire-1727/src/test/java/jira1727/ErrorInTestFactoryJupiterTest.java b/surefire-its/src/test/resources/surefire-1727/src/test/java/jira1727/ErrorInTestFactoryJupiterTest.java index 97f5f0de26..f6216613db 100644 --- a/surefire-its/src/test/resources/surefire-1727/src/test/java/jira1727/ErrorInTestFactoryJupiterTest.java +++ b/surefire-its/src/test/resources/surefire-1727/src/test/java/jira1727/ErrorInTestFactoryJupiterTest.java @@ -1,24 +1,5 @@ package jira1727; -/* - * 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.junit.jupiter.api.DynamicTest; import org.junit.jupiter.api.TestFactory; diff --git a/surefire-its/src/test/resources/surefire-1727/src/test/java/jira1727/ErrorInTestProvider.java b/surefire-its/src/test/resources/surefire-1727/src/test/java/jira1727/ErrorInTestProvider.java index a2134265bb..348b1d91b1 100644 --- a/surefire-its/src/test/resources/surefire-1727/src/test/java/jira1727/ErrorInTestProvider.java +++ b/surefire-its/src/test/resources/surefire-1727/src/test/java/jira1727/ErrorInTestProvider.java @@ -1,24 +1,5 @@ package jira1727; -/* - * 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.junit.jupiter.api.extension.ExtensionContext; import org.junit.jupiter.api.extension.TestTemplateInvocationContext; import org.junit.jupiter.api.extension.TestTemplateInvocationContextProvider; diff --git a/surefire-its/src/test/resources/surefire-1727/src/test/java/jira1727/ErrorInTestTemplateProviderTest.java b/surefire-its/src/test/resources/surefire-1727/src/test/java/jira1727/ErrorInTestTemplateProviderTest.java index 21dcef1dbf..647914eac8 100644 --- a/surefire-its/src/test/resources/surefire-1727/src/test/java/jira1727/ErrorInTestTemplateProviderTest.java +++ b/surefire-its/src/test/resources/surefire-1727/src/test/java/jira1727/ErrorInTestTemplateProviderTest.java @@ -1,24 +1,5 @@ package jira1727; -/* - * 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.junit.jupiter.api.TestTemplate; import org.junit.jupiter.api.extension.ExtendWith; diff --git a/surefire-its/src/test/resources/surefire-1727/src/test/java/jira1727/FailureInTestFactoryJupiterTest.java b/surefire-its/src/test/resources/surefire-1727/src/test/java/jira1727/FailureInTestFactoryJupiterTest.java index bd9c292b78..1b0c245360 100644 --- a/surefire-its/src/test/resources/surefire-1727/src/test/java/jira1727/FailureInTestFactoryJupiterTest.java +++ b/surefire-its/src/test/resources/surefire-1727/src/test/java/jira1727/FailureInTestFactoryJupiterTest.java @@ -1,24 +1,5 @@ package jira1727; -/* - * 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.junit.jupiter.api.DynamicTest; import org.junit.jupiter.api.TestFactory; diff --git a/surefire-its/src/test/resources/surefire-1727/src/test/java/jira1727/FailureInTestProvider.java b/surefire-its/src/test/resources/surefire-1727/src/test/java/jira1727/FailureInTestProvider.java index 7a76e97399..b45d3ee09a 100644 --- a/surefire-its/src/test/resources/surefire-1727/src/test/java/jira1727/FailureInTestProvider.java +++ b/surefire-its/src/test/resources/surefire-1727/src/test/java/jira1727/FailureInTestProvider.java @@ -1,24 +1,5 @@ package jira1727; -/* - * 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.junit.jupiter.api.extension.ExtensionContext; import org.junit.jupiter.api.extension.TestTemplateInvocationContext; import org.junit.jupiter.api.extension.TestTemplateInvocationContextProvider; diff --git a/surefire-its/src/test/resources/surefire-1727/src/test/java/jira1727/FailureInTestTemplateProviderTest.java b/surefire-its/src/test/resources/surefire-1727/src/test/java/jira1727/FailureInTestTemplateProviderTest.java index 5ef3da07a2..bca0c1a448 100644 --- a/surefire-its/src/test/resources/surefire-1727/src/test/java/jira1727/FailureInTestTemplateProviderTest.java +++ b/surefire-its/src/test/resources/surefire-1727/src/test/java/jira1727/FailureInTestTemplateProviderTest.java @@ -1,24 +1,5 @@ package jira1727; -/* - * 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.junit.jupiter.api.TestTemplate; import org.junit.jupiter.api.extension.ExtendWith; diff --git a/surefire-its/src/test/resources/surefire-1733-junit4/src/main/java/main/Service.java b/surefire-its/src/test/resources/surefire-1733-junit4/src/main/java/main/Service.java index 03e83400dc..413bc9899a 100644 --- a/surefire-its/src/test/resources/surefire-1733-junit4/src/main/java/main/Service.java +++ b/surefire-its/src/test/resources/surefire-1733-junit4/src/main/java/main/Service.java @@ -1,24 +1,5 @@ package main; -/* - * 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 java.io.IOException; import java.util.Scanner; diff --git a/surefire-its/src/test/resources/surefire-1733-junit4/src/test/java/test/MyIT.java b/surefire-its/src/test/resources/surefire-1733-junit4/src/test/java/test/MyIT.java index c36a356521..1d63f1ac76 100644 --- a/surefire-its/src/test/resources/surefire-1733-junit4/src/test/java/test/MyIT.java +++ b/surefire-its/src/test/resources/surefire-1733-junit4/src/test/java/test/MyIT.java @@ -1,24 +1,5 @@ package test; -/* - * 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 main.Service; import org.junit.Test; diff --git a/surefire-its/src/test/resources/surefire-1733-junit4/src/test/java/test/MyTest.java b/surefire-its/src/test/resources/surefire-1733-junit4/src/test/java/test/MyTest.java index 28c190d429..404658a91f 100644 --- a/surefire-its/src/test/resources/surefire-1733-junit4/src/test/java/test/MyTest.java +++ b/surefire-its/src/test/resources/surefire-1733-junit4/src/test/java/test/MyTest.java @@ -1,24 +1,5 @@ package test; -/* - * 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 main.Service; import org.junit.Test; diff --git a/surefire-its/src/test/resources/surefire-1733-testng/src/test/java/test/MyIT.java b/surefire-its/src/test/resources/surefire-1733-testng/src/test/java/test/MyIT.java index 534672dc0f..6016944b3c 100644 --- a/surefire-its/src/test/resources/surefire-1733-testng/src/test/java/test/MyIT.java +++ b/surefire-its/src/test/resources/surefire-1733-testng/src/test/java/test/MyIT.java @@ -1,24 +1,5 @@ package test; -/* - * 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 main.Service; import org.testng.annotations.Test; diff --git a/surefire-its/src/test/resources/surefire-1733-testng/src/test/java/test/MyTest.java b/surefire-its/src/test/resources/surefire-1733-testng/src/test/java/test/MyTest.java index c13d1f17f4..1e485da6ef 100644 --- a/surefire-its/src/test/resources/surefire-1733-testng/src/test/java/test/MyTest.java +++ b/surefire-its/src/test/resources/surefire-1733-testng/src/test/java/test/MyTest.java @@ -1,24 +1,5 @@ package test; -/* - * 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 main.Service; import org.testng.annotations.Test; diff --git a/surefire-its/src/test/resources/surefire-1741/src/test/java/jira1741/ErrorInBeforeAllJupiterTest.java b/surefire-its/src/test/resources/surefire-1741/src/test/java/jira1741/ErrorInBeforeAllJupiterTest.java index 09e0222720..79bdf30076 100644 --- a/surefire-its/src/test/resources/surefire-1741/src/test/java/jira1741/ErrorInBeforeAllJupiterTest.java +++ b/surefire-its/src/test/resources/surefire-1741/src/test/java/jira1741/ErrorInBeforeAllJupiterTest.java @@ -1,24 +1,5 @@ package jira1741; -/* - * 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.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; diff --git a/surefire-its/src/test/resources/surefire-1741/src/test/java/jira1741/ErrorInParameterizedSourceJupiterTest.java b/surefire-its/src/test/resources/surefire-1741/src/test/java/jira1741/ErrorInParameterizedSourceJupiterTest.java index 17902e6c9b..b3d217c975 100644 --- a/surefire-its/src/test/resources/surefire-1741/src/test/java/jira1741/ErrorInParameterizedSourceJupiterTest.java +++ b/surefire-its/src/test/resources/surefire-1741/src/test/java/jira1741/ErrorInParameterizedSourceJupiterTest.java @@ -1,24 +1,5 @@ package jira1741; -/* - * 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 java.util.stream.Stream; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; diff --git a/surefire-its/src/test/resources/surefire-1741/src/test/java/jira1741/FailureInParameterizedSourceJupiterTest.java b/surefire-its/src/test/resources/surefire-1741/src/test/java/jira1741/FailureInParameterizedSourceJupiterTest.java index 4232c783c3..a24b80331b 100644 --- a/surefire-its/src/test/resources/surefire-1741/src/test/java/jira1741/FailureInParameterizedSourceJupiterTest.java +++ b/surefire-its/src/test/resources/surefire-1741/src/test/java/jira1741/FailureInParameterizedSourceJupiterTest.java @@ -1,24 +1,5 @@ package jira1741; -/* - * 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 java.util.stream.Stream; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; diff --git a/surefire-its/src/test/resources/surefire-1744-alwaysIncludeOutputLogs/src/test/java/alwaysIncludeOutputLogs/TestSurefire3.java b/surefire-its/src/test/resources/surefire-1744-alwaysIncludeOutputLogs/src/test/java/alwaysIncludeOutputLogs/TestSurefire3.java index 0f0345b304..3bf537352d 100644 --- a/surefire-its/src/test/resources/surefire-1744-alwaysIncludeOutputLogs/src/test/java/alwaysIncludeOutputLogs/TestSurefire3.java +++ b/surefire-its/src/test/resources/surefire-1744-alwaysIncludeOutputLogs/src/test/java/alwaysIncludeOutputLogs/TestSurefire3.java @@ -1,24 +1,5 @@ package alwaysIncludeOutputLogs; -/* - * 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.junit.Test; import org.apache.log4j.Logger; public class TestSurefire3 diff --git a/surefire-its/src/test/resources/surefire-1748-fail-no-parameters/src/test/java/jira1748/AssertionsFailNoParametersJupiterTest.java b/surefire-its/src/test/resources/surefire-1748-fail-no-parameters/src/test/java/jira1748/AssertionsFailNoParametersJupiterTest.java index e8569a9344..083155dcea 100644 --- a/surefire-its/src/test/resources/surefire-1748-fail-no-parameters/src/test/java/jira1748/AssertionsFailNoParametersJupiterTest.java +++ b/surefire-its/src/test/resources/surefire-1748-fail-no-parameters/src/test/java/jira1748/AssertionsFailNoParametersJupiterTest.java @@ -1,24 +1,5 @@ package jira1748; -/* - * 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.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.fail; diff --git a/surefire-its/src/test/resources/surefire-1748/src/test/java/jira1748/AssertionsFailEmptyStringParameterJupiterTest.java b/surefire-its/src/test/resources/surefire-1748/src/test/java/jira1748/AssertionsFailEmptyStringParameterJupiterTest.java index b82823a344..15106907a3 100644 --- a/surefire-its/src/test/resources/surefire-1748/src/test/java/jira1748/AssertionsFailEmptyStringParameterJupiterTest.java +++ b/surefire-its/src/test/resources/surefire-1748/src/test/java/jira1748/AssertionsFailEmptyStringParameterJupiterTest.java @@ -1,24 +1,5 @@ package jira1748; -/* - * 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.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.fail; diff --git a/surefire-its/src/test/resources/surefire-1857-assertion-message/src/test/java/jira1857/AssertionFailureMessageTest.java b/surefire-its/src/test/resources/surefire-1857-assertion-message/src/test/java/jira1857/AssertionFailureMessageTest.java index 60648cb11d..cc343c11a6 100644 --- a/surefire-its/src/test/resources/surefire-1857-assertion-message/src/test/java/jira1857/AssertionFailureMessageTest.java +++ b/surefire-its/src/test/resources/surefire-1857-assertion-message/src/test/java/jira1857/AssertionFailureMessageTest.java @@ -1,24 +1,5 @@ package jira1857; -/* - * 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.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.fail; diff --git a/surefire-its/src/test/resources/surefire-1857-exception-message/src/test/java/jira1857/ExceptionMessageTest.java b/surefire-its/src/test/resources/surefire-1857-exception-message/src/test/java/jira1857/ExceptionMessageTest.java index 8e316997bb..4ff737956c 100644 --- a/surefire-its/src/test/resources/surefire-1857-exception-message/src/test/java/jira1857/ExceptionMessageTest.java +++ b/surefire-its/src/test/resources/surefire-1857-exception-message/src/test/java/jira1857/ExceptionMessageTest.java @@ -1,24 +1,5 @@ package jira1857; -/* - * 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.junit.jupiter.api.Test; class ExceptionMessageTest diff --git a/surefire-its/src/test/resources/surefire-1914-xml-reporting-parameterizedtest/src/test/java/jira1914/ParameterizedDisplayNameTest.java b/surefire-its/src/test/resources/surefire-1914-xml-reporting-parameterizedtest/src/test/java/jira1914/ParameterizedDisplayNameTest.java index 579cb99b4f..ae4fb266e3 100644 --- a/surefire-its/src/test/resources/surefire-1914-xml-reporting-parameterizedtest/src/test/java/jira1914/ParameterizedDisplayNameTest.java +++ b/surefire-its/src/test/resources/surefire-1914-xml-reporting-parameterizedtest/src/test/java/jira1914/ParameterizedDisplayNameTest.java @@ -1,24 +1,5 @@ package jira1914; -/* - * 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.junit.jupiter.api.DisplayName; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; diff --git a/surefire-its/src/test/resources/surefire-1914-xml-reporting-parameterizedtest/src/test/java/jira1914/ParameterizedJupiterTest.java b/surefire-its/src/test/resources/surefire-1914-xml-reporting-parameterizedtest/src/test/java/jira1914/ParameterizedJupiterTest.java index 418ff43ae4..d513d888b3 100644 --- a/surefire-its/src/test/resources/surefire-1914-xml-reporting-parameterizedtest/src/test/java/jira1914/ParameterizedJupiterTest.java +++ b/surefire-its/src/test/resources/surefire-1914-xml-reporting-parameterizedtest/src/test/java/jira1914/ParameterizedJupiterTest.java @@ -1,24 +1,5 @@ package jira1914; -/* - * 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 static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.params.ParameterizedTest; diff --git a/surefire-its/src/test/resources/surefire-1993-jpms-providing-modules/application/src/main/java/org/apache/failsafe/its/serviceloader/application/StudentServiceLoader.java b/surefire-its/src/test/resources/surefire-1993-jpms-providing-modules/application/src/main/java/org/apache/failsafe/its/serviceloader/application/StudentServiceLoader.java index f30016f9b9..89dc6cded1 100644 --- a/surefire-its/src/test/resources/surefire-1993-jpms-providing-modules/application/src/main/java/org/apache/failsafe/its/serviceloader/application/StudentServiceLoader.java +++ b/surefire-its/src/test/resources/surefire-1993-jpms-providing-modules/application/src/main/java/org/apache/failsafe/its/serviceloader/application/StudentServiceLoader.java @@ -1,24 +1,5 @@ package org.apache.failsafe.its.serviceloader.application; -/* - * 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.failsafe.its.serviceloader.api.service.StudentService; import java.util.ArrayList; import java.util.List; diff --git a/surefire-its/src/test/resources/surefire-1993-jpms-providing-modules/application/src/main/java/org/apache/failsafe/its/serviceloader/application/TrainingApplication.java b/surefire-its/src/test/resources/surefire-1993-jpms-providing-modules/application/src/main/java/org/apache/failsafe/its/serviceloader/application/TrainingApplication.java index 58f810cdf1..acfa6656d1 100644 --- a/surefire-its/src/test/resources/surefire-1993-jpms-providing-modules/application/src/main/java/org/apache/failsafe/its/serviceloader/application/TrainingApplication.java +++ b/surefire-its/src/test/resources/surefire-1993-jpms-providing-modules/application/src/main/java/org/apache/failsafe/its/serviceloader/application/TrainingApplication.java @@ -1,24 +1,5 @@ package org.apache.failsafe.its.serviceloader.application; -/* - * 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.failsafe.its.serviceloader.api.model.Student; import org.apache.failsafe.its.serviceloader.api.service.StudentService; diff --git a/surefire-its/src/test/resources/surefire-1993-jpms-providing-modules/application/src/test/java/org/apache/failsafe/its/serviceloader/application/TrainingApplicationIT.java b/surefire-its/src/test/resources/surefire-1993-jpms-providing-modules/application/src/test/java/org/apache/failsafe/its/serviceloader/application/TrainingApplicationIT.java index debfe5f5ff..8d38584159 100644 --- a/surefire-its/src/test/resources/surefire-1993-jpms-providing-modules/application/src/test/java/org/apache/failsafe/its/serviceloader/application/TrainingApplicationIT.java +++ b/surefire-its/src/test/resources/surefire-1993-jpms-providing-modules/application/src/test/java/org/apache/failsafe/its/serviceloader/application/TrainingApplicationIT.java @@ -1,24 +1,5 @@ package org.apache.failsafe.its.serviceloader.application; -/* - * 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.failsafe.its.serviceloader.api.model.Student; import org.junit.jupiter.api.Test; diff --git a/surefire-its/src/test/resources/surefire-1993-jpms-providing-modules/studentservice-provider/src/main/java/org/apache/failsafe/its/serviceloader/provider/internal/InternalStudentService.java b/surefire-its/src/test/resources/surefire-1993-jpms-providing-modules/studentservice-provider/src/main/java/org/apache/failsafe/its/serviceloader/provider/internal/InternalStudentService.java index 197512d744..0caa3f237e 100644 --- a/surefire-its/src/test/resources/surefire-1993-jpms-providing-modules/studentservice-provider/src/main/java/org/apache/failsafe/its/serviceloader/provider/internal/InternalStudentService.java +++ b/surefire-its/src/test/resources/surefire-1993-jpms-providing-modules/studentservice-provider/src/main/java/org/apache/failsafe/its/serviceloader/provider/internal/InternalStudentService.java @@ -1,24 +1,5 @@ package org.apache.failsafe.its.serviceloader.provider.internal; -/* - * 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.failsafe.its.serviceloader.api.model.Student; import java.util.Arrays; diff --git a/surefire-its/src/test/resources/surefire-1993-jpms-providing-modules/studentservice-provider/src/main/java/org/apache/failsafe/its/serviceloader/provider/service/StudentServiceImpl.java b/surefire-its/src/test/resources/surefire-1993-jpms-providing-modules/studentservice-provider/src/main/java/org/apache/failsafe/its/serviceloader/provider/service/StudentServiceImpl.java index c2ec8c4f16..a67c5315dd 100644 --- a/surefire-its/src/test/resources/surefire-1993-jpms-providing-modules/studentservice-provider/src/main/java/org/apache/failsafe/its/serviceloader/provider/service/StudentServiceImpl.java +++ b/surefire-its/src/test/resources/surefire-1993-jpms-providing-modules/studentservice-provider/src/main/java/org/apache/failsafe/its/serviceloader/provider/service/StudentServiceImpl.java @@ -1,24 +1,5 @@ package org.apache.failsafe.its.serviceloader.provider.service; -/* - * 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.failsafe.its.serviceloader.provider.internal.InternalStudentService; import org.apache.failsafe.its.serviceloader.api.model.Student; import org.apache.failsafe.its.serviceloader.api.service.StudentService; diff --git a/surefire-its/src/test/resources/surefire-1993-jpms-providing-modules/studentservice/src/main/java/org/apache/failsafe/its/serviceloader/api/service/StudentService.java b/surefire-its/src/test/resources/surefire-1993-jpms-providing-modules/studentservice/src/main/java/org/apache/failsafe/its/serviceloader/api/service/StudentService.java index 44afe26c08..499579d57f 100644 --- a/surefire-its/src/test/resources/surefire-1993-jpms-providing-modules/studentservice/src/main/java/org/apache/failsafe/its/serviceloader/api/service/StudentService.java +++ b/surefire-its/src/test/resources/surefire-1993-jpms-providing-modules/studentservice/src/main/java/org/apache/failsafe/its/serviceloader/api/service/StudentService.java @@ -1,24 +1,5 @@ package org.apache.failsafe.its.serviceloader.api.service; -/* - * 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.failsafe.its.serviceloader.api.model.Student; import java.util.List; diff --git a/surefire-its/src/test/resources/surefire-2117-xml-reporting-nested/src/test/java/jira2117/NestedDisplayNameTest.java b/surefire-its/src/test/resources/surefire-2117-xml-reporting-nested/src/test/java/jira2117/NestedDisplayNameTest.java index 7789ec839f..4ddc9fecec 100644 --- a/surefire-its/src/test/resources/surefire-2117-xml-reporting-nested/src/test/java/jira2117/NestedDisplayNameTest.java +++ b/surefire-its/src/test/resources/surefire-2117-xml-reporting-nested/src/test/java/jira2117/NestedDisplayNameTest.java @@ -1,24 +1,5 @@ package jira2117; -/* - * 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.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; diff --git a/surefire-its/src/test/resources/surefire-224-wellFormedXmlFailures/src/test/java/wellFormedXmlFailures/TestSurefire3.java b/surefire-its/src/test/resources/surefire-224-wellFormedXmlFailures/src/test/java/wellFormedXmlFailures/TestSurefire3.java index 20f2736fed..e92eab5b7c 100644 --- a/surefire-its/src/test/resources/surefire-224-wellFormedXmlFailures/src/test/java/wellFormedXmlFailures/TestSurefire3.java +++ b/surefire-its/src/test/resources/surefire-224-wellFormedXmlFailures/src/test/java/wellFormedXmlFailures/TestSurefire3.java @@ -1,24 +1,5 @@ package wellFormedXmlFailures; -/* - * 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 junit.extensions.TestSetup; import junit.framework.Test; import junit.framework.TestCase; diff --git a/surefire-its/src/test/resources/surefire-260-testWithIdenticalNames/src/test/java/surefire260/TestA.java b/surefire-its/src/test/resources/surefire-260-testWithIdenticalNames/src/test/java/surefire260/TestA.java index 3b52a449a3..7ba1208af1 100644 --- a/surefire-its/src/test/resources/surefire-260-testWithIdenticalNames/src/test/java/surefire260/TestA.java +++ b/surefire-its/src/test/resources/surefire-260-testWithIdenticalNames/src/test/java/surefire260/TestA.java @@ -1,24 +1,5 @@ package surefire260; -/* - * 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 junit.framework.TestCase; public class TestA diff --git a/surefire-its/src/test/resources/surefire-260-testWithIdenticalNames/src/test/java/surefire260/TestB.java b/surefire-its/src/test/resources/surefire-260-testWithIdenticalNames/src/test/java/surefire260/TestB.java index d06b7b2120..64a8e22a79 100644 --- a/surefire-its/src/test/resources/surefire-260-testWithIdenticalNames/src/test/java/surefire260/TestB.java +++ b/surefire-its/src/test/resources/surefire-260-testWithIdenticalNames/src/test/java/surefire260/TestB.java @@ -1,24 +1,5 @@ package surefire260; -/* - * 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 junit.framework.TestCase; public class TestB diff --git a/surefire-its/src/test/resources/surefire-260-testWithIdenticalNames/src/test/java/surefire260/TestC.java b/surefire-its/src/test/resources/surefire-260-testWithIdenticalNames/src/test/java/surefire260/TestC.java index a5050fb38a..c67eba05b2 100644 --- a/surefire-its/src/test/resources/surefire-260-testWithIdenticalNames/src/test/java/surefire260/TestC.java +++ b/surefire-its/src/test/resources/surefire-260-testWithIdenticalNames/src/test/java/surefire260/TestC.java @@ -1,24 +1,5 @@ package surefire260; -/* - * 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 junit.framework.TestCase; public class TestC diff --git a/surefire-its/src/test/resources/surefire-34-securityManager-success/src/test/java/junit4/SecurityManagerTest.java b/surefire-its/src/test/resources/surefire-34-securityManager-success/src/test/java/junit4/SecurityManagerTest.java index 3448502cfc..30c4c074ae 100644 --- a/surefire-its/src/test/resources/surefire-34-securityManager-success/src/test/java/junit4/SecurityManagerTest.java +++ b/surefire-its/src/test/resources/surefire-34-securityManager-success/src/test/java/junit4/SecurityManagerTest.java @@ -1,24 +1,5 @@ package junit4; -/* - * 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 junit.framework.TestCase; diff --git a/surefire-its/src/test/resources/surefire-34-securityManager/src/test/java/junit4/SecurityManagerTest.java b/surefire-its/src/test/resources/surefire-34-securityManager/src/test/java/junit4/SecurityManagerTest.java index 6fb992fcca..c4d9889202 100644 --- a/surefire-its/src/test/resources/surefire-34-securityManager/src/test/java/junit4/SecurityManagerTest.java +++ b/surefire-its/src/test/resources/surefire-34-securityManager/src/test/java/junit4/SecurityManagerTest.java @@ -1,24 +1,5 @@ package junit4; -/* - * 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 java.io.File; import junit.framework.TestCase; diff --git a/surefire-its/src/test/resources/surefire-408-manual-provider-selection/src/test/java/junit/twoTestCases/BasicTest.java b/surefire-its/src/test/resources/surefire-408-manual-provider-selection/src/test/java/junit/twoTestCases/BasicTest.java index 2efc5ed2af..e3ce320ba8 100644 --- a/surefire-its/src/test/resources/surefire-408-manual-provider-selection/src/test/java/junit/twoTestCases/BasicTest.java +++ b/surefire-its/src/test/resources/surefire-408-manual-provider-selection/src/test/java/junit/twoTestCases/BasicTest.java @@ -1,24 +1,5 @@ package junit.twoTestCases; -/* - * 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 junit.extensions.TestSetup; import junit.framework.Test; import junit.framework.TestCase; diff --git a/surefire-its/src/test/resources/surefire-408-manual-provider-selection/src/test/java/junit/twoTestCases/TestTwo.java b/surefire-its/src/test/resources/surefire-408-manual-provider-selection/src/test/java/junit/twoTestCases/TestTwo.java index 9af4558751..e6377b63e7 100644 --- a/surefire-its/src/test/resources/surefire-408-manual-provider-selection/src/test/java/junit/twoTestCases/TestTwo.java +++ b/surefire-its/src/test/resources/surefire-408-manual-provider-selection/src/test/java/junit/twoTestCases/TestTwo.java @@ -1,24 +1,5 @@ package junit.twoTestCases; -/* - * 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 junit.framework.TestCase; diff --git a/surefire-its/src/test/resources/surefire-500-puzzling-error/src/test/java/surefire500/ExplodingTest.java b/surefire-its/src/test/resources/surefire-500-puzzling-error/src/test/java/surefire500/ExplodingTest.java index 88164bf360..6588edd63a 100644 --- a/surefire-its/src/test/resources/surefire-500-puzzling-error/src/test/java/surefire500/ExplodingTest.java +++ b/surefire-its/src/test/resources/surefire-500-puzzling-error/src/test/java/surefire500/ExplodingTest.java @@ -1,24 +1,5 @@ package surefire500; -/* - * 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.junit.Test; import static org.junit.Assert.assertTrue; diff --git a/surefire-its/src/test/resources/surefire-569-RunTestFromDependencyJars/testjar/src/test/java/org/test/TestA.java b/surefire-its/src/test/resources/surefire-569-RunTestFromDependencyJars/testjar/src/test/java/org/test/TestA.java index 404377a728..8444815529 100644 --- a/surefire-its/src/test/resources/surefire-569-RunTestFromDependencyJars/testjar/src/test/java/org/test/TestA.java +++ b/surefire-its/src/test/resources/surefire-569-RunTestFromDependencyJars/testjar/src/test/java/org/test/TestA.java @@ -1,24 +1,5 @@ package org.test; -/* - * 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.junit.Test; public class TestA { @@ -26,4 +7,4 @@ public class TestA { @Test public void shouldRun() { } -} \ No newline at end of file +} diff --git a/surefire-its/src/test/resources/surefire-569-RunTestFromDependencyJars/testjar/src/test/java/org/test/TestB.java b/surefire-its/src/test/resources/surefire-569-RunTestFromDependencyJars/testjar/src/test/java/org/test/TestB.java index 1295e97f21..a5de75a270 100644 --- a/surefire-its/src/test/resources/surefire-569-RunTestFromDependencyJars/testjar/src/test/java/org/test/TestB.java +++ b/surefire-its/src/test/resources/surefire-569-RunTestFromDependencyJars/testjar/src/test/java/org/test/TestB.java @@ -1,24 +1,5 @@ package org.test; -/* - * 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.junit.Test; public class TestB { @@ -26,4 +7,4 @@ public class TestB { @Test public void shouldRun() { } -} \ No newline at end of file +} diff --git a/surefire-its/src/test/resources/surefire-613-testCount-in-parallel/src/test/java/surefire163/Test1.java b/surefire-its/src/test/resources/surefire-613-testCount-in-parallel/src/test/java/surefire163/Test1.java index 625663585c..a32678e437 100644 --- a/surefire-its/src/test/resources/surefire-613-testCount-in-parallel/src/test/java/surefire163/Test1.java +++ b/surefire-its/src/test/resources/surefire-613-testCount-in-parallel/src/test/java/surefire163/Test1.java @@ -1,24 +1,5 @@ package surefire613; -/* - * 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.junit.Test; import static org.junit.Assert.assertTrue; @@ -87,4 +68,4 @@ public void testWithFailingAssumption14() { public void testWithFailingAssumption15() { assumeThat( 2, is(3)); } -} \ No newline at end of file +} diff --git a/surefire-its/src/test/resources/surefire-613-testCount-in-parallel/src/test/java/surefire163/Test2.java b/surefire-its/src/test/resources/surefire-613-testCount-in-parallel/src/test/java/surefire163/Test2.java index c6d58402fa..c1c289d278 100644 --- a/surefire-its/src/test/resources/surefire-613-testCount-in-parallel/src/test/java/surefire163/Test2.java +++ b/surefire-its/src/test/resources/surefire-613-testCount-in-parallel/src/test/java/surefire163/Test2.java @@ -1,24 +1,5 @@ package surefire613; -/* - * 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.junit.Ignore; import org.junit.Test; @@ -124,4 +105,4 @@ public void testWithException8() throw new RuntimeException( "We expect this" ); } -} \ No newline at end of file +} diff --git a/surefire-its/src/test/resources/surefire-621-testCounting-junit3-in-parallel/src/it/java/mho/JUnit4AdapterSuiteTest.java b/surefire-its/src/test/resources/surefire-621-testCounting-junit3-in-parallel/src/it/java/mho/JUnit4AdapterSuiteTest.java index 47c2d75c58..a0e18fdaf8 100644 --- a/surefire-its/src/test/resources/surefire-621-testCounting-junit3-in-parallel/src/it/java/mho/JUnit4AdapterSuiteTest.java +++ b/surefire-its/src/test/resources/surefire-621-testCounting-junit3-in-parallel/src/it/java/mho/JUnit4AdapterSuiteTest.java @@ -1,24 +1,5 @@ package mho; -/* - * 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 junit.framework.JUnit4TestAdapter; import junit.framework.Test; import org.junit.runner.RunWith; diff --git a/surefire-its/src/test/resources/surefire-621-testCounting-junit3-in-parallel/src/it/java/mho/MySuiteTest1.java b/surefire-its/src/test/resources/surefire-621-testCounting-junit3-in-parallel/src/it/java/mho/MySuiteTest1.java index edd5781ca5..f836baaa43 100644 --- a/surefire-its/src/test/resources/surefire-621-testCounting-junit3-in-parallel/src/it/java/mho/MySuiteTest1.java +++ b/surefire-its/src/test/resources/surefire-621-testCounting-junit3-in-parallel/src/it/java/mho/MySuiteTest1.java @@ -1,24 +1,5 @@ package mho; -/* - * 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 junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; diff --git a/surefire-its/src/test/resources/surefire-621-testCounting-junit3-in-parallel/src/it/java/mho/MySuiteTest2.java b/surefire-its/src/test/resources/surefire-621-testCounting-junit3-in-parallel/src/it/java/mho/MySuiteTest2.java index 6ef92f6db1..09644db32c 100644 --- a/surefire-its/src/test/resources/surefire-621-testCounting-junit3-in-parallel/src/it/java/mho/MySuiteTest2.java +++ b/surefire-its/src/test/resources/surefire-621-testCounting-junit3-in-parallel/src/it/java/mho/MySuiteTest2.java @@ -1,24 +1,5 @@ package mho; -/* - * 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 junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; diff --git a/surefire-its/src/test/resources/surefire-621-testCounting-junit3-in-parallel/src/it/java/mho/MySuiteTest3.java b/surefire-its/src/test/resources/surefire-621-testCounting-junit3-in-parallel/src/it/java/mho/MySuiteTest3.java index 6618566838..39ca6e323f 100644 --- a/surefire-its/src/test/resources/surefire-621-testCounting-junit3-in-parallel/src/it/java/mho/MySuiteTest3.java +++ b/surefire-its/src/test/resources/surefire-621-testCounting-junit3-in-parallel/src/it/java/mho/MySuiteTest3.java @@ -1,24 +1,5 @@ package mho; -/* - * 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 junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; diff --git a/surefire-its/src/test/resources/surefire-628-consoleoutputbeforeandafterclass/src/test/java/surefire628/Test1.java b/surefire-its/src/test/resources/surefire-628-consoleoutputbeforeandafterclass/src/test/java/surefire628/Test1.java index 91d120166a..ee2abe00a6 100644 --- a/surefire-its/src/test/resources/surefire-628-consoleoutputbeforeandafterclass/src/test/java/surefire628/Test1.java +++ b/surefire-its/src/test/resources/surefire-628-consoleoutputbeforeandafterclass/src/test/java/surefire628/Test1.java @@ -1,24 +1,5 @@ package surefire628; -/* - * 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.junit.Test; import org.junit.BeforeClass; import org.junit.AfterClass; @@ -45,4 +26,4 @@ public static void testWithFailingAssumption3() { System.out.println( "After628Test1 on" + Thread.currentThread().getName()); } -} \ No newline at end of file +} diff --git a/surefire-its/src/test/resources/surefire-634-systemPropertiesWarning/src/test/java/junit4/BasicTest.java b/surefire-its/src/test/resources/surefire-634-systemPropertiesWarning/src/test/java/junit4/BasicTest.java index 2d43f8f817..c12f9465db 100644 --- a/surefire-its/src/test/resources/surefire-634-systemPropertiesWarning/src/test/java/junit4/BasicTest.java +++ b/surefire-its/src/test/resources/surefire-634-systemPropertiesWarning/src/test/java/junit4/BasicTest.java @@ -1,24 +1,5 @@ package junit4; -/* - * 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.junit.After; import org.junit.AfterClass; import org.junit.Assert; diff --git a/surefire-its/src/test/resources/surefire-649-systemProperties/src/test/java/jiras/surefire649/SystemPropertiesTest.java b/surefire-its/src/test/resources/surefire-649-systemProperties/src/test/java/jiras/surefire649/SystemPropertiesTest.java index 27512dfaf9..f7c85c1ce8 100644 --- a/surefire-its/src/test/resources/surefire-649-systemProperties/src/test/java/jiras/surefire649/SystemPropertiesTest.java +++ b/surefire-its/src/test/resources/surefire-649-systemProperties/src/test/java/jiras/surefire649/SystemPropertiesTest.java @@ -1,24 +1,5 @@ package jiras.surefire649; -/* - * 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.junit.Test; public final class SystemPropertiesTest { diff --git a/surefire-its/src/test/resources/surefire-649-systemPropertyVariables/src/test/java/jiras/surefire649/SystemPropertyVariablesTest.java b/surefire-its/src/test/resources/surefire-649-systemPropertyVariables/src/test/java/jiras/surefire649/SystemPropertyVariablesTest.java index e235b46fa5..50f31763e3 100644 --- a/surefire-its/src/test/resources/surefire-649-systemPropertyVariables/src/test/java/jiras/surefire649/SystemPropertyVariablesTest.java +++ b/surefire-its/src/test/resources/surefire-649-systemPropertyVariables/src/test/java/jiras/surefire649/SystemPropertyVariablesTest.java @@ -1,24 +1,5 @@ package jiras.surefire649; -/* - * 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.junit.Test; public final class SystemPropertyVariablesTest { diff --git a/surefire-its/src/test/resources/surefire-673-mockito/src/test/java/surefire673/TestMockito.java b/surefire-its/src/test/resources/surefire-673-mockito/src/test/java/surefire673/TestMockito.java index 12c16bdc01..cafa75da63 100644 --- a/surefire-its/src/test/resources/surefire-673-mockito/src/test/java/surefire673/TestMockito.java +++ b/surefire-its/src/test/resources/surefire-673-mockito/src/test/java/surefire673/TestMockito.java @@ -1,24 +1,5 @@ package surefire673; -/* - * 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.junit.Test; import org.mockito.Mockito; diff --git a/surefire-its/src/test/resources/surefire-674-buildFailingWhenErrors/src/test/java/resultcounting/Test2.java b/surefire-its/src/test/resources/surefire-674-buildFailingWhenErrors/src/test/java/resultcounting/Test2.java index 26b218c12e..05dbd99799 100644 --- a/surefire-its/src/test/resources/surefire-674-buildFailingWhenErrors/src/test/java/resultcounting/Test2.java +++ b/surefire-its/src/test/resources/surefire-674-buildFailingWhenErrors/src/test/java/resultcounting/Test2.java @@ -1,24 +1,5 @@ package resultcounting; -/* - * 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.junit.Test; /** @@ -33,4 +14,4 @@ public void testWithException1() { throw new RuntimeException( "We expect this" ); } -} \ No newline at end of file +} diff --git a/surefire-its/src/test/resources/surefire-685-commaseparatedIncludes/src/test/java/surefire685/TestA.java b/surefire-its/src/test/resources/surefire-685-commaseparatedIncludes/src/test/java/surefire685/TestA.java index b34e4100a0..e384dd4640 100644 --- a/surefire-its/src/test/resources/surefire-685-commaseparatedIncludes/src/test/java/surefire685/TestA.java +++ b/surefire-its/src/test/resources/surefire-685-commaseparatedIncludes/src/test/java/surefire685/TestA.java @@ -1,23 +1,4 @@ package surefire685; -/* - * 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 junit.framework.TestCase; diff --git a/surefire-its/src/test/resources/surefire-685-commaseparatedIncludes/src/test/java/surefire685/TestB.java b/surefire-its/src/test/resources/surefire-685-commaseparatedIncludes/src/test/java/surefire685/TestB.java index 6e272d709d..96995da45a 100644 --- a/surefire-its/src/test/resources/surefire-685-commaseparatedIncludes/src/test/java/surefire685/TestB.java +++ b/surefire-its/src/test/resources/surefire-685-commaseparatedIncludes/src/test/java/surefire685/TestB.java @@ -1,23 +1,4 @@ package surefire685; -/* - * 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 junit.framework.TestCase; diff --git a/surefire-its/src/test/resources/surefire-685-commaseparatedIncludes/src/test/java/surefire685/TestC.java b/surefire-its/src/test/resources/surefire-685-commaseparatedIncludes/src/test/java/surefire685/TestC.java index 68bd647eae..3d6e6515de 100644 --- a/surefire-its/src/test/resources/surefire-685-commaseparatedIncludes/src/test/java/surefire685/TestC.java +++ b/surefire-its/src/test/resources/surefire-685-commaseparatedIncludes/src/test/java/surefire685/TestC.java @@ -1,23 +1,4 @@ package surefire685; -/* - * 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 junit.framework.TestCase; diff --git a/surefire-its/src/test/resources/surefire-697-niceSummary/src/test/java/junit/surefire697/BasicTest.java b/surefire-its/src/test/resources/surefire-697-niceSummary/src/test/java/junit/surefire697/BasicTest.java index f1c3d6677b..5b6d4dffab 100644 --- a/surefire-its/src/test/resources/surefire-697-niceSummary/src/test/java/junit/surefire697/BasicTest.java +++ b/surefire-its/src/test/resources/surefire-697-niceSummary/src/test/java/junit/surefire697/BasicTest.java @@ -1,24 +1,5 @@ package junit.surefire697; -/* - * 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 junit.extensions.TestSetup; import junit.framework.Test; import junit.framework.TestCase; diff --git a/surefire-its/src/test/resources/surefire-697-niceSummary/src/test/java/junit/surefire697/TestTwo.java b/surefire-its/src/test/resources/surefire-697-niceSummary/src/test/java/junit/surefire697/TestTwo.java index 759002fdee..daa0a201e4 100644 --- a/surefire-its/src/test/resources/surefire-697-niceSummary/src/test/java/junit/surefire697/TestTwo.java +++ b/surefire-its/src/test/resources/surefire-697-niceSummary/src/test/java/junit/surefire697/TestTwo.java @@ -1,24 +1,5 @@ package junit.surefire697; -/* - * 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 junit.framework.TestCase; diff --git a/surefire-its/src/test/resources/surefire-803-multiFailsafeExec-failureInFirst/src/test/java/org/apache/maven/surefire/test/FailingTest.java b/surefire-its/src/test/resources/surefire-803-multiFailsafeExec-failureInFirst/src/test/java/org/apache/maven/surefire/test/FailingTest.java index 8a0da3c401..3d9a750324 100644 --- a/surefire-its/src/test/resources/surefire-803-multiFailsafeExec-failureInFirst/src/test/java/org/apache/maven/surefire/test/FailingTest.java +++ b/surefire-its/src/test/resources/surefire-803-multiFailsafeExec-failureInFirst/src/test/java/org/apache/maven/surefire/test/FailingTest.java @@ -1,24 +1,5 @@ package org.apache.maven.surefire.test; -/* - * 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 static org.hamcrest.CoreMatchers.equalTo; import static org.junit.Assert.assertThat; diff --git a/surefire-its/src/test/resources/surefire-803-multiFailsafeExec-failureInFirst/src/test/java/org/apache/maven/surefire/test/SucceedingTest.java b/surefire-its/src/test/resources/surefire-803-multiFailsafeExec-failureInFirst/src/test/java/org/apache/maven/surefire/test/SucceedingTest.java index 3078c61178..d5cb3168c3 100644 --- a/surefire-its/src/test/resources/surefire-803-multiFailsafeExec-failureInFirst/src/test/java/org/apache/maven/surefire/test/SucceedingTest.java +++ b/surefire-its/src/test/resources/surefire-803-multiFailsafeExec-failureInFirst/src/test/java/org/apache/maven/surefire/test/SucceedingTest.java @@ -1,24 +1,5 @@ package org.apache.maven.surefire.test; -/* - * 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 static org.hamcrest.CoreMatchers.equalTo; import static org.junit.Assert.assertThat; diff --git a/surefire-its/src/test/resources/surefire-803-multiFailsafeExec-rebuildOverwrites/src/test/java/org/apache/maven/surefire/test/TheTest.java b/surefire-its/src/test/resources/surefire-803-multiFailsafeExec-rebuildOverwrites/src/test/java/org/apache/maven/surefire/test/TheTest.java index 79c5b51f0a..5e0142a880 100644 --- a/surefire-its/src/test/resources/surefire-803-multiFailsafeExec-rebuildOverwrites/src/test/java/org/apache/maven/surefire/test/TheTest.java +++ b/surefire-its/src/test/resources/surefire-803-multiFailsafeExec-rebuildOverwrites/src/test/java/org/apache/maven/surefire/test/TheTest.java @@ -1,24 +1,5 @@ package org.apache.maven.surefire.test; -/* - * 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 static org.hamcrest.CoreMatchers.equalTo; import static org.junit.Assert.assertThat; diff --git a/surefire-its/src/test/resources/surefire-806-specifiedTests-multi/src/test/java/defaultConfiguration/FirstTest.java b/surefire-its/src/test/resources/surefire-806-specifiedTests-multi/src/test/java/defaultConfiguration/FirstTest.java index 56aeb83ea1..510bbf375e 100644 --- a/surefire-its/src/test/resources/surefire-806-specifiedTests-multi/src/test/java/defaultConfiguration/FirstTest.java +++ b/surefire-its/src/test/resources/surefire-806-specifiedTests-multi/src/test/java/defaultConfiguration/FirstTest.java @@ -1,24 +1,5 @@ package defaultConfiguration; -/* - * 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 junit.extensions.TestSetup; import junit.framework.Test; import junit.framework.TestCase; diff --git a/surefire-its/src/test/resources/surefire-806-specifiedTests-multi/src/test/java/defaultConfiguration/FourthTest.java b/surefire-its/src/test/resources/surefire-806-specifiedTests-multi/src/test/java/defaultConfiguration/FourthTest.java index 880a5b2e04..7562ade850 100644 --- a/surefire-its/src/test/resources/surefire-806-specifiedTests-multi/src/test/java/defaultConfiguration/FourthTest.java +++ b/surefire-its/src/test/resources/surefire-806-specifiedTests-multi/src/test/java/defaultConfiguration/FourthTest.java @@ -1,24 +1,5 @@ package defaultConfiguration; -/* - * 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 junit.extensions.TestSetup; import junit.framework.Test; import junit.framework.TestCase; diff --git a/surefire-its/src/test/resources/surefire-806-specifiedTests-multi/src/test/java/defaultConfiguration/SecondTest.java b/surefire-its/src/test/resources/surefire-806-specifiedTests-multi/src/test/java/defaultConfiguration/SecondTest.java index 4ff022c606..dd3f3c9be0 100644 --- a/surefire-its/src/test/resources/surefire-806-specifiedTests-multi/src/test/java/defaultConfiguration/SecondTest.java +++ b/surefire-its/src/test/resources/surefire-806-specifiedTests-multi/src/test/java/defaultConfiguration/SecondTest.java @@ -1,24 +1,5 @@ package defaultConfiguration; -/* - * 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 junit.extensions.TestSetup; import junit.framework.Test; import junit.framework.TestCase; diff --git a/surefire-its/src/test/resources/surefire-806-specifiedTests-multi/src/test/java/defaultConfiguration/ThirdTest.java b/surefire-its/src/test/resources/surefire-806-specifiedTests-multi/src/test/java/defaultConfiguration/ThirdTest.java index ff25a9bab3..4e6869c9fb 100644 --- a/surefire-its/src/test/resources/surefire-806-specifiedTests-multi/src/test/java/defaultConfiguration/ThirdTest.java +++ b/surefire-its/src/test/resources/surefire-806-specifiedTests-multi/src/test/java/defaultConfiguration/ThirdTest.java @@ -1,24 +1,5 @@ package defaultConfiguration; -/* - * 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 junit.extensions.TestSetup; import junit.framework.Test; import junit.framework.TestCase; diff --git a/surefire-its/src/test/resources/surefire-806-specifiedTests-single/src/test/java/defaultConfiguration/FirstTest.java b/surefire-its/src/test/resources/surefire-806-specifiedTests-single/src/test/java/defaultConfiguration/FirstTest.java index 3c7264f511..a0d8af3353 100644 --- a/surefire-its/src/test/resources/surefire-806-specifiedTests-single/src/test/java/defaultConfiguration/FirstTest.java +++ b/surefire-its/src/test/resources/surefire-806-specifiedTests-single/src/test/java/defaultConfiguration/FirstTest.java @@ -1,24 +1,5 @@ package defaultConfiguration; -/* - * 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 junit.extensions.TestSetup; import junit.framework.Test; import junit.framework.TestCase; diff --git a/surefire-its/src/test/resources/surefire-806-specifiedTests-single/src/test/java/defaultConfiguration/FourthTest.java b/surefire-its/src/test/resources/surefire-806-specifiedTests-single/src/test/java/defaultConfiguration/FourthTest.java index 880a5b2e04..7562ade850 100644 --- a/surefire-its/src/test/resources/surefire-806-specifiedTests-single/src/test/java/defaultConfiguration/FourthTest.java +++ b/surefire-its/src/test/resources/surefire-806-specifiedTests-single/src/test/java/defaultConfiguration/FourthTest.java @@ -1,24 +1,5 @@ package defaultConfiguration; -/* - * 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 junit.extensions.TestSetup; import junit.framework.Test; import junit.framework.TestCase; diff --git a/surefire-its/src/test/resources/surefire-806-specifiedTests-single/src/test/java/defaultConfiguration/SecondTest.java b/surefire-its/src/test/resources/surefire-806-specifiedTests-single/src/test/java/defaultConfiguration/SecondTest.java index 4ff022c606..dd3f3c9be0 100644 --- a/surefire-its/src/test/resources/surefire-806-specifiedTests-single/src/test/java/defaultConfiguration/SecondTest.java +++ b/surefire-its/src/test/resources/surefire-806-specifiedTests-single/src/test/java/defaultConfiguration/SecondTest.java @@ -1,24 +1,5 @@ package defaultConfiguration; -/* - * 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 junit.extensions.TestSetup; import junit.framework.Test; import junit.framework.TestCase; diff --git a/surefire-its/src/test/resources/surefire-806-specifiedTests-single/src/test/java/defaultConfiguration/ThirdTest.java b/surefire-its/src/test/resources/surefire-806-specifiedTests-single/src/test/java/defaultConfiguration/ThirdTest.java index ff25a9bab3..4e6869c9fb 100644 --- a/surefire-its/src/test/resources/surefire-806-specifiedTests-single/src/test/java/defaultConfiguration/ThirdTest.java +++ b/surefire-its/src/test/resources/surefire-806-specifiedTests-single/src/test/java/defaultConfiguration/ThirdTest.java @@ -1,24 +1,5 @@ package defaultConfiguration; -/* - * 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 junit.extensions.TestSetup; import junit.framework.Test; import junit.framework.TestCase; diff --git a/surefire-its/src/test/resources/surefire-809-groupExpr-junit48/src/test/java/junit4/BasicTest.java b/surefire-its/src/test/resources/surefire-809-groupExpr-junit48/src/test/java/junit4/BasicTest.java index ecfec311d3..672e1c28ca 100644 --- a/surefire-its/src/test/resources/surefire-809-groupExpr-junit48/src/test/java/junit4/BasicTest.java +++ b/surefire-its/src/test/resources/surefire-809-groupExpr-junit48/src/test/java/junit4/BasicTest.java @@ -1,23 +1,4 @@ package junit4; -/* - * 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.junit.AfterClass; import org.junit.Before; import org.junit.Rule; diff --git a/surefire-its/src/test/resources/surefire-809-groupExpr-junit48/src/test/java/junit4/CategoryCTest.java b/surefire-its/src/test/resources/surefire-809-groupExpr-junit48/src/test/java/junit4/CategoryCTest.java index 7fc323d9b9..f69e070b15 100644 --- a/surefire-its/src/test/resources/surefire-809-groupExpr-junit48/src/test/java/junit4/CategoryCTest.java +++ b/surefire-its/src/test/resources/surefire-809-groupExpr-junit48/src/test/java/junit4/CategoryCTest.java @@ -1,23 +1,4 @@ package junit4; -/* - * 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.junit.AfterClass; import org.junit.Before; import org.junit.Rule; diff --git a/surefire-its/src/test/resources/surefire-809-groupExpr-junit48/src/test/java/junit4/NoCategoryTest.java b/surefire-its/src/test/resources/surefire-809-groupExpr-junit48/src/test/java/junit4/NoCategoryTest.java index f08f40f195..8cb62d1107 100644 --- a/surefire-its/src/test/resources/surefire-809-groupExpr-junit48/src/test/java/junit4/NoCategoryTest.java +++ b/surefire-its/src/test/resources/surefire-809-groupExpr-junit48/src/test/java/junit4/NoCategoryTest.java @@ -1,23 +1,4 @@ package junit4; -/* - * 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.junit.AfterClass; import org.junit.Test; diff --git a/surefire-its/src/test/resources/surefire-809-groupExpr-testng/src/test/java/testng/BasicTest.java b/surefire-its/src/test/resources/surefire-809-groupExpr-testng/src/test/java/testng/BasicTest.java index c53875a179..dbc6521d15 100644 --- a/surefire-its/src/test/resources/surefire-809-groupExpr-testng/src/test/java/testng/BasicTest.java +++ b/surefire-its/src/test/resources/surefire-809-groupExpr-testng/src/test/java/testng/BasicTest.java @@ -1,23 +1,4 @@ package testng; -/* - * 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.testng.annotations.AfterClass; import org.testng.annotations.Test; diff --git a/surefire-its/src/test/resources/surefire-809-groupExpr-testng/src/test/java/testng/CategoryCTest.java b/surefire-its/src/test/resources/surefire-809-groupExpr-testng/src/test/java/testng/CategoryCTest.java index 66fafabe30..a6db88a3de 100644 --- a/surefire-its/src/test/resources/surefire-809-groupExpr-testng/src/test/java/testng/CategoryCTest.java +++ b/surefire-its/src/test/resources/surefire-809-groupExpr-testng/src/test/java/testng/CategoryCTest.java @@ -1,23 +1,4 @@ package testng; -/* - * 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.testng.annotations.AfterClass; import org.testng.annotations.Test; diff --git a/surefire-its/src/test/resources/surefire-809-groupExpr-testng/src/test/java/testng/NoCategoryTest.java b/surefire-its/src/test/resources/surefire-809-groupExpr-testng/src/test/java/testng/NoCategoryTest.java index 111f20d26f..efbb13f114 100644 --- a/surefire-its/src/test/resources/surefire-809-groupExpr-testng/src/test/java/testng/NoCategoryTest.java +++ b/surefire-its/src/test/resources/surefire-809-groupExpr-testng/src/test/java/testng/NoCategoryTest.java @@ -1,23 +1,4 @@ package testng; -/* - * 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.testng.annotations.AfterClass; import org.testng.annotations.Test; diff --git a/surefire-its/src/test/resources/surefire-812-log4j-classloader/src/test/java/surefire812/LoggingTest.java b/surefire-its/src/test/resources/surefire-812-log4j-classloader/src/test/java/surefire812/LoggingTest.java index 3cda524286..343934adc4 100644 --- a/surefire-its/src/test/resources/surefire-812-log4j-classloader/src/test/java/surefire812/LoggingTest.java +++ b/surefire-its/src/test/resources/surefire-812-log4j-classloader/src/test/java/surefire812/LoggingTest.java @@ -1,24 +1,5 @@ package surefire812; -/* - * 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.log4j.Logger; import junit.framework.TestCase; diff --git a/surefire-its/src/test/resources/surefire-818-ignored-tests-on-npe/src/test/java/cyril/test/IgnoredTest.java b/surefire-its/src/test/resources/surefire-818-ignored-tests-on-npe/src/test/java/cyril/test/IgnoredTest.java index d66adc8073..02250ee924 100644 --- a/surefire-its/src/test/resources/surefire-818-ignored-tests-on-npe/src/test/java/cyril/test/IgnoredTest.java +++ b/surefire-its/src/test/resources/surefire-818-ignored-tests-on-npe/src/test/java/cyril/test/IgnoredTest.java @@ -1,24 +1,5 @@ package cyril.test; -/* - * 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.junit.Test; diff --git a/surefire-its/src/test/resources/surefire-822-legal-JUnit4-descriptions/src/test/java/surefire/testcase/JunitParamsTest.java b/surefire-its/src/test/resources/surefire-822-legal-JUnit4-descriptions/src/test/java/surefire/testcase/JunitParamsTest.java index 3ccd814296..7c79d96962 100644 --- a/surefire-its/src/test/resources/surefire-822-legal-JUnit4-descriptions/src/test/java/surefire/testcase/JunitParamsTest.java +++ b/surefire-its/src/test/resources/surefire-822-legal-JUnit4-descriptions/src/test/java/surefire/testcase/JunitParamsTest.java @@ -1,23 +1,4 @@ package surefire.testcase; -/* - * 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 java.util.Arrays; import java.util.Collection; diff --git a/surefire-its/src/test/resources/surefire-822-legal-JUnit4-descriptions/src/test/java/surefire/testcase/NonJunitParamsTest.java b/surefire-its/src/test/resources/surefire-822-legal-JUnit4-descriptions/src/test/java/surefire/testcase/NonJunitParamsTest.java index 6cffeeb6a8..a3ac5220cf 100644 --- a/surefire-its/src/test/resources/surefire-822-legal-JUnit4-descriptions/src/test/java/surefire/testcase/NonJunitParamsTest.java +++ b/surefire-its/src/test/resources/surefire-822-legal-JUnit4-descriptions/src/test/java/surefire/testcase/NonJunitParamsTest.java @@ -1,23 +1,4 @@ package surefire.testcase; -/* - * 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.junit.Test; import static org.hamcrest.CoreMatchers.equalTo; diff --git a/surefire-its/src/test/resources/surefire-828-emptyGroupExpr-junit48/src/test/java/junit4/BasicTest.java b/surefire-its/src/test/resources/surefire-828-emptyGroupExpr-junit48/src/test/java/junit4/BasicTest.java index ecfec311d3..672e1c28ca 100644 --- a/surefire-its/src/test/resources/surefire-828-emptyGroupExpr-junit48/src/test/java/junit4/BasicTest.java +++ b/surefire-its/src/test/resources/surefire-828-emptyGroupExpr-junit48/src/test/java/junit4/BasicTest.java @@ -1,23 +1,4 @@ package junit4; -/* - * 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.junit.AfterClass; import org.junit.Before; import org.junit.Rule; diff --git a/surefire-its/src/test/resources/surefire-828-emptyGroupExpr-junit48/src/test/java/junit4/CategoryCTest.java b/surefire-its/src/test/resources/surefire-828-emptyGroupExpr-junit48/src/test/java/junit4/CategoryCTest.java index 7fc323d9b9..f69e070b15 100644 --- a/surefire-its/src/test/resources/surefire-828-emptyGroupExpr-junit48/src/test/java/junit4/CategoryCTest.java +++ b/surefire-its/src/test/resources/surefire-828-emptyGroupExpr-junit48/src/test/java/junit4/CategoryCTest.java @@ -1,23 +1,4 @@ package junit4; -/* - * 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.junit.AfterClass; import org.junit.Before; import org.junit.Rule; diff --git a/surefire-its/src/test/resources/surefire-828-emptyGroupExpr-junit48/src/test/java/junit4/NoCategoryTest.java b/surefire-its/src/test/resources/surefire-828-emptyGroupExpr-junit48/src/test/java/junit4/NoCategoryTest.java index f08f40f195..8cb62d1107 100644 --- a/surefire-its/src/test/resources/surefire-828-emptyGroupExpr-junit48/src/test/java/junit4/NoCategoryTest.java +++ b/surefire-its/src/test/resources/surefire-828-emptyGroupExpr-junit48/src/test/java/junit4/NoCategoryTest.java @@ -1,23 +1,4 @@ package junit4; -/* - * 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.junit.AfterClass; import org.junit.Test; diff --git a/surefire-its/src/test/resources/surefire-828-emptyGroupExpr-testng/src/test/java/testng/BasicTest.java b/surefire-its/src/test/resources/surefire-828-emptyGroupExpr-testng/src/test/java/testng/BasicTest.java index c53875a179..dbc6521d15 100644 --- a/surefire-its/src/test/resources/surefire-828-emptyGroupExpr-testng/src/test/java/testng/BasicTest.java +++ b/surefire-its/src/test/resources/surefire-828-emptyGroupExpr-testng/src/test/java/testng/BasicTest.java @@ -1,23 +1,4 @@ package testng; -/* - * 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.testng.annotations.AfterClass; import org.testng.annotations.Test; diff --git a/surefire-its/src/test/resources/surefire-828-emptyGroupExpr-testng/src/test/java/testng/CategoryCTest.java b/surefire-its/src/test/resources/surefire-828-emptyGroupExpr-testng/src/test/java/testng/CategoryCTest.java index 66fafabe30..a6db88a3de 100644 --- a/surefire-its/src/test/resources/surefire-828-emptyGroupExpr-testng/src/test/java/testng/CategoryCTest.java +++ b/surefire-its/src/test/resources/surefire-828-emptyGroupExpr-testng/src/test/java/testng/CategoryCTest.java @@ -1,23 +1,4 @@ package testng; -/* - * 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.testng.annotations.AfterClass; import org.testng.annotations.Test; diff --git a/surefire-its/src/test/resources/surefire-828-emptyGroupExpr-testng/src/test/java/testng/NoCategoryTest.java b/surefire-its/src/test/resources/surefire-828-emptyGroupExpr-testng/src/test/java/testng/NoCategoryTest.java index 111f20d26f..efbb13f114 100644 --- a/surefire-its/src/test/resources/surefire-828-emptyGroupExpr-testng/src/test/java/testng/NoCategoryTest.java +++ b/surefire-its/src/test/resources/surefire-828-emptyGroupExpr-testng/src/test/java/testng/NoCategoryTest.java @@ -1,23 +1,4 @@ package testng; -/* - * 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.testng.annotations.AfterClass; import org.testng.annotations.Test; diff --git a/surefire-its/src/test/resources/surefire-832-provider-selection/src/test/java/junit4/BasicTest.java b/surefire-its/src/test/resources/surefire-832-provider-selection/src/test/java/junit4/BasicTest.java index ecfec311d3..672e1c28ca 100644 --- a/surefire-its/src/test/resources/surefire-832-provider-selection/src/test/java/junit4/BasicTest.java +++ b/surefire-its/src/test/resources/surefire-832-provider-selection/src/test/java/junit4/BasicTest.java @@ -1,23 +1,4 @@ package junit4; -/* - * 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.junit.AfterClass; import org.junit.Before; import org.junit.Rule; diff --git a/surefire-its/src/test/resources/surefire-832-provider-selection/src/test/java/junit4/CategoryCTest.java b/surefire-its/src/test/resources/surefire-832-provider-selection/src/test/java/junit4/CategoryCTest.java index 7fc323d9b9..f69e070b15 100644 --- a/surefire-its/src/test/resources/surefire-832-provider-selection/src/test/java/junit4/CategoryCTest.java +++ b/surefire-its/src/test/resources/surefire-832-provider-selection/src/test/java/junit4/CategoryCTest.java @@ -1,23 +1,4 @@ package junit4; -/* - * 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.junit.AfterClass; import org.junit.Before; import org.junit.Rule; diff --git a/surefire-its/src/test/resources/surefire-832-provider-selection/src/test/java/junit4/NoCategoryTest.java b/surefire-its/src/test/resources/surefire-832-provider-selection/src/test/java/junit4/NoCategoryTest.java index f08f40f195..8cb62d1107 100644 --- a/surefire-its/src/test/resources/surefire-832-provider-selection/src/test/java/junit4/NoCategoryTest.java +++ b/surefire-its/src/test/resources/surefire-832-provider-selection/src/test/java/junit4/NoCategoryTest.java @@ -1,23 +1,4 @@ package junit4; -/* - * 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.junit.AfterClass; import org.junit.Test; diff --git a/surefire-its/src/test/resources/surefire-847-testngfail/src/test/java/org/codehaus/SomeFailedTest.java b/surefire-its/src/test/resources/surefire-847-testngfail/src/test/java/org/codehaus/SomeFailedTest.java index 5e6a3da5e0..57343981f6 100644 --- a/surefire-its/src/test/resources/surefire-847-testngfail/src/test/java/org/codehaus/SomeFailedTest.java +++ b/surefire-its/src/test/resources/surefire-847-testngfail/src/test/java/org/codehaus/SomeFailedTest.java @@ -1,24 +1,5 @@ package org.codehaus; -/* - * 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.testng.Assert; import org.testng.annotations.Test; diff --git a/surefire-its/src/test/resources/surefire-847-testngfail/src/test/java/org/codehaus/SomePassedTest.java b/surefire-its/src/test/resources/surefire-847-testngfail/src/test/java/org/codehaus/SomePassedTest.java index 737f070f3e..039f77fe70 100644 --- a/surefire-its/src/test/resources/surefire-847-testngfail/src/test/java/org/codehaus/SomePassedTest.java +++ b/surefire-its/src/test/resources/surefire-847-testngfail/src/test/java/org/codehaus/SomePassedTest.java @@ -1,24 +1,5 @@ package org.codehaus; -/* - * 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.testng.Assert; import org.testng.annotations.Test; diff --git a/surefire-its/src/test/resources/surefire-855-failsafe-use-bundle/src/test/java/jiras/surefre855/bundle/FooIT.java b/surefire-its/src/test/resources/surefire-855-failsafe-use-bundle/src/test/java/jiras/surefre855/bundle/FooIT.java index 00e2193bdf..b8db8c4469 100644 --- a/surefire-its/src/test/resources/surefire-855-failsafe-use-bundle/src/test/java/jiras/surefre855/bundle/FooIT.java +++ b/surefire-its/src/test/resources/surefire-855-failsafe-use-bundle/src/test/java/jiras/surefre855/bundle/FooIT.java @@ -1,24 +1,5 @@ package jiras.surefire855.bundle; -/* - * 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.junit.Test; import java.io.File; diff --git a/surefire-its/src/test/resources/surefire-855-failsafe-use-jar/src/test/java/jiras/surefire855/jar/FooIT.java b/surefire-its/src/test/resources/surefire-855-failsafe-use-jar/src/test/java/jiras/surefire855/jar/FooIT.java index 3daa41ff21..e07b4ac43d 100644 --- a/surefire-its/src/test/resources/surefire-855-failsafe-use-jar/src/test/java/jiras/surefire855/jar/FooIT.java +++ b/surefire-its/src/test/resources/surefire-855-failsafe-use-jar/src/test/java/jiras/surefire855/jar/FooIT.java @@ -1,24 +1,5 @@ package jiras.surefire855.jar; -/* - * 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.junit.Test; import java.io.File; diff --git a/surefire-its/src/test/resources/surefire-855-failsafe-use-war/src/test/java/jiras/surefire855/war/FooIT.java b/surefire-its/src/test/resources/surefire-855-failsafe-use-war/src/test/java/jiras/surefire855/war/FooIT.java index 0e7dba94ea..c532d76157 100644 --- a/surefire-its/src/test/resources/surefire-855-failsafe-use-war/src/test/java/jiras/surefire855/war/FooIT.java +++ b/surefire-its/src/test/resources/surefire-855-failsafe-use-war/src/test/java/jiras/surefire855/war/FooIT.java @@ -1,24 +1,5 @@ package jiras.surefire855.war; -/* - * 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.junit.Test; import java.io.File; diff --git a/surefire-its/src/test/resources/surefire-926-2-provider-failure/src/test/java/com/company/JUnitTest.java b/surefire-its/src/test/resources/surefire-926-2-provider-failure/src/test/java/com/company/JUnitTest.java index 39639cfa88..29d84a0756 100644 --- a/surefire-its/src/test/resources/surefire-926-2-provider-failure/src/test/java/com/company/JUnitTest.java +++ b/surefire-its/src/test/resources/surefire-926-2-provider-failure/src/test/java/com/company/JUnitTest.java @@ -1,24 +1,5 @@ package com.company; -/* - * 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.junit.Assert; import org.junit.Test; diff --git a/surefire-its/src/test/resources/surefire-926-2-provider-failure/src/test/java/com/company/TestNGTest.java b/surefire-its/src/test/resources/surefire-926-2-provider-failure/src/test/java/com/company/TestNGTest.java index 2701cb2206..5d70f9f3ea 100644 --- a/surefire-its/src/test/resources/surefire-926-2-provider-failure/src/test/java/com/company/TestNGTest.java +++ b/surefire-its/src/test/resources/surefire-926-2-provider-failure/src/test/java/com/company/TestNGTest.java @@ -1,24 +1,5 @@ package com.company; -/* - * 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.testng.Assert; import org.testng.annotations.Test; diff --git a/surefire-its/src/test/resources/surefire-930-failsafe-runtests/src/test/java/org/apache/maven/plugins/failsafe/ExampleIntegrationTest.java b/surefire-its/src/test/resources/surefire-930-failsafe-runtests/src/test/java/org/apache/maven/plugins/failsafe/ExampleIntegrationTest.java index 3ddc90c68c..937fda6734 100644 --- a/surefire-its/src/test/resources/surefire-930-failsafe-runtests/src/test/java/org/apache/maven/plugins/failsafe/ExampleIntegrationTest.java +++ b/surefire-its/src/test/resources/surefire-930-failsafe-runtests/src/test/java/org/apache/maven/plugins/failsafe/ExampleIntegrationTest.java @@ -1,24 +1,5 @@ package org.apache.maven.plugins.failsafe; -/* - * 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.junit.Assert; import org.testng.annotations.Test; diff --git a/surefire-its/src/test/resources/surefire-930-failsafe-runtests/src/test/java/org/apache/maven/plugins/failsafe/ExampleTest.java b/surefire-its/src/test/resources/surefire-930-failsafe-runtests/src/test/java/org/apache/maven/plugins/failsafe/ExampleTest.java index 19a08d50f2..bb26b896aa 100644 --- a/surefire-its/src/test/resources/surefire-930-failsafe-runtests/src/test/java/org/apache/maven/plugins/failsafe/ExampleTest.java +++ b/surefire-its/src/test/resources/surefire-930-failsafe-runtests/src/test/java/org/apache/maven/plugins/failsafe/ExampleTest.java @@ -1,24 +1,5 @@ package org.apache.maven.plugins.failsafe; -/* - * 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.junit.Assert; import org.testng.annotations.Test; diff --git a/surefire-its/src/test/resources/surefire-931-provider-failure/src/test/java/com/mycompany/testfailed/AppTest.java b/surefire-its/src/test/resources/surefire-931-provider-failure/src/test/java/com/mycompany/testfailed/AppTest.java index e760b875d1..57c0d927ae 100644 --- a/surefire-its/src/test/resources/surefire-931-provider-failure/src/test/java/com/mycompany/testfailed/AppTest.java +++ b/surefire-its/src/test/resources/surefire-931-provider-failure/src/test/java/com/mycompany/testfailed/AppTest.java @@ -1,24 +1,5 @@ package com.mycompany.testfailed; -/* - * 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 junit.framework.TestCase; import org.testng.annotations.Test; diff --git a/surefire-its/src/test/resources/surefire-942-testngSuite/src/test/java/org/BasicTest.java b/surefire-its/src/test/resources/surefire-942-testngSuite/src/test/java/org/BasicTest.java index be0bea06e7..a663ac5a31 100644 --- a/surefire-its/src/test/resources/surefire-942-testngSuite/src/test/java/org/BasicTest.java +++ b/surefire-its/src/test/resources/surefire-942-testngSuite/src/test/java/org/BasicTest.java @@ -1,24 +1,5 @@ package org; -/* - * 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.testng.annotations.*; import org.testng.Assert; diff --git a/surefire-its/src/test/resources/surefire-943-report-content/src/test/java/org/sample/module/My1Test.java b/surefire-its/src/test/resources/surefire-943-report-content/src/test/java/org/sample/module/My1Test.java index 6512a3a7a3..1f909a5937 100644 --- a/surefire-its/src/test/resources/surefire-943-report-content/src/test/java/org/sample/module/My1Test.java +++ b/surefire-its/src/test/resources/surefire-943-report-content/src/test/java/org/sample/module/My1Test.java @@ -1,24 +1,5 @@ package org.sample.module; -/* - * 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 static org.junit.Assert.fail; import org.junit.Test; diff --git a/surefire-its/src/test/resources/surefire-943-report-content/src/test/java/org/sample/module/My2Test.java b/surefire-its/src/test/resources/surefire-943-report-content/src/test/java/org/sample/module/My2Test.java index faea7165bf..571e1eb370 100644 --- a/surefire-its/src/test/resources/surefire-943-report-content/src/test/java/org/sample/module/My2Test.java +++ b/surefire-its/src/test/resources/surefire-943-report-content/src/test/java/org/sample/module/My2Test.java @@ -1,24 +1,5 @@ package org.sample.module; -/* - * 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 static org.junit.Assert.fail; import org.junit.Test; diff --git a/surefire-its/src/test/resources/surefire-943-report-content/src/test/java/org/sample/module/My3Test.java b/surefire-its/src/test/resources/surefire-943-report-content/src/test/java/org/sample/module/My3Test.java index 2d35a99161..323c03e960 100644 --- a/surefire-its/src/test/resources/surefire-943-report-content/src/test/java/org/sample/module/My3Test.java +++ b/surefire-its/src/test/resources/surefire-943-report-content/src/test/java/org/sample/module/My3Test.java @@ -1,24 +1,5 @@ package org.sample.module; -/* - * 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 static org.junit.Assert.fail; import org.junit.Test; diff --git a/surefire-its/src/test/resources/surefire-943-report-content/src/test/java/org/sample/module/My4Test.java b/surefire-its/src/test/resources/surefire-943-report-content/src/test/java/org/sample/module/My4Test.java index c500c1e939..7fa8ef8a83 100644 --- a/surefire-its/src/test/resources/surefire-943-report-content/src/test/java/org/sample/module/My4Test.java +++ b/surefire-its/src/test/resources/surefire-943-report-content/src/test/java/org/sample/module/My4Test.java @@ -1,24 +1,5 @@ package org.sample.module; -/* - * 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.junit.Test; import org.junit.Ignore; diff --git a/surefire-its/src/test/resources/surefire-943-report-content/src/test/java/org/sample/module/My5Test.java b/surefire-its/src/test/resources/surefire-943-report-content/src/test/java/org/sample/module/My5Test.java index 1e3074161d..fbacd366b7 100644 --- a/surefire-its/src/test/resources/surefire-943-report-content/src/test/java/org/sample/module/My5Test.java +++ b/surefire-its/src/test/resources/surefire-943-report-content/src/test/java/org/sample/module/My5Test.java @@ -1,24 +1,5 @@ package org.sample.module; -/* - * 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.junit.BeforeClass; import org.junit.Test; diff --git a/surefire-its/src/test/resources/surefire-946-killMainProcessInReusableFork/src/test/java/junit44/environment/Basic01Test.java b/surefire-its/src/test/resources/surefire-946-killMainProcessInReusableFork/src/test/java/junit44/environment/Basic01Test.java index 77971fd31f..62ee374542 100644 --- a/surefire-its/src/test/resources/surefire-946-killMainProcessInReusableFork/src/test/java/junit44/environment/Basic01Test.java +++ b/surefire-its/src/test/resources/surefire-946-killMainProcessInReusableFork/src/test/java/junit44/environment/Basic01Test.java @@ -1,24 +1,5 @@ package junit44.environment; -/* - * 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 dummy.DummyClass; import org.junit.AfterClass; import org.junit.Test; diff --git a/surefire-its/src/test/resources/surefire-946-killMainProcessInReusableFork/src/test/java/junit44/environment/Basic02Test.java b/surefire-its/src/test/resources/surefire-946-killMainProcessInReusableFork/src/test/java/junit44/environment/Basic02Test.java index 1133efea0a..38940dcdae 100644 --- a/surefire-its/src/test/resources/surefire-946-killMainProcessInReusableFork/src/test/java/junit44/environment/Basic02Test.java +++ b/surefire-its/src/test/resources/surefire-946-killMainProcessInReusableFork/src/test/java/junit44/environment/Basic02Test.java @@ -1,24 +1,5 @@ package junit44.environment; -/* - * 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 dummy.DummyClass; import org.junit.AfterClass; import org.junit.Test; diff --git a/surefire-its/src/test/resources/surefire-946-killMainProcessInReusableFork/src/test/java/junit44/environment/Basic03Test.java b/surefire-its/src/test/resources/surefire-946-killMainProcessInReusableFork/src/test/java/junit44/environment/Basic03Test.java index 15b1bd9e75..edb820d3de 100644 --- a/surefire-its/src/test/resources/surefire-946-killMainProcessInReusableFork/src/test/java/junit44/environment/Basic03Test.java +++ b/surefire-its/src/test/resources/surefire-946-killMainProcessInReusableFork/src/test/java/junit44/environment/Basic03Test.java @@ -1,24 +1,5 @@ package junit44.environment; -/* - * 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 dummy.DummyClass; import org.junit.AfterClass; import org.junit.Test; diff --git a/surefire-its/src/test/resources/surefire-946-killMainProcessInReusableFork/src/test/java/junit44/environment/Basic04Test.java b/surefire-its/src/test/resources/surefire-946-killMainProcessInReusableFork/src/test/java/junit44/environment/Basic04Test.java index 41513369b2..4d02bb2221 100644 --- a/surefire-its/src/test/resources/surefire-946-killMainProcessInReusableFork/src/test/java/junit44/environment/Basic04Test.java +++ b/surefire-its/src/test/resources/surefire-946-killMainProcessInReusableFork/src/test/java/junit44/environment/Basic04Test.java @@ -1,24 +1,5 @@ package junit44.environment; -/* - * 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 dummy.DummyClass; import org.junit.AfterClass; import org.junit.Test; diff --git a/surefire-its/src/test/resources/surefire-946-killMainProcessInReusableFork/src/test/java/junit44/environment/Basic05Test.java b/surefire-its/src/test/resources/surefire-946-killMainProcessInReusableFork/src/test/java/junit44/environment/Basic05Test.java index 3f142611fc..5f9fac4261 100644 --- a/surefire-its/src/test/resources/surefire-946-killMainProcessInReusableFork/src/test/java/junit44/environment/Basic05Test.java +++ b/surefire-its/src/test/resources/surefire-946-killMainProcessInReusableFork/src/test/java/junit44/environment/Basic05Test.java @@ -1,24 +1,5 @@ package junit44.environment; -/* - * 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 dummy.DummyClass; import org.junit.AfterClass; import org.junit.Test; diff --git a/surefire-its/src/test/resources/surefire-946-killMainProcessInReusableFork/src/test/java/junit44/environment/Basic06Test.java b/surefire-its/src/test/resources/surefire-946-killMainProcessInReusableFork/src/test/java/junit44/environment/Basic06Test.java index 1925665f08..594722a6c8 100644 --- a/surefire-its/src/test/resources/surefire-946-killMainProcessInReusableFork/src/test/java/junit44/environment/Basic06Test.java +++ b/surefire-its/src/test/resources/surefire-946-killMainProcessInReusableFork/src/test/java/junit44/environment/Basic06Test.java @@ -1,24 +1,5 @@ package junit44.environment; -/* - * 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 dummy.DummyClass; import org.junit.AfterClass; import org.junit.Test; diff --git a/surefire-its/src/test/resources/surefire-946-killMainProcessInReusableFork/src/test/java/junit44/environment/Basic07Test.java b/surefire-its/src/test/resources/surefire-946-killMainProcessInReusableFork/src/test/java/junit44/environment/Basic07Test.java index 77436bb4f7..e882693caa 100644 --- a/surefire-its/src/test/resources/surefire-946-killMainProcessInReusableFork/src/test/java/junit44/environment/Basic07Test.java +++ b/surefire-its/src/test/resources/surefire-946-killMainProcessInReusableFork/src/test/java/junit44/environment/Basic07Test.java @@ -1,24 +1,5 @@ package junit44.environment; -/* - * 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 dummy.DummyClass; import org.junit.AfterClass; import org.junit.Test; diff --git a/surefire-its/src/test/resources/surefire-946-killMainProcessInReusableFork/src/test/java/junit44/environment/Basic08Test.java b/surefire-its/src/test/resources/surefire-946-killMainProcessInReusableFork/src/test/java/junit44/environment/Basic08Test.java index ed62c32560..d5724a4333 100644 --- a/surefire-its/src/test/resources/surefire-946-killMainProcessInReusableFork/src/test/java/junit44/environment/Basic08Test.java +++ b/surefire-its/src/test/resources/surefire-946-killMainProcessInReusableFork/src/test/java/junit44/environment/Basic08Test.java @@ -1,24 +1,5 @@ package junit44.environment; -/* - * 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 dummy.DummyClass; import org.junit.AfterClass; import org.junit.Test; diff --git a/surefire-its/src/test/resources/surefire-946-killMainProcessInReusableFork/src/test/java/junit44/environment/Basic09Test.java b/surefire-its/src/test/resources/surefire-946-killMainProcessInReusableFork/src/test/java/junit44/environment/Basic09Test.java index 87043e2891..2ea8b630cf 100644 --- a/surefire-its/src/test/resources/surefire-946-killMainProcessInReusableFork/src/test/java/junit44/environment/Basic09Test.java +++ b/surefire-its/src/test/resources/surefire-946-killMainProcessInReusableFork/src/test/java/junit44/environment/Basic09Test.java @@ -1,24 +1,5 @@ package junit44.environment; -/* - * 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 dummy.DummyClass; import org.junit.AfterClass; import org.junit.Test; diff --git a/surefire-its/src/test/resources/surefire-946-killMainProcessInReusableFork/src/test/java/junit44/environment/Basic10Test.java b/surefire-its/src/test/resources/surefire-946-killMainProcessInReusableFork/src/test/java/junit44/environment/Basic10Test.java index d481da7f5a..3ae8a38df3 100644 --- a/surefire-its/src/test/resources/surefire-946-killMainProcessInReusableFork/src/test/java/junit44/environment/Basic10Test.java +++ b/surefire-its/src/test/resources/surefire-946-killMainProcessInReusableFork/src/test/java/junit44/environment/Basic10Test.java @@ -1,24 +1,5 @@ package junit44.environment; -/* - * 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 dummy.DummyClass; import org.junit.AfterClass; import org.junit.Test; diff --git a/surefire-its/src/test/resources/surefire-972-bizarre-noclassdef/boom/src/test/java/org/apache/maven/surefire/crb/ClassRuleIT.java b/surefire-its/src/test/resources/surefire-972-bizarre-noclassdef/boom/src/test/java/org/apache/maven/surefire/crb/ClassRuleIT.java index 0d5eab91b6..5554fd90f5 100644 --- a/surefire-its/src/test/resources/surefire-972-bizarre-noclassdef/boom/src/test/java/org/apache/maven/surefire/crb/ClassRuleIT.java +++ b/surefire-its/src/test/resources/surefire-972-bizarre-noclassdef/boom/src/test/java/org/apache/maven/surefire/crb/ClassRuleIT.java @@ -1,24 +1,5 @@ package org.apache.maven.surefire.crb; -/* - * 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.junit.Assert; import org.junit.ClassRule; import org.junit.Test; diff --git a/surefire-its/src/test/resources/surefire-979-smartStackTrace-wrongClassloader/module1/src/main/java/surefire979/TestBase.java b/surefire-its/src/test/resources/surefire-979-smartStackTrace-wrongClassloader/module1/src/main/java/surefire979/TestBase.java index 442b3c3aad..4cba8527d1 100644 --- a/surefire-its/src/test/resources/surefire-979-smartStackTrace-wrongClassloader/module1/src/main/java/surefire979/TestBase.java +++ b/surefire-its/src/test/resources/surefire-979-smartStackTrace-wrongClassloader/module1/src/main/java/surefire979/TestBase.java @@ -1,25 +1,6 @@ package surefire979; -/* - * 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.input.AutoCloseInputStream; import org.junit.Test; diff --git a/surefire-its/src/test/resources/surefire-979-smartStackTrace-wrongClassloader/module2/src/test/java/surefire979/FailingStaticInitializerTest.java b/surefire-its/src/test/resources/surefire-979-smartStackTrace-wrongClassloader/module2/src/test/java/surefire979/FailingStaticInitializerTest.java index 3371fbd201..dd37362b9e 100644 --- a/surefire-its/src/test/resources/surefire-979-smartStackTrace-wrongClassloader/module2/src/test/java/surefire979/FailingStaticInitializerTest.java +++ b/surefire-its/src/test/resources/surefire-979-smartStackTrace-wrongClassloader/module2/src/test/java/surefire979/FailingStaticInitializerTest.java @@ -1,25 +1,6 @@ package surefire979; -/* - * 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.junit.Test; diff --git a/surefire-its/src/test/resources/surefire-985-parameterized-and-categories/src/test/java/sample/parameterized/Parameterized01Test.java b/surefire-its/src/test/resources/surefire-985-parameterized-and-categories/src/test/java/sample/parameterized/Parameterized01Test.java index d1bb29d7b5..7c34e952b9 100644 --- a/surefire-its/src/test/resources/surefire-985-parameterized-and-categories/src/test/java/sample/parameterized/Parameterized01Test.java +++ b/surefire-its/src/test/resources/surefire-985-parameterized-and-categories/src/test/java/sample/parameterized/Parameterized01Test.java @@ -1,24 +1,5 @@ package sample.parameterized; -/* - * 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 java.util.Arrays; import java.util.Collection; diff --git a/surefire-its/src/test/resources/surefire-985-parameterized-and-categories/src/test/java/sample/parameterized/Parameterized02Test.java b/surefire-its/src/test/resources/surefire-985-parameterized-and-categories/src/test/java/sample/parameterized/Parameterized02Test.java index c5ae22fe54..f1b3ff59b4 100644 --- a/surefire-its/src/test/resources/surefire-985-parameterized-and-categories/src/test/java/sample/parameterized/Parameterized02Test.java +++ b/surefire-its/src/test/resources/surefire-985-parameterized-and-categories/src/test/java/sample/parameterized/Parameterized02Test.java @@ -1,24 +1,5 @@ package sample.parameterized; -/* - * 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 java.util.Arrays; import java.util.Collection; diff --git a/surefire-its/src/test/resources/surefire-985-parameterized-and-categories/src/test/java/sample/parameterized/Parameterized03Test.java b/surefire-its/src/test/resources/surefire-985-parameterized-and-categories/src/test/java/sample/parameterized/Parameterized03Test.java index ac5dfad89c..7aa9bc6dc7 100644 --- a/surefire-its/src/test/resources/surefire-985-parameterized-and-categories/src/test/java/sample/parameterized/Parameterized03Test.java +++ b/surefire-its/src/test/resources/surefire-985-parameterized-and-categories/src/test/java/sample/parameterized/Parameterized03Test.java @@ -1,24 +1,5 @@ package sample.parameterized; -/* - * 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 java.util.Arrays; import java.util.Collection; diff --git a/surefire-its/src/test/resources/surefire-995-categoryInheritance/src/test/java/jiras/surefire955/CategorizedTest.java b/surefire-its/src/test/resources/surefire-995-categoryInheritance/src/test/java/jiras/surefire955/CategorizedTest.java index a25b15a6ab..0370595192 100644 --- a/surefire-its/src/test/resources/surefire-995-categoryInheritance/src/test/java/jiras/surefire955/CategorizedTest.java +++ b/surefire-its/src/test/resources/surefire-995-categoryInheritance/src/test/java/jiras/surefire955/CategorizedTest.java @@ -1,24 +1,5 @@ package jiras.surefire955; -/* - * 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.junit.Test; import org.junit.experimental.categories.Category; diff --git a/surefire-its/src/test/resources/surefire-995-categoryInheritance/src/test/java/jiras/surefire955/NotIncludedTest.java b/surefire-its/src/test/resources/surefire-995-categoryInheritance/src/test/java/jiras/surefire955/NotIncludedTest.java index c52bff08ef..f472bf9e8f 100644 --- a/surefire-its/src/test/resources/surefire-995-categoryInheritance/src/test/java/jiras/surefire955/NotIncludedTest.java +++ b/surefire-its/src/test/resources/surefire-995-categoryInheritance/src/test/java/jiras/surefire955/NotIncludedTest.java @@ -1,24 +1,5 @@ package jiras.surefire955; -/* - * 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.junit.Test; public class NotIncludedTest diff --git a/surefire-its/src/test/resources/surefire-995-categoryInheritance/src/test/java/jiras/surefire955/SpecialCategorizedTest.java b/surefire-its/src/test/resources/surefire-995-categoryInheritance/src/test/java/jiras/surefire955/SpecialCategorizedTest.java index 8082f43de2..fe61f9e27c 100644 --- a/surefire-its/src/test/resources/surefire-995-categoryInheritance/src/test/java/jiras/surefire955/SpecialCategorizedTest.java +++ b/surefire-its/src/test/resources/surefire-995-categoryInheritance/src/test/java/jiras/surefire955/SpecialCategorizedTest.java @@ -1,24 +1,5 @@ package jiras.surefire955; -/* - * 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.junit.Test; public final class SpecialCategorizedTest diff --git a/surefire-its/src/test/resources/surefire-995-categoryInheritance/src/test/java/jiras/surefire955/SpecialNonCategoryTest.java b/surefire-its/src/test/resources/surefire-995-categoryInheritance/src/test/java/jiras/surefire955/SpecialNonCategoryTest.java index 853ae50c7f..fdd4090440 100644 --- a/surefire-its/src/test/resources/surefire-995-categoryInheritance/src/test/java/jiras/surefire955/SpecialNonCategoryTest.java +++ b/surefire-its/src/test/resources/surefire-995-categoryInheritance/src/test/java/jiras/surefire955/SpecialNonCategoryTest.java @@ -1,24 +1,5 @@ package jiras.surefire955; -/* - * 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.junit.Test; public class SpecialNonCategoryTest diff --git a/surefire-its/src/test/resources/surefire-995-categoryInheritance/src/test/java/jiras/surefire955/group/ABCTest.java b/surefire-its/src/test/resources/surefire-995-categoryInheritance/src/test/java/jiras/surefire955/group/ABCTest.java index 1d37ff5642..b236f755fd 100644 --- a/surefire-its/src/test/resources/surefire-995-categoryInheritance/src/test/java/jiras/surefire955/group/ABCTest.java +++ b/surefire-its/src/test/resources/surefire-995-categoryInheritance/src/test/java/jiras/surefire955/group/ABCTest.java @@ -1,24 +1,5 @@ package jiras.surefire955.group; -/* - * 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 jiras.surefire955.group.marker.CategoryA; import org.junit.Test; import org.junit.experimental.categories.Category; diff --git a/surefire-its/src/test/resources/surefire-995-categoryInheritance/src/test/java/jiras/surefire955/group/ATest.java b/surefire-its/src/test/resources/surefire-995-categoryInheritance/src/test/java/jiras/surefire955/group/ATest.java index 0fef6c8521..4c201b4cb3 100644 --- a/surefire-its/src/test/resources/surefire-995-categoryInheritance/src/test/java/jiras/surefire955/group/ATest.java +++ b/surefire-its/src/test/resources/surefire-995-categoryInheritance/src/test/java/jiras/surefire955/group/ATest.java @@ -1,24 +1,5 @@ package jiras.surefire955.group; -/* - * 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 jiras.surefire955.group.marker.CategoryA; import org.junit.Test; import org.junit.experimental.categories.Category; diff --git a/surefire-its/src/test/resources/surefire-995-categoryInheritance/src/test/java/jiras/surefire955/group/AbstractBCTest.java b/surefire-its/src/test/resources/surefire-995-categoryInheritance/src/test/java/jiras/surefire955/group/AbstractBCTest.java index 85119178b7..f2e510d390 100644 --- a/surefire-its/src/test/resources/surefire-995-categoryInheritance/src/test/java/jiras/surefire955/group/AbstractBCTest.java +++ b/surefire-its/src/test/resources/surefire-995-categoryInheritance/src/test/java/jiras/surefire955/group/AbstractBCTest.java @@ -1,24 +1,5 @@ package jiras.surefire955.group; -/* - * 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 jiras.surefire955.group.marker.CategoryB; import org.junit.Test; import org.junit.experimental.categories.Category; diff --git a/surefire-its/src/test/resources/surefire-995-categoryInheritance/src/test/java/jiras/surefire955/group/AbstractCTest.java b/surefire-its/src/test/resources/surefire-995-categoryInheritance/src/test/java/jiras/surefire955/group/AbstractCTest.java index 34745c6151..355f445947 100644 --- a/surefire-its/src/test/resources/surefire-995-categoryInheritance/src/test/java/jiras/surefire955/group/AbstractCTest.java +++ b/surefire-its/src/test/resources/surefire-995-categoryInheritance/src/test/java/jiras/surefire955/group/AbstractCTest.java @@ -1,24 +1,5 @@ package jiras.surefire955.group; -/* - * 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 jiras.surefire955.group.marker.CategoryC; import org.junit.Test; import org.junit.experimental.categories.Category; diff --git a/surefire-its/src/test/resources/surefire-995-categoryInheritance/src/test/java/jiras/surefire955/group/BBCTest.java b/surefire-its/src/test/resources/surefire-995-categoryInheritance/src/test/java/jiras/surefire955/group/BBCTest.java index 0fbe803395..4d4949c02c 100644 --- a/surefire-its/src/test/resources/surefire-995-categoryInheritance/src/test/java/jiras/surefire955/group/BBCTest.java +++ b/surefire-its/src/test/resources/surefire-995-categoryInheritance/src/test/java/jiras/surefire955/group/BBCTest.java @@ -1,24 +1,5 @@ package jiras.surefire955.group; -/* - * 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 jiras.surefire955.group.marker.CategoryB; import org.junit.Test; import org.junit.experimental.categories.Category; diff --git a/surefire-its/src/test/resources/surefire-995-categoryInheritance/src/test/java/jiras/surefire955/group/BCTest.java b/surefire-its/src/test/resources/surefire-995-categoryInheritance/src/test/java/jiras/surefire955/group/BCTest.java index e99c2b69a8..40e8c76839 100644 --- a/surefire-its/src/test/resources/surefire-995-categoryInheritance/src/test/java/jiras/surefire955/group/BCTest.java +++ b/surefire-its/src/test/resources/surefire-995-categoryInheritance/src/test/java/jiras/surefire955/group/BCTest.java @@ -1,24 +1,5 @@ package jiras.surefire955.group; -/* - * 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.junit.Test; public class BCTest extends jiras.surefire955.group.AbstractBCTest diff --git a/surefire-its/src/test/resources/surefire-995-categoryInheritance/src/test/java/jiras/surefire955/group/BTest.java b/surefire-its/src/test/resources/surefire-995-categoryInheritance/src/test/java/jiras/surefire955/group/BTest.java index d0bf839af8..07720b9444 100644 --- a/surefire-its/src/test/resources/surefire-995-categoryInheritance/src/test/java/jiras/surefire955/group/BTest.java +++ b/surefire-its/src/test/resources/surefire-995-categoryInheritance/src/test/java/jiras/surefire955/group/BTest.java @@ -1,24 +1,5 @@ package jiras.surefire955.group; -/* - * 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 jiras.surefire955.group.marker.CategoryB; import org.junit.Test; import org.junit.experimental.categories.Category; diff --git a/surefire-its/src/test/resources/surefire-995-categoryInheritance/src/test/java/jiras/surefire955/group/UncategorizedTest.java b/surefire-its/src/test/resources/surefire-995-categoryInheritance/src/test/java/jiras/surefire955/group/UncategorizedTest.java index 06f8554bb0..5c142fd3e9 100644 --- a/surefire-its/src/test/resources/surefire-995-categoryInheritance/src/test/java/jiras/surefire955/group/UncategorizedTest.java +++ b/surefire-its/src/test/resources/surefire-995-categoryInheritance/src/test/java/jiras/surefire955/group/UncategorizedTest.java @@ -1,24 +1,5 @@ package jiras.surefire955.group; -/* - * 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.junit.Test; public class UncategorizedTest diff --git a/surefire-its/src/test/resources/system-properties/src/test/java/systemProperties/BasicTest.java b/surefire-its/src/test/resources/system-properties/src/test/java/systemProperties/BasicTest.java index caf96cb517..984079e138 100644 --- a/surefire-its/src/test/resources/system-properties/src/test/java/systemProperties/BasicTest.java +++ b/surefire-its/src/test/resources/system-properties/src/test/java/systemProperties/BasicTest.java @@ -1,24 +1,5 @@ package systemProperties; -/* - * 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 java.io.File; import junit.framework.TestCase; diff --git a/surefire-its/src/test/resources/testng-740-parallel-without-threadcount/src/test/java/testng740/TestNG740ParallelTest.java b/surefire-its/src/test/resources/testng-740-parallel-without-threadcount/src/test/java/testng740/TestNG740ParallelTest.java index 855b92fa05..70ad3a9cae 100644 --- a/surefire-its/src/test/resources/testng-740-parallel-without-threadcount/src/test/java/testng740/TestNG740ParallelTest.java +++ b/surefire-its/src/test/resources/testng-740-parallel-without-threadcount/src/test/java/testng740/TestNG740ParallelTest.java @@ -1,24 +1,5 @@ package testng.simple; -/* - * 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.testng.annotations.Test; diff --git a/surefire-its/src/test/resources/testng-740-parallel/src/test/java/testng740/TestNG740ParallelTest.java b/surefire-its/src/test/resources/testng-740-parallel/src/test/java/testng740/TestNG740ParallelTest.java index 855b92fa05..70ad3a9cae 100644 --- a/surefire-its/src/test/resources/testng-740-parallel/src/test/java/testng740/TestNG740ParallelTest.java +++ b/surefire-its/src/test/resources/testng-740-parallel/src/test/java/testng740/TestNG740ParallelTest.java @@ -1,24 +1,5 @@ package testng.simple; -/* - * 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.testng.annotations.Test; diff --git a/surefire-its/src/test/resources/testng-afterSuiteFailure/src/test/java/testng/afterSuiteFailure/TestNGSuiteTest.java b/surefire-its/src/test/resources/testng-afterSuiteFailure/src/test/java/testng/afterSuiteFailure/TestNGSuiteTest.java index 0d93e1bd64..121a94bfbd 100644 --- a/surefire-its/src/test/resources/testng-afterSuiteFailure/src/test/java/testng/afterSuiteFailure/TestNGSuiteTest.java +++ b/surefire-its/src/test/resources/testng-afterSuiteFailure/src/test/java/testng/afterSuiteFailure/TestNGSuiteTest.java @@ -1,24 +1,5 @@ package testng.afterSuiteFailure; -/* - * 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.testng.Assert; import org.testng.annotations.AfterSuite; import org.testng.annotations.Test; @@ -37,4 +18,4 @@ public void failAfterSuite() { Assert.fail(); } -} \ No newline at end of file +} diff --git a/surefire-its/src/test/resources/testng-beforeMethod/src/test/java/testng/beforeMethod/TestNGSuiteTest.java b/surefire-its/src/test/resources/testng-beforeMethod/src/test/java/testng/beforeMethod/TestNGSuiteTest.java index bdbad433cb..4a298ae044 100644 --- a/surefire-its/src/test/resources/testng-beforeMethod/src/test/java/testng/beforeMethod/TestNGSuiteTest.java +++ b/surefire-its/src/test/resources/testng-beforeMethod/src/test/java/testng/beforeMethod/TestNGSuiteTest.java @@ -1,24 +1,5 @@ package testng.beforeMethod; -/* - * 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.testng.Assert; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; @@ -37,4 +18,4 @@ public void testBeforeMethod() { Assert.assertTrue( beforeMethod ); } -} \ No newline at end of file +} diff --git a/surefire-its/src/test/resources/testng-beforeMethodFailure/src/test/java/testng/beforeMethodFailure/TestNGSuiteTest.java b/surefire-its/src/test/resources/testng-beforeMethodFailure/src/test/java/testng/beforeMethodFailure/TestNGSuiteTest.java index 58786f0bef..f0a6275b5c 100644 --- a/surefire-its/src/test/resources/testng-beforeMethodFailure/src/test/java/testng/beforeMethodFailure/TestNGSuiteTest.java +++ b/surefire-its/src/test/resources/testng-beforeMethodFailure/src/test/java/testng/beforeMethodFailure/TestNGSuiteTest.java @@ -1,24 +1,5 @@ package testng.beforeMethodFailure; -/* - * 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.testng.Assert; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; @@ -37,4 +18,4 @@ public void testBeforeMethod() { Assert.assertTrue( beforeMethod ); } -} \ No newline at end of file +} diff --git a/surefire-its/src/test/resources/testng-execute-error/src/test/java/it/BasicTest.java b/surefire-its/src/test/resources/testng-execute-error/src/test/java/it/BasicTest.java index e601daf032..d5d6f08bcc 100644 --- a/surefire-its/src/test/resources/testng-execute-error/src/test/java/it/BasicTest.java +++ b/surefire-its/src/test/resources/testng-execute-error/src/test/java/it/BasicTest.java @@ -1,24 +1,5 @@ package it; -/* - * 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 static org.testng.Assert.*; import org.testng.annotations.*; diff --git a/surefire-its/src/test/resources/testng-group-thread-parallel/src/test/java/testng/groupThreadParallel/TestNGTest.java b/surefire-its/src/test/resources/testng-group-thread-parallel/src/test/java/testng/groupThreadParallel/TestNGTest.java index 9ccdef113e..ae7b4d6145 100644 --- a/surefire-its/src/test/resources/testng-group-thread-parallel/src/test/java/testng/groupThreadParallel/TestNGTest.java +++ b/surefire-its/src/test/resources/testng-group-thread-parallel/src/test/java/testng/groupThreadParallel/TestNGTest.java @@ -1,24 +1,5 @@ package testng.groupThreadParallel; -/* - * 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.testng.Assert; import org.testng.annotations.AfterSuite; import org.testng.annotations.BeforeClass; @@ -110,4 +91,4 @@ public void shouldNotRun() { Assert.fail( "Group specified by test shouldnt be run." ); } -} \ No newline at end of file +} diff --git a/surefire-its/src/test/resources/testng-groups/src/test/java/testng/groups/TestNGGroupTest.java b/surefire-its/src/test/resources/testng-groups/src/test/java/testng/groups/TestNGGroupTest.java index 5d84bbad0c..61196ce6db 100644 --- a/surefire-its/src/test/resources/testng-groups/src/test/java/testng/groups/TestNGGroupTest.java +++ b/surefire-its/src/test/resources/testng-groups/src/test/java/testng/groups/TestNGGroupTest.java @@ -1,24 +1,5 @@ package testng.groups; -/* - * 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.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; diff --git a/surefire-its/src/test/resources/testng-jdk14/src/test/java/testng/jdk14/TestNGJavadocTest.java b/surefire-its/src/test/resources/testng-jdk14/src/test/java/testng/jdk14/TestNGJavadocTest.java index 25dd31a661..90bb4f2a40 100644 --- a/surefire-its/src/test/resources/testng-jdk14/src/test/java/testng/jdk14/TestNGJavadocTest.java +++ b/surefire-its/src/test/resources/testng-jdk14/src/test/java/testng/jdk14/TestNGJavadocTest.java @@ -1,24 +1,5 @@ package testng.jdk14; -/* - * 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.testng.Assert; /** @@ -60,4 +41,4 @@ public void shouldNotRun() { Assert.assertTrue( false, "Group specified by test shouldnt be run." ); } -} \ No newline at end of file +} diff --git a/surefire-its/src/test/resources/testng-junit4-together/src/test/java/Junit4NoRunWithTest.java b/surefire-its/src/test/resources/testng-junit4-together/src/test/java/Junit4NoRunWithTest.java index a7b6934789..3dc64b7d66 100644 --- a/surefire-its/src/test/resources/testng-junit4-together/src/test/java/Junit4NoRunWithTest.java +++ b/surefire-its/src/test/resources/testng-junit4-together/src/test/java/Junit4NoRunWithTest.java @@ -1,22 +1,3 @@ -/* - * 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 static org.junit.Assert.assertNotNull; import org.junit.Before; diff --git a/surefire-its/src/test/resources/testng-junit4-together/src/test/java/Junit4SimpleRunWithTest.java b/surefire-its/src/test/resources/testng-junit4-together/src/test/java/Junit4SimpleRunWithTest.java index d9a64209d9..f167792dde 100644 --- a/surefire-its/src/test/resources/testng-junit4-together/src/test/java/Junit4SimpleRunWithTest.java +++ b/surefire-its/src/test/resources/testng-junit4-together/src/test/java/Junit4SimpleRunWithTest.java @@ -1,22 +1,3 @@ -/* - * 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 static org.junit.Assert.assertNotNull; import org.junit.Before; diff --git a/surefire-its/src/test/resources/testng-junit4-together/src/test/java/TestNGTest.java b/surefire-its/src/test/resources/testng-junit4-together/src/test/java/TestNGTest.java index a7edb4a19f..1970e1d93d 100644 --- a/surefire-its/src/test/resources/testng-junit4-together/src/test/java/TestNGTest.java +++ b/surefire-its/src/test/resources/testng-junit4-together/src/test/java/TestNGTest.java @@ -1,22 +1,3 @@ -/* - * 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.testng.annotations.BeforeClass; import org.testng.annotations.Test; diff --git a/surefire-its/src/test/resources/testng-listener-reporter/src/test/java/listenReport/FileHelper.java b/surefire-its/src/test/resources/testng-listener-reporter/src/test/java/listenReport/FileHelper.java index 291adb4af6..5136636fde 100644 --- a/surefire-its/src/test/resources/testng-listener-reporter/src/test/java/listenReport/FileHelper.java +++ b/surefire-its/src/test/resources/testng-listener-reporter/src/test/java/listenReport/FileHelper.java @@ -1,24 +1,5 @@ package listenReport; -/* - * 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 java.io.File; import java.io.FileWriter; import java.io.IOException; diff --git a/surefire-its/src/test/resources/testng-listener-reporter/src/test/java/listenReport/Reporter.java b/surefire-its/src/test/resources/testng-listener-reporter/src/test/java/listenReport/Reporter.java index 45862700b5..dc7703548a 100644 --- a/surefire-its/src/test/resources/testng-listener-reporter/src/test/java/listenReport/Reporter.java +++ b/surefire-its/src/test/resources/testng-listener-reporter/src/test/java/listenReport/Reporter.java @@ -1,24 +1,5 @@ package listenReport; -/* - * 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 java.util.List; import org.testng.IReporter; diff --git a/surefire-its/src/test/resources/testng-listener-reporter/src/test/java/listenReport/ResultListener.java b/surefire-its/src/test/resources/testng-listener-reporter/src/test/java/listenReport/ResultListener.java index fd1f461ad9..fa5fc2e19f 100644 --- a/surefire-its/src/test/resources/testng-listener-reporter/src/test/java/listenReport/ResultListener.java +++ b/surefire-its/src/test/resources/testng-listener-reporter/src/test/java/listenReport/ResultListener.java @@ -1,24 +1,5 @@ package listenReport; -/* - * 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.testng.ITestContext; import org.testng.ITestResult; import org.testng.internal.IResultListener; diff --git a/surefire-its/src/test/resources/testng-listener-reporter/src/test/java/listenReport/SuiteListener.java b/surefire-its/src/test/resources/testng-listener-reporter/src/test/java/listenReport/SuiteListener.java index 48a86b4ca4..57e948612b 100644 --- a/surefire-its/src/test/resources/testng-listener-reporter/src/test/java/listenReport/SuiteListener.java +++ b/surefire-its/src/test/resources/testng-listener-reporter/src/test/java/listenReport/SuiteListener.java @@ -1,24 +1,5 @@ package listenReport; -/* - * 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.testng.ISuite; import org.testng.ISuiteListener; diff --git a/surefire-its/src/test/resources/testng-listener-reporter/src/test/java/listenReport/TestNGSuiteTest.java b/surefire-its/src/test/resources/testng-listener-reporter/src/test/java/listenReport/TestNGSuiteTest.java index 3e278349a1..7483cb0f74 100644 --- a/surefire-its/src/test/resources/testng-listener-reporter/src/test/java/listenReport/TestNGSuiteTest.java +++ b/surefire-its/src/test/resources/testng-listener-reporter/src/test/java/listenReport/TestNGSuiteTest.java @@ -1,24 +1,5 @@ package listenReport; -/* - * 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.testng.annotations.Test; @@ -29,4 +10,4 @@ public void doNothing() { } -} \ No newline at end of file +} diff --git a/surefire-its/src/test/resources/testng-listeners/src/test/java/listeners/SimpleTest.java b/surefire-its/src/test/resources/testng-listeners/src/test/java/listeners/SimpleTest.java index f4204a1240..c90ea78d34 100644 --- a/surefire-its/src/test/resources/testng-listeners/src/test/java/listeners/SimpleTest.java +++ b/surefire-its/src/test/resources/testng-listeners/src/test/java/listeners/SimpleTest.java @@ -1,24 +1,5 @@ package listeners; -/* - * 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.testng.annotations.Listeners; import org.testng.annotations.Test; diff --git a/surefire-its/src/test/resources/testng-method-pattern-after/src/test/java/testng/BasicTest.java b/surefire-its/src/test/resources/testng-method-pattern-after/src/test/java/testng/BasicTest.java index 468e425e53..7aa5d29b49 100644 --- a/surefire-its/src/test/resources/testng-method-pattern-after/src/test/java/testng/BasicTest.java +++ b/surefire-its/src/test/resources/testng-method-pattern-after/src/test/java/testng/BasicTest.java @@ -1,24 +1,5 @@ package testng; -/* - * 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.testng.annotations.*; import org.testng.Assert; diff --git a/surefire-its/src/test/resources/testng-method-pattern-before/src/test/java/testng/BasicTest.java b/surefire-its/src/test/resources/testng-method-pattern-before/src/test/java/testng/BasicTest.java index 468e425e53..7aa5d29b49 100644 --- a/surefire-its/src/test/resources/testng-method-pattern-before/src/test/java/testng/BasicTest.java +++ b/surefire-its/src/test/resources/testng-method-pattern-before/src/test/java/testng/BasicTest.java @@ -1,24 +1,5 @@ package testng; -/* - * 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.testng.annotations.*; import org.testng.Assert; diff --git a/surefire-its/src/test/resources/testng-method-pattern/src/test/java/testng/BasicTest.java b/surefire-its/src/test/resources/testng-method-pattern/src/test/java/testng/BasicTest.java index 381016cf03..ce57dd86b6 100644 --- a/surefire-its/src/test/resources/testng-method-pattern/src/test/java/testng/BasicTest.java +++ b/surefire-its/src/test/resources/testng-method-pattern/src/test/java/testng/BasicTest.java @@ -1,24 +1,5 @@ package testng; -/* - * 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.testng.annotations.*; import org.testng.Assert; diff --git a/surefire-its/src/test/resources/testng-multiple-method-patterns/src/test/java/jiras/surefire745/BasicTest.java b/surefire-its/src/test/resources/testng-multiple-method-patterns/src/test/java/jiras/surefire745/BasicTest.java index 3e2728e670..9aed7db9b3 100644 --- a/surefire-its/src/test/resources/testng-multiple-method-patterns/src/test/java/jiras/surefire745/BasicTest.java +++ b/surefire-its/src/test/resources/testng-multiple-method-patterns/src/test/java/jiras/surefire745/BasicTest.java @@ -1,25 +1,6 @@ package jiras.surefire745; -/* - * 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.testng.annotations.*; import static org.testng.Assert.*; diff --git a/surefire-its/src/test/resources/testng-multiple-method-patterns/src/test/java/jiras/surefire745/TestFive.java b/surefire-its/src/test/resources/testng-multiple-method-patterns/src/test/java/jiras/surefire745/TestFive.java index d11ef5d073..bca632a31b 100644 --- a/surefire-its/src/test/resources/testng-multiple-method-patterns/src/test/java/jiras/surefire745/TestFive.java +++ b/surefire-its/src/test/resources/testng-multiple-method-patterns/src/test/java/jiras/surefire745/TestFive.java @@ -1,24 +1,5 @@ package jiras.surefire745; -/* - * 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.testng.annotations.*; public class TestFive diff --git a/surefire-its/src/test/resources/testng-multiple-method-patterns/src/test/java/jiras/surefire745/TestFour.java b/surefire-its/src/test/resources/testng-multiple-method-patterns/src/test/java/jiras/surefire745/TestFour.java index 0b1b6c678a..2580bb2ff8 100644 --- a/surefire-its/src/test/resources/testng-multiple-method-patterns/src/test/java/jiras/surefire745/TestFour.java +++ b/surefire-its/src/test/resources/testng-multiple-method-patterns/src/test/java/jiras/surefire745/TestFour.java @@ -1,24 +1,5 @@ package jiras.surefire745; -/* - * 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.testng.annotations.*; public class TestFour diff --git a/surefire-its/src/test/resources/testng-multiple-method-patterns/src/test/java/jiras/surefire745/TestThree.java b/surefire-its/src/test/resources/testng-multiple-method-patterns/src/test/java/jiras/surefire745/TestThree.java index 0d290dcffb..018c12bfb9 100644 --- a/surefire-its/src/test/resources/testng-multiple-method-patterns/src/test/java/jiras/surefire745/TestThree.java +++ b/surefire-its/src/test/resources/testng-multiple-method-patterns/src/test/java/jiras/surefire745/TestThree.java @@ -1,24 +1,5 @@ package jiras.surefire745; -/* - * 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.testng.annotations.*; import static org.testng.Assert.*; diff --git a/surefire-its/src/test/resources/testng-multiple-method-patterns/src/test/java/jiras/surefire745/TestTwo.java b/surefire-its/src/test/resources/testng-multiple-method-patterns/src/test/java/jiras/surefire745/TestTwo.java index 4e1b56dead..5a61c586e5 100644 --- a/surefire-its/src/test/resources/testng-multiple-method-patterns/src/test/java/jiras/surefire745/TestTwo.java +++ b/surefire-its/src/test/resources/testng-multiple-method-patterns/src/test/java/jiras/surefire745/TestTwo.java @@ -1,24 +1,5 @@ package jiras.surefire745; -/* - * 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.testng.annotations.*; public class TestTwo diff --git a/surefire-its/src/test/resources/testng-parallel-suites/src/test/java/testng/suiteXml/ShouldNotRunTest.java b/surefire-its/src/test/resources/testng-parallel-suites/src/test/java/testng/suiteXml/ShouldNotRunTest.java index d2eb9cac8e..1b9e7bf4b0 100644 --- a/surefire-its/src/test/resources/testng-parallel-suites/src/test/java/testng/suiteXml/ShouldNotRunTest.java +++ b/surefire-its/src/test/resources/testng-parallel-suites/src/test/java/testng/suiteXml/ShouldNotRunTest.java @@ -1,24 +1,5 @@ package testng.suiteXml; -/* - * 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.testng.annotations.Test; /** @@ -32,4 +13,4 @@ public void shouldNotRun() { System.out.println( getClass().getSimpleName() + "#shouldNotRun()" ); } -} \ No newline at end of file +} diff --git a/surefire-its/src/test/resources/testng-parallel-suites/src/test/java/testng/suiteXml/TestNGSuiteTest.java b/surefire-its/src/test/resources/testng-parallel-suites/src/test/java/testng/suiteXml/TestNGSuiteTest.java index be91c4885e..179db0b14a 100644 --- a/surefire-its/src/test/resources/testng-parallel-suites/src/test/java/testng/suiteXml/TestNGSuiteTest.java +++ b/surefire-its/src/test/resources/testng-parallel-suites/src/test/java/testng/suiteXml/TestNGSuiteTest.java @@ -1,24 +1,5 @@ package testng.suiteXml; -/* - * 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.testng.annotations.Test; import java.nio.charset.Charset; @@ -43,4 +24,4 @@ public void shouldRunAndPrintItself() TimeUnit.SECONDS.sleep( 2 ); } -} \ No newline at end of file +} diff --git a/surefire-its/src/test/resources/testng-path with spaces/src/test/java/testng/pathWithSpaces/TestNGSuiteTest.java b/surefire-its/src/test/resources/testng-path with spaces/src/test/java/testng/pathWithSpaces/TestNGSuiteTest.java index 92549a30ac..41fd6729f3 100644 --- a/surefire-its/src/test/resources/testng-path with spaces/src/test/java/testng/pathWithSpaces/TestNGSuiteTest.java +++ b/surefire-its/src/test/resources/testng-path with spaces/src/test/java/testng/pathWithSpaces/TestNGSuiteTest.java @@ -1,24 +1,5 @@ package testng.pathWithSpaces; -/* - * 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 java.io.File; import java.net.URISyntaxException; @@ -32,4 +13,4 @@ public void loadTestResourceWithSpaces() throws URISyntaxException { new File( getClass().getResource( "/test.txt" ).toURI() ); } -} \ No newline at end of file +} diff --git a/surefire-its/src/test/resources/testng-simple/src/test/java/testng/simple/TestNGSuiteTestA.java b/surefire-its/src/test/resources/testng-simple/src/test/java/testng/simple/TestNGSuiteTestA.java index 6f97d09ce3..9c25e2668f 100644 --- a/surefire-its/src/test/resources/testng-simple/src/test/java/testng/simple/TestNGSuiteTestA.java +++ b/surefire-its/src/test/resources/testng-simple/src/test/java/testng/simple/TestNGSuiteTestA.java @@ -1,24 +1,5 @@ package testng.simple; -/* - * 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.testng.annotations.Test; @@ -29,4 +10,4 @@ public void doNothing() { } -} \ No newline at end of file +} diff --git a/surefire-its/src/test/resources/testng-simple/src/test/java/testng/simple/TestNGSuiteTestB.java b/surefire-its/src/test/resources/testng-simple/src/test/java/testng/simple/TestNGSuiteTestB.java index e8d856d324..db97fbc762 100644 --- a/surefire-its/src/test/resources/testng-simple/src/test/java/testng/simple/TestNGSuiteTestB.java +++ b/surefire-its/src/test/resources/testng-simple/src/test/java/testng/simple/TestNGSuiteTestB.java @@ -1,24 +1,5 @@ package testng.simple; -/* - * 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.testng.annotations.Test; @@ -29,4 +10,4 @@ public void doNothing() { } -} \ No newline at end of file +} diff --git a/surefire-its/src/test/resources/testng-simple/src/test/java/testng/simple/TestNGSuiteTestC.java b/surefire-its/src/test/resources/testng-simple/src/test/java/testng/simple/TestNGSuiteTestC.java index 751feff3d8..c85893cc77 100644 --- a/surefire-its/src/test/resources/testng-simple/src/test/java/testng/simple/TestNGSuiteTestC.java +++ b/surefire-its/src/test/resources/testng-simple/src/test/java/testng/simple/TestNGSuiteTestC.java @@ -1,24 +1,5 @@ package testng.simple; -/* - * 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.testng.annotations.Test; @@ -29,4 +10,4 @@ public void doNothing() { } -} \ No newline at end of file +} diff --git a/surefire-its/src/test/resources/testng-single-method-5-14-9/src/test/java/testng/BasicTest.java b/surefire-its/src/test/resources/testng-single-method-5-14-9/src/test/java/testng/BasicTest.java index 381016cf03..ce57dd86b6 100644 --- a/surefire-its/src/test/resources/testng-single-method-5-14-9/src/test/java/testng/BasicTest.java +++ b/surefire-its/src/test/resources/testng-single-method-5-14-9/src/test/java/testng/BasicTest.java @@ -1,24 +1,5 @@ package testng; -/* - * 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.testng.annotations.*; import org.testng.Assert; diff --git a/surefire-its/src/test/resources/testng-single-method/src/test/java/testng/BasicTest.java b/surefire-its/src/test/resources/testng-single-method/src/test/java/testng/BasicTest.java index 381016cf03..ce57dd86b6 100644 --- a/surefire-its/src/test/resources/testng-single-method/src/test/java/testng/BasicTest.java +++ b/surefire-its/src/test/resources/testng-single-method/src/test/java/testng/BasicTest.java @@ -1,24 +1,5 @@ package testng; -/* - * 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.testng.annotations.*; import org.testng.Assert; diff --git a/surefire-its/src/test/resources/testng-succes-percentage/src/test/java/testng/TestNGSuccessPercentFailingTest.java b/surefire-its/src/test/resources/testng-succes-percentage/src/test/java/testng/TestNGSuccessPercentFailingTest.java index 791869c5b7..5e60b4be94 100644 --- a/surefire-its/src/test/resources/testng-succes-percentage/src/test/java/testng/TestNGSuccessPercentFailingTest.java +++ b/surefire-its/src/test/resources/testng-succes-percentage/src/test/java/testng/TestNGSuccessPercentFailingTest.java @@ -1,24 +1,5 @@ package testng; -/* - * 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.testng.annotations.*; import static org.testng.Assert.*; import java.util.concurrent.atomic.AtomicInteger; diff --git a/surefire-its/src/test/resources/testng-succes-percentage/src/test/java/testng/TestNGSuccessPercentPassingTest.java b/surefire-its/src/test/resources/testng-succes-percentage/src/test/java/testng/TestNGSuccessPercentPassingTest.java index 35a1be4fa9..11cac3bccf 100644 --- a/surefire-its/src/test/resources/testng-succes-percentage/src/test/java/testng/TestNGSuccessPercentPassingTest.java +++ b/surefire-its/src/test/resources/testng-succes-percentage/src/test/java/testng/TestNGSuccessPercentPassingTest.java @@ -1,24 +1,5 @@ package testng; -/* - * 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.testng.annotations.*; import static org.testng.Assert.*; import java.util.concurrent.atomic.AtomicInteger; diff --git a/surefire-its/src/test/resources/testng-suite-xml/src/test/java/testng/suiteXml/TestNGSuiteTest.java b/surefire-its/src/test/resources/testng-suite-xml/src/test/java/testng/suiteXml/TestNGSuiteTest.java index 0ebf3dfea1..228a9d9e25 100644 --- a/surefire-its/src/test/resources/testng-suite-xml/src/test/java/testng/suiteXml/TestNGSuiteTest.java +++ b/surefire-its/src/test/resources/testng-suite-xml/src/test/java/testng/suiteXml/TestNGSuiteTest.java @@ -1,24 +1,5 @@ package testng.suiteXml; -/* - * 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.testng.annotations.BeforeClass; import org.testng.annotations.Test; @@ -51,4 +32,4 @@ public void isTestObjectNull() { assert testObject != null : "testObject is null"; } -} \ No newline at end of file +} diff --git a/surefire-its/src/test/resources/testng-twoTestCaseSuite/src/test/java/testng/two/TestNGTestTwo.java b/surefire-its/src/test/resources/testng-twoTestCaseSuite/src/test/java/testng/two/TestNGTestTwo.java index 9ab2c86d39..f4a9dec7bd 100644 --- a/surefire-its/src/test/resources/testng-twoTestCaseSuite/src/test/java/testng/two/TestNGTestTwo.java +++ b/surefire-its/src/test/resources/testng-twoTestCaseSuite/src/test/java/testng/two/TestNGTestTwo.java @@ -1,24 +1,5 @@ package testng.two; -/* - * 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.testng.annotations.Test; @@ -29,4 +10,4 @@ public void testTwo() { } -} \ No newline at end of file +} diff --git a/surefire-its/src/test/resources/unicode-testnames/src/test/java/junit/twoTestCases/EscapeTest.java b/surefire-its/src/test/resources/unicode-testnames/src/test/java/junit/twoTestCases/EscapeTest.java index 69ea6e1883..02961a651b 100644 --- a/surefire-its/src/test/resources/unicode-testnames/src/test/java/junit/twoTestCases/EscapeTest.java +++ b/surefire-its/src/test/resources/unicode-testnames/src/test/java/junit/twoTestCases/EscapeTest.java @@ -1,24 +1,5 @@ package junit.twoTestCases; -/* - * 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 junit.extensions.TestSetup; import junit.framework.Test; import junit.framework.TestCase; diff --git a/surefire-its/src/test/resources/unicode-testnames/src/test/java/junit/twoTestCases/XXYZTest.java b/surefire-its/src/test/resources/unicode-testnames/src/test/java/junit/twoTestCases/XXYZTest.java index 6496e1bf1a..db11855c86 100644 --- a/surefire-its/src/test/resources/unicode-testnames/src/test/java/junit/twoTestCases/XXYZTest.java +++ b/surefire-its/src/test/resources/unicode-testnames/src/test/java/junit/twoTestCases/XXYZTest.java @@ -1,23 +1,4 @@ package junit.twoTestCases; -/* - * 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 junit.framework.TestCase; diff --git a/surefire-its/src/test/resources/webapp/src/test/java/WebAppTest.java b/surefire-its/src/test/resources/webapp/src/test/java/WebAppTest.java index b4c4e15f9b..a71edeb907 100644 --- a/surefire-its/src/test/resources/webapp/src/test/java/WebAppTest.java +++ b/surefire-its/src/test/resources/webapp/src/test/java/WebAppTest.java @@ -1,22 +1,3 @@ -/* - * 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 java.io.InputStream; import java.net.URL; diff --git a/surefire-logger-api/pom.xml b/surefire-logger-api/pom.xml index 5e46b9b67e..755b49eb80 100644 --- a/surefire-logger-api/pom.xml +++ b/surefire-logger-api/pom.xml @@ -18,79 +18,78 @@ ~ under the License. --> - 4.0.0 + 4.0.0 - - org.apache.maven.surefire - surefire - 3.0.0-M10-SNAPSHOT - + + org.apache.maven.surefire + surefire + 3.0.0-M10-SNAPSHOT + - surefire-logger-api + surefire-logger-api - SureFire Logger API - - Interfaces and Utilities related only to internal SureFire Logger API. Free of dependencies. - + SureFire Logger API + Interfaces and Utilities related only to internal SureFire Logger API. Free of dependencies. - - UTF-8 - + + + tibordigana + Tibor Digaňa (tibor17) + tibordigana@apache.org + + PMC + + Europe/Bratislava + + - - - tibordigana - Tibor Digaňa (tibor17) - tibordigana@apache.org - - PMC - - Europe/Bratislava - - + + UTF-8 + - - - org.mockito - mockito-core - test - - + + + org.mockito + mockito-core + test + + - - - - org.jacoco - jacoco-maven-plugin - - - jacoco-agent - - prepare-agent - - - - - jacoco.agent - - - - maven-surefire-plugin - - ${jvm.args.tests} ${jacoco.agent} - - **/JUnit4SuiteTest.java - - - - - org.apache.maven.surefire - surefire-shadefire - 3.0.0-M7 - - - - - + + + + org.jacoco + jacoco-maven-plugin + + jacoco.agent + + + + jacoco-agent + + prepare-agent + + + + + + maven-surefire-plugin + + ${jvm.args.tests} ${jacoco.agent} + + **/JUnit4SuiteTest.java + + + + + org.apache.maven.surefire + surefire-shadefire + 3.0.0-M7 + + + + + + diff --git a/surefire-logger-api/src/main/java/org/apache/maven/plugin/surefire/log/api/ConsoleLogger.java b/surefire-logger-api/src/main/java/org/apache/maven/plugin/surefire/log/api/ConsoleLogger.java index 20b3016dfd..0736e9e7a6 100644 --- a/surefire-logger-api/src/main/java/org/apache/maven/plugin/surefire/log/api/ConsoleLogger.java +++ b/surefire-logger-api/src/main/java/org/apache/maven/plugin/surefire/log/api/ConsoleLogger.java @@ -1,3 +1,21 @@ +/* + * 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.maven.plugin.surefire.log.api; /* @@ -29,26 +47,25 @@ * via IsolatedClassLoader which can see classes from JRE only. This interface MUST use * JRE types in method signatures, e.g. {@link String} or {@link Throwable}, etc. */ -public interface ConsoleLogger -{ +public interface ConsoleLogger { boolean isDebugEnabled(); - void debug( String message ); + void debug(String message); boolean isInfoEnabled(); - void info( String message ); + void info(String message); boolean isWarnEnabled(); - void warning( String message ); + void warning(String message); boolean isErrorEnabled(); /** * @param message message to log */ - void error( String message ); + void error(String message); /** * Simply delegates to {@link #error(String) error( toString( t, message ) )}. @@ -56,12 +73,12 @@ public interface ConsoleLogger * @param message message to log * @param t exception, message and trace to log */ - void error( String message, Throwable t ); + void error(String message, Throwable t); /** * Simply delegates to method {@link #error(String, Throwable) error(null, Throwable)}. * * @param t exception, message and trace to log */ - void error( Throwable t ); + void error(Throwable t); } diff --git a/surefire-logger-api/src/main/java/org/apache/maven/plugin/surefire/log/api/ConsoleLoggerDecorator.java b/surefire-logger-api/src/main/java/org/apache/maven/plugin/surefire/log/api/ConsoleLoggerDecorator.java index 0ab20cc0c9..299f88a4c4 100644 --- a/surefire-logger-api/src/main/java/org/apache/maven/plugin/surefire/log/api/ConsoleLoggerDecorator.java +++ b/surefire-logger-api/src/main/java/org/apache/maven/plugin/surefire/log/api/ConsoleLoggerDecorator.java @@ -1,3 +1,21 @@ +/* + * 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.maven.plugin.surefire.log.api; /* @@ -26,123 +44,87 @@ * @author Tibor Digana (tibor17) * @since 2.20 */ -public final class ConsoleLoggerDecorator - implements ConsoleLogger -{ +public final class ConsoleLoggerDecorator implements ConsoleLogger { private final Object logger; - public ConsoleLoggerDecorator( Object logger ) - { - if ( logger == null ) - { - throw new NullPointerException( "logger argument is null in " + ConsoleLoggerDecorator.class ); + public ConsoleLoggerDecorator(Object logger) { + if (logger == null) { + throw new NullPointerException("logger argument is null in " + ConsoleLoggerDecorator.class); } this.logger = logger; } @Override - public boolean isDebugEnabled() - { - return invokeReturnedBoolean( "isDebugEnabled" ); + public boolean isDebugEnabled() { + return invokeReturnedBoolean("isDebugEnabled"); } @Override - public void debug( String message ) - { - invokeWithMessage( message, "debug" ); + public void debug(String message) { + invokeWithMessage(message, "debug"); } @Override - public boolean isInfoEnabled() - { - return invokeReturnedBoolean( "isInfoEnabled" ); + public boolean isInfoEnabled() { + return invokeReturnedBoolean("isInfoEnabled"); } @Override - public void info( String message ) - { - invokeWithMessage( message, "info" ); + public void info(String message) { + invokeWithMessage(message, "info"); } @Override - public boolean isWarnEnabled() - { - return invokeReturnedBoolean( "isWarnEnabled" ); + public boolean isWarnEnabled() { + return invokeReturnedBoolean("isWarnEnabled"); } @Override - public void warning( String message ) - { - invokeWithMessage( message, "warning" ); + public void warning(String message) { + invokeWithMessage(message, "warning"); } @Override - public boolean isErrorEnabled() - { - return invokeReturnedBoolean( "isErrorEnabled" ); + public boolean isErrorEnabled() { + return invokeReturnedBoolean("isErrorEnabled"); } @Override - public void error( String message ) - { - invokeWithMessage( message, "error" ); + public void error(String message) { + invokeWithMessage(message, "error"); } @Override - public void error( String message, Throwable t ) - { - try - { - logger.getClass() - .getMethod( "error", String.class, Throwable.class ) - .invoke( logger, message, t ); - } - catch ( Exception e ) - { - throw new IllegalStateException( e.getLocalizedMessage(), e ); + public void error(String message, Throwable t) { + try { + logger.getClass().getMethod("error", String.class, Throwable.class).invoke(logger, message, t); + } catch (Exception e) { + throw new IllegalStateException(e.getLocalizedMessage(), e); } } @Override - public void error( Throwable t ) - { - try - { - logger.getClass() - .getMethod( "error", Throwable.class ) - .invoke( logger, t ); - } - catch ( Exception e ) - { - throw new IllegalStateException( e.getLocalizedMessage(), e ); + public void error(Throwable t) { + try { + logger.getClass().getMethod("error", Throwable.class).invoke(logger, t); + } catch (Exception e) { + throw new IllegalStateException(e.getLocalizedMessage(), e); } } - private boolean invokeReturnedBoolean( String isErrorEnabled ) - { - try - { - return (Boolean) logger.getClass() - .getMethod( isErrorEnabled ) - .invoke( logger ); - } - catch ( Exception e ) - { - throw new IllegalStateException( e.getLocalizedMessage(), e ); + private boolean invokeReturnedBoolean(String isErrorEnabled) { + try { + return (Boolean) logger.getClass().getMethod(isErrorEnabled).invoke(logger); + } catch (Exception e) { + throw new IllegalStateException(e.getLocalizedMessage(), e); } } - private void invokeWithMessage( String message, String error ) - { - try - { - logger.getClass() - .getMethod( error, String.class ) - .invoke( logger, message ); - } - catch ( Exception e ) - { - throw new IllegalStateException( e.getLocalizedMessage(), e ); + private void invokeWithMessage(String message, String error) { + try { + logger.getClass().getMethod(error, String.class).invoke(logger, message); + } catch (Exception e) { + throw new IllegalStateException(e.getLocalizedMessage(), e); } } } diff --git a/surefire-logger-api/src/main/java/org/apache/maven/plugin/surefire/log/api/ConsoleLoggerUtils.java b/surefire-logger-api/src/main/java/org/apache/maven/plugin/surefire/log/api/ConsoleLoggerUtils.java index df2d44fd3b..daa3dfb624 100644 --- a/surefire-logger-api/src/main/java/org/apache/maven/plugin/surefire/log/api/ConsoleLoggerUtils.java +++ b/surefire-logger-api/src/main/java/org/apache/maven/plugin/surefire/log/api/ConsoleLoggerUtils.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire.log.api; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.surefire.log.api; import java.io.PrintWriter; import java.io.StringWriter; @@ -26,28 +25,22 @@ * @author Tibor Digana (tibor17) * @since 2.20 */ -public final class ConsoleLoggerUtils -{ - private ConsoleLoggerUtils() - { - throw new IllegalStateException( "non instantiable constructor" ); +public final class ConsoleLoggerUtils { + private ConsoleLoggerUtils() { + throw new IllegalStateException("non instantiable constructor"); } - public static String toString( Throwable t ) - { - return toString( null, t ); + public static String toString(Throwable t) { + return toString(null, t); } - public static String toString( String message, Throwable t ) - { - StringWriter result = new StringWriter( 512 ); - try ( PrintWriter writer = new PrintWriter( result ) ) - { - if ( message != null ) - { - writer.println( message ); + public static String toString(String message, Throwable t) { + StringWriter result = new StringWriter(512); + try (PrintWriter writer = new PrintWriter(result)) { + if (message != null) { + writer.println(message); } - t.printStackTrace( writer ); + t.printStackTrace(writer); return result.toString(); } } diff --git a/surefire-logger-api/src/main/java/org/apache/maven/plugin/surefire/log/api/Level.java b/surefire-logger-api/src/main/java/org/apache/maven/plugin/surefire/log/api/Level.java index 9195000275..7690797a4a 100644 --- a/surefire-logger-api/src/main/java/org/apache/maven/plugin/surefire/log/api/Level.java +++ b/surefire-logger-api/src/main/java/org/apache/maven/plugin/surefire/log/api/Level.java @@ -1,3 +1,21 @@ +/* + * 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.maven.plugin.surefire.log.api; /* @@ -26,8 +44,7 @@ * @author Tibor Digana (tibor17) * @since 2.20 */ -public enum Level -{ +public enum Level { /** * direct println */ @@ -48,17 +65,14 @@ public enum Level */ SUCCESS; - public static Level resolveLevel( boolean hasSuccessful, boolean hasFailure, boolean hasError, - boolean hasSkipped, boolean hasFlake ) - { + public static Level resolveLevel( + boolean hasSuccessful, boolean hasFailure, boolean hasError, boolean hasSkipped, boolean hasFlake) { boolean isRed = hasFailure | hasError; - if ( isRed ) - { + if (isRed) { return FAILURE; } boolean isYellow = hasSkipped | hasFlake; - if ( isYellow ) - { + if (isYellow) { return UNSTABLE; } return hasSuccessful ? SUCCESS : NO_COLOR; diff --git a/surefire-logger-api/src/main/java/org/apache/maven/plugin/surefire/log/api/NullConsoleLogger.java b/surefire-logger-api/src/main/java/org/apache/maven/plugin/surefire/log/api/NullConsoleLogger.java index a0fc22a2a2..92b60af0a2 100644 --- a/surefire-logger-api/src/main/java/org/apache/maven/plugin/surefire/log/api/NullConsoleLogger.java +++ b/surefire-logger-api/src/main/java/org/apache/maven/plugin/surefire/log/api/NullConsoleLogger.java @@ -1,3 +1,21 @@ +/* + * 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.maven.plugin.surefire.log.api; /* @@ -25,59 +43,42 @@ * @author Tibor Digana (tibor17) * @since 2.20 */ -public final class NullConsoleLogger implements ConsoleLogger -{ +public final class NullConsoleLogger implements ConsoleLogger { @Override - public boolean isDebugEnabled() - { + public boolean isDebugEnabled() { return false; } @Override - public void debug( String message ) - { - } + public void debug(String message) {} @Override - public boolean isInfoEnabled() - { + public boolean isInfoEnabled() { return false; } @Override - public void info( String message ) - { - } + public void info(String message) {} @Override - public boolean isWarnEnabled() - { + public boolean isWarnEnabled() { return false; } @Override - public void warning( String message ) - { - } + public void warning(String message) {} @Override - public boolean isErrorEnabled() - { + public boolean isErrorEnabled() { return false; } @Override - public void error( String message ) - { - } + public void error(String message) {} @Override - public void error( String message, Throwable t ) - { - } + public void error(String message, Throwable t) {} @Override - public void error( Throwable t ) - { - } + public void error(Throwable t) {} } diff --git a/surefire-logger-api/src/main/java/org/apache/maven/plugin/surefire/log/api/PrintStreamLogger.java b/surefire-logger-api/src/main/java/org/apache/maven/plugin/surefire/log/api/PrintStreamLogger.java index e1425fa34e..ae9634a4f6 100644 --- a/surefire-logger-api/src/main/java/org/apache/maven/plugin/surefire/log/api/PrintStreamLogger.java +++ b/surefire-logger-api/src/main/java/org/apache/maven/plugin/surefire/log/api/PrintStreamLogger.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire.log.api; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,79 +16,67 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.surefire.log.api; import java.io.PrintStream; /** * Console logger for {@link PrintStream}. */ -public class PrintStreamLogger - implements ConsoleLogger -{ +public class PrintStreamLogger implements ConsoleLogger { private final PrintStream stream; - public PrintStreamLogger( PrintStream stream ) - { + public PrintStreamLogger(PrintStream stream) { this.stream = stream; } @Override - public boolean isDebugEnabled() - { + public boolean isDebugEnabled() { return true; } @Override - public void debug( String message ) - { - stream.println( message ); + public void debug(String message) { + stream.println(message); } @Override - public boolean isInfoEnabled() - { + public boolean isInfoEnabled() { return true; } @Override - public void info( String message ) - { - stream.println( message ); + public void info(String message) { + stream.println(message); } @Override - public boolean isWarnEnabled() - { + public boolean isWarnEnabled() { return true; } @Override - public void warning( String message ) - { - stream.println( message ); + public void warning(String message) { + stream.println(message); } @Override - public boolean isErrorEnabled() - { + public boolean isErrorEnabled() { return true; } @Override - public void error( String message ) - { - stream.println( message ); + public void error(String message) { + stream.println(message); } @Override - public void error( String message, Throwable t ) - { - error( ConsoleLoggerUtils.toString( message, t ) ); + public void error(String message, Throwable t) { + error(ConsoleLoggerUtils.toString(message, t)); } @Override - public void error( Throwable t ) - { - error( null, t ); + public void error(Throwable t) { + error(null, t); } } diff --git a/surefire-logger-api/src/test/java/org/apache/maven/plugin/surefire/log/api/ConsoleLoggerUtilsTest.java b/surefire-logger-api/src/test/java/org/apache/maven/plugin/surefire/log/api/ConsoleLoggerUtilsTest.java index 9e819bb595..b4eec4ce80 100644 --- a/surefire-logger-api/src/test/java/org/apache/maven/plugin/surefire/log/api/ConsoleLoggerUtilsTest.java +++ b/surefire-logger-api/src/test/java/org/apache/maven/plugin/surefire/log/api/ConsoleLoggerUtilsTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire.log.api; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,47 +16,43 @@ * specific language governing permissions and limitations * under the License. */ - -import org.junit.Test; +package org.apache.maven.plugin.surefire.log.api; import java.io.PrintWriter; import java.io.StringWriter; +import org.junit.Test; + import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link ConsoleLoggerUtils}. */ -public class ConsoleLoggerUtilsTest -{ +public class ConsoleLoggerUtilsTest { @Test - public void shouldPrintStacktraceAsString() - { - Exception e = new IllegalArgumentException( "wrong param" ); - String msg = ConsoleLoggerUtils.toString( e ); + public void shouldPrintStacktraceAsString() { + Exception e = new IllegalArgumentException("wrong param"); + String msg = ConsoleLoggerUtils.toString(e); StringWriter text = new StringWriter(); - PrintWriter writer = new PrintWriter( text ); - e.printStackTrace( writer ); + PrintWriter writer = new PrintWriter(text); + e.printStackTrace(writer); String s = text.toString(); - assertThat( msg ) - .isEqualTo( s ); + assertThat(msg).isEqualTo(s); } @Test - public void shouldPrintStacktracWithMessageAsString() - { - Exception e = new IllegalArgumentException( "wrong param" ); - String msg = ConsoleLoggerUtils.toString( "issue", e ); + public void shouldPrintStacktracWithMessageAsString() { + Exception e = new IllegalArgumentException("wrong param"); + String msg = ConsoleLoggerUtils.toString("issue", e); StringWriter text = new StringWriter(); - PrintWriter writer = new PrintWriter( text ); - writer.println( "issue" ); - e.printStackTrace( writer ); + PrintWriter writer = new PrintWriter(text); + writer.println("issue"); + e.printStackTrace(writer); String s = text.toString(); - assertThat( msg ) - .isEqualTo( s ); + assertThat(msg).isEqualTo(s); } } diff --git a/surefire-logger-api/src/test/java/org/apache/maven/plugin/surefire/log/api/JUnit4SuiteTest.java b/surefire-logger-api/src/test/java/org/apache/maven/plugin/surefire/log/api/JUnit4SuiteTest.java index 69665a3108..75cedc65c4 100644 --- a/surefire-logger-api/src/test/java/org/apache/maven/plugin/surefire/log/api/JUnit4SuiteTest.java +++ b/surefire-logger-api/src/test/java/org/apache/maven/plugin/surefire/log/api/JUnit4SuiteTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire.log.api; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.surefire.log.api; import junit.framework.JUnit4TestAdapter; import junit.framework.Test; @@ -32,12 +31,10 @@ * @author Tibor Digana (tibor17) * @since 3.0.0-M4 */ -@SuiteClasses( { ConsoleLoggerUtilsTest.class, LevelTest.class, LoggersTest.class } ) -@RunWith( Suite.class ) -public class JUnit4SuiteTest extends TestCase -{ - public static Test suite() - { - return new JUnit4TestAdapter( JUnit4SuiteTest.class ); +@SuiteClasses({ConsoleLoggerUtilsTest.class, LevelTest.class, LoggersTest.class}) +@RunWith(Suite.class) +public class JUnit4SuiteTest extends TestCase { + public static Test suite() { + return new JUnit4TestAdapter(JUnit4SuiteTest.class); } } diff --git a/surefire-logger-api/src/test/java/org/apache/maven/plugin/surefire/log/api/LevelTest.java b/surefire-logger-api/src/test/java/org/apache/maven/plugin/surefire/log/api/LevelTest.java index 597a118d9c..0477ce9e00 100644 --- a/surefire-logger-api/src/test/java/org/apache/maven/plugin/surefire/log/api/LevelTest.java +++ b/surefire-logger-api/src/test/java/org/apache/maven/plugin/surefire/log/api/LevelTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire.log.api; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugin.surefire.log.api; import org.junit.Test; @@ -27,47 +26,40 @@ /** * Tests for {@link Level}. */ -public class LevelTest -{ +public class LevelTest { @Test - public void shouldHaveSuccess() - { - Level level = resolveLevel( true, false, false, false, false ); - assertThat( level ).isEqualTo( Level.SUCCESS ); + public void shouldHaveSuccess() { + Level level = resolveLevel(true, false, false, false, false); + assertThat(level).isEqualTo(Level.SUCCESS); } @Test - public void shouldNotHaveSuccess() - { - Level level = resolveLevel( false, false, false, false, false ); - assertThat( level ).isEqualTo( Level.NO_COLOR ); + public void shouldNotHaveSuccess() { + Level level = resolveLevel(false, false, false, false, false); + assertThat(level).isEqualTo(Level.NO_COLOR); } @Test - public void shouldBeFailure() - { - Level level = resolveLevel( false, true, false, false, false ); - assertThat( level ).isEqualTo( Level.FAILURE ); + public void shouldBeFailure() { + Level level = resolveLevel(false, true, false, false, false); + assertThat(level).isEqualTo(Level.FAILURE); } @Test - public void shouldBeError() - { - Level level = resolveLevel( false, false, true, false, false ); - assertThat( level ).isEqualTo( Level.FAILURE ); + public void shouldBeError() { + Level level = resolveLevel(false, false, true, false, false); + assertThat(level).isEqualTo(Level.FAILURE); } @Test - public void shouldBeSkipped() - { - Level level = resolveLevel( false, false, false, true, false ); - assertThat( level ).isEqualTo( Level.UNSTABLE ); + public void shouldBeSkipped() { + Level level = resolveLevel(false, false, false, true, false); + assertThat(level).isEqualTo(Level.UNSTABLE); } @Test - public void shouldBeFlake() - { - Level level = resolveLevel( false, false, false, false, true ); - assertThat( level ).isEqualTo( Level.UNSTABLE ); + public void shouldBeFlake() { + Level level = resolveLevel(false, false, false, false, true); + assertThat(level).isEqualTo(Level.UNSTABLE); } } diff --git a/surefire-logger-api/src/test/java/org/apache/maven/plugin/surefire/log/api/LoggersTest.java b/surefire-logger-api/src/test/java/org/apache/maven/plugin/surefire/log/api/LoggersTest.java index 2bad634884..2667e2698c 100644 --- a/surefire-logger-api/src/test/java/org/apache/maven/plugin/surefire/log/api/LoggersTest.java +++ b/surefire-logger-api/src/test/java/org/apache/maven/plugin/surefire/log/api/LoggersTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugin.surefire.log.api; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,13 +16,14 @@ * specific language governing permissions and limitations * under the License. */ - -import org.junit.Test; -import org.mockito.ArgumentCaptor; +package org.apache.maven.plugin.surefire.log.api; import java.io.ByteArrayOutputStream; import java.io.PrintStream; +import org.junit.Test; +import org.mockito.ArgumentCaptor; + import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; @@ -34,104 +33,99 @@ /** * Tests for {@link ConsoleLoggerDecorator}, {@link NullConsoleLogger} and {@link PrintStreamLogger}. */ -public class LoggersTest -{ +public class LoggersTest { @Test - public void testPrintStreamLogger() - { + public void testPrintStreamLogger() { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); - PrintStream printStream = new PrintStream( outputStream ); - PrintStreamLogger logger = new PrintStreamLogger( printStream ); - + PrintStream printStream = new PrintStream(outputStream); + PrintStreamLogger logger = new PrintStreamLogger(printStream); - assertThat( logger.isErrorEnabled() ).isTrue(); - assertThat( logger.isWarnEnabled() ).isTrue(); - assertThat( logger.isInfoEnabled() ).isTrue(); - assertThat( logger.isDebugEnabled() ).isTrue(); + assertThat(logger.isErrorEnabled()).isTrue(); + assertThat(logger.isWarnEnabled()).isTrue(); + assertThat(logger.isInfoEnabled()).isTrue(); + assertThat(logger.isDebugEnabled()).isTrue(); - logger.error( "error" ); - logger.debug( "debug" ); - logger.info( "info" ); - logger.warning( "warning" ); + logger.error("error"); + logger.debug("debug"); + logger.info("info"); + logger.warning("warning"); String line = System.lineSeparator(); - assertThat( outputStream.toString() ) - .isEqualTo( "error" + line + "debug" + line + "info" + line + "warning" + line ); + assertThat(outputStream.toString()) + .isEqualTo("error" + line + "debug" + line + "info" + line + "warning" + line); - Exception e = new Exception( "exception" ); + Exception e = new Exception("exception"); outputStream.reset(); - logger.error( e ); - assertThat( outputStream.toString() ) - .contains( "java.lang.Exception: exception" ) - .contains( "at " + getClass().getName() + ".testPrintStreamLogger(LoggersTest.java:61)" ); + logger.error(e); + assertThat(outputStream.toString()) + .contains("java.lang.Exception: exception") + .contains("at " + getClass().getName() + ".testPrintStreamLogger(LoggersTest.java"); } - @Test( expected = NullPointerException.class ) - public void shouldThrowNPE() - { - new ConsoleLoggerDecorator( null ); + @Test(expected = NullPointerException.class) + public void shouldThrowNPE() { + new ConsoleLoggerDecorator(null); } @Test - public void testDecorator() - { - ConsoleLogger logger = mock( ConsoleLogger.class ); - ConsoleLoggerDecorator decorator = new ConsoleLoggerDecorator( logger ); - - assertThat( decorator.isDebugEnabled() ).isFalse(); - when( logger.isDebugEnabled() ).thenReturn( true ); - assertThat( decorator.isDebugEnabled() ).isTrue(); - - assertThat( decorator.isInfoEnabled() ).isFalse(); - when( logger.isInfoEnabled() ).thenReturn( true ); - assertThat( decorator.isInfoEnabled() ).isTrue(); - - assertThat( decorator.isWarnEnabled() ).isFalse(); - when( logger.isWarnEnabled() ).thenReturn( true ); - assertThat( decorator.isWarnEnabled() ).isTrue(); - - assertThat( decorator.isErrorEnabled() ).isFalse(); - when( logger.isErrorEnabled() ).thenReturn( true ); - assertThat( decorator.isErrorEnabled() ).isTrue(); - - ArgumentCaptor argumentMsg = ArgumentCaptor.forClass( String.class ); - decorator.debug( "debug" ); - verify( logger, times( 1 ) ).debug( argumentMsg.capture() ); - assertThat( argumentMsg.getAllValues() ).hasSize( 1 ); - assertThat( argumentMsg.getAllValues().get( 0 ) ).isEqualTo( "debug" ); - - argumentMsg = ArgumentCaptor.forClass( String.class ); - decorator.info( "info" ); - verify( logger, times( 1 ) ).info( argumentMsg.capture() ); - assertThat( argumentMsg.getAllValues() ).hasSize( 1 ); - assertThat( argumentMsg.getAllValues().get( 0 ) ).isEqualTo( "info" ); - - argumentMsg = ArgumentCaptor.forClass( String.class ); - decorator.warning( "warning" ); - verify( logger, times( 1 ) ).warning( argumentMsg.capture() ); - assertThat( argumentMsg.getAllValues() ).hasSize( 1 ); - assertThat( argumentMsg.getAllValues().get( 0 ) ).isEqualTo( "warning" ); - - argumentMsg = ArgumentCaptor.forClass( String.class ); - decorator.error( "error" ); - verify( logger, times( 1 ) ).error( argumentMsg.capture() ); - assertThat( argumentMsg.getAllValues() ).hasSize( 1 ); - assertThat( argumentMsg.getAllValues().get( 0 ) ).isEqualTo( "error" ); - - ArgumentCaptor argumentThrowable = ArgumentCaptor.forClass( Throwable.class ); - argumentMsg = ArgumentCaptor.forClass( String.class ); + public void testDecorator() { + ConsoleLogger logger = mock(ConsoleLogger.class); + ConsoleLoggerDecorator decorator = new ConsoleLoggerDecorator(logger); + + assertThat(decorator.isDebugEnabled()).isFalse(); + when(logger.isDebugEnabled()).thenReturn(true); + assertThat(decorator.isDebugEnabled()).isTrue(); + + assertThat(decorator.isInfoEnabled()).isFalse(); + when(logger.isInfoEnabled()).thenReturn(true); + assertThat(decorator.isInfoEnabled()).isTrue(); + + assertThat(decorator.isWarnEnabled()).isFalse(); + when(logger.isWarnEnabled()).thenReturn(true); + assertThat(decorator.isWarnEnabled()).isTrue(); + + assertThat(decorator.isErrorEnabled()).isFalse(); + when(logger.isErrorEnabled()).thenReturn(true); + assertThat(decorator.isErrorEnabled()).isTrue(); + + ArgumentCaptor argumentMsg = ArgumentCaptor.forClass(String.class); + decorator.debug("debug"); + verify(logger, times(1)).debug(argumentMsg.capture()); + assertThat(argumentMsg.getAllValues()).hasSize(1); + assertThat(argumentMsg.getAllValues().get(0)).isEqualTo("debug"); + + argumentMsg = ArgumentCaptor.forClass(String.class); + decorator.info("info"); + verify(logger, times(1)).info(argumentMsg.capture()); + assertThat(argumentMsg.getAllValues()).hasSize(1); + assertThat(argumentMsg.getAllValues().get(0)).isEqualTo("info"); + + argumentMsg = ArgumentCaptor.forClass(String.class); + decorator.warning("warning"); + verify(logger, times(1)).warning(argumentMsg.capture()); + assertThat(argumentMsg.getAllValues()).hasSize(1); + assertThat(argumentMsg.getAllValues().get(0)).isEqualTo("warning"); + + argumentMsg = ArgumentCaptor.forClass(String.class); + decorator.error("error"); + verify(logger, times(1)).error(argumentMsg.capture()); + assertThat(argumentMsg.getAllValues()).hasSize(1); + assertThat(argumentMsg.getAllValues().get(0)).isEqualTo("error"); + + ArgumentCaptor argumentThrowable = ArgumentCaptor.forClass(Throwable.class); + argumentMsg = ArgumentCaptor.forClass(String.class); Exception e = new Exception(); - decorator.error( "error", e ); - verify( logger, times( 1 ) ).error( argumentMsg.capture(), argumentThrowable.capture() ); - assertThat( argumentMsg.getAllValues() ).hasSize( 1 ); - assertThat( argumentMsg.getAllValues().get( 0 ) ).isEqualTo( "error" ); - assertThat( argumentThrowable.getAllValues() ).hasSize( 1 ); - assertThat( argumentThrowable.getAllValues().get( 0 ) ).isSameAs( e ); - - argumentThrowable = ArgumentCaptor.forClass( Throwable.class ); - decorator.error( e ); - verify( logger, times( 1 ) ).error( argumentThrowable.capture() ); - assertThat( argumentThrowable.getAllValues() ).hasSize( 1 ); - assertThat( argumentThrowable.getAllValues().get( 0 ) ).isSameAs( e ); + decorator.error("error", e); + verify(logger, times(1)).error(argumentMsg.capture(), argumentThrowable.capture()); + assertThat(argumentMsg.getAllValues()).hasSize(1); + assertThat(argumentMsg.getAllValues().get(0)).isEqualTo("error"); + assertThat(argumentThrowable.getAllValues()).hasSize(1); + assertThat(argumentThrowable.getAllValues().get(0)).isSameAs(e); + + argumentThrowable = ArgumentCaptor.forClass(Throwable.class); + decorator.error(e); + verify(logger, times(1)).error(argumentThrowable.capture()); + assertThat(argumentThrowable.getAllValues()).hasSize(1); + assertThat(argumentThrowable.getAllValues().get(0)).isSameAs(e); } } diff --git a/surefire-providers/common-java5/pom.xml b/surefire-providers/common-java5/pom.xml index 9dda6e70d6..816eafac50 100644 --- a/surefire-providers/common-java5/pom.xml +++ b/surefire-providers/common-java5/pom.xml @@ -1,3 +1,4 @@ + - 4.0.0 @@ -31,6 +31,10 @@ Shared Java 5 Provider Base Shared Java 5 code for all providers. + + surefire-3.0.0-M8 + + org.apache.maven.surefire @@ -44,6 +48,9 @@ org.jacoco jacoco-maven-plugin + + jacoco.agent + jacoco-agent @@ -52,9 +59,6 @@ - - jacoco.agent - maven-surefire-plugin @@ -65,14 +69,11 @@ org.apache.maven.surefire surefire-shadefire - 3.0.0-M7 + 3.0.0-M7 + - - - surefire-3.0.0-M8 - diff --git a/surefire-providers/common-java5/src/main/java/org/apache/maven/surefire/report/ClassMethodIndexer.java b/surefire-providers/common-java5/src/main/java/org/apache/maven/surefire/report/ClassMethodIndexer.java index 8e58d7a4c8..0686646c2b 100644 --- a/surefire-providers/common-java5/src/main/java/org/apache/maven/surefire/report/ClassMethodIndexer.java +++ b/surefire-providers/common-java5/src/main/java/org/apache/maven/surefire/report/ClassMethodIndexer.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.report; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,47 +16,43 @@ * specific language governing permissions and limitations * under the License. */ - -import org.apache.maven.surefire.api.util.internal.ClassMethod; +package org.apache.maven.surefire.report; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicInteger; +import org.apache.maven.surefire.api.util.internal.ClassMethod; + import static java.util.Objects.requireNonNull; /** * Creates an index for class/method. * Returns ThreadLocal index if created before. */ -public final class ClassMethodIndexer -{ - private final AtomicInteger classIndex = new AtomicInteger( 1 ); - private final AtomicInteger methodIndex = new AtomicInteger( 1 ); +public final class ClassMethodIndexer { + private final AtomicInteger classIndex = new AtomicInteger(1); + private final AtomicInteger methodIndex = new AtomicInteger(1); private final Map testIdMapping = new ConcurrentHashMap<>(); private final ThreadLocal testLocalMapping = new ThreadLocal<>(); - public long indexClassMethod( String clazz, String method ) - { - ClassMethod key = new ClassMethod( requireNonNull( clazz ), method ); - return testIdMapping.computeIfAbsent( key, cm -> - { - Long classId = testIdMapping.get( new ClassMethod( requireNonNull( clazz ), null ) ); - long c = classId == null ? ( ( (long) classIndex.getAndIncrement() ) << 32 ) : classId; + public long indexClassMethod(String clazz, String method) { + ClassMethod key = new ClassMethod(requireNonNull(clazz), method); + return testIdMapping.computeIfAbsent(key, cm -> { + Long classId = testIdMapping.get(new ClassMethod(requireNonNull(clazz), null)); + long c = classId == null ? (((long) classIndex.getAndIncrement()) << 32) : classId; int m = method == null ? 0 : methodIndex.getAndIncrement(); long id = c | m; - testLocalMapping.set( id ); + testLocalMapping.set(id); return id; - } ); + }); } - public long indexClass( String clazz ) - { - return indexClassMethod( clazz, null ); + public long indexClass(String clazz) { + return indexClassMethod(clazz, null); } - public Long getLocalIndex() - { + public Long getLocalIndex() { return testLocalMapping.get(); } } diff --git a/surefire-providers/common-java5/src/main/java/org/apache/maven/surefire/report/ClassNameStackTraceFilter.java b/surefire-providers/common-java5/src/main/java/org/apache/maven/surefire/report/ClassNameStackTraceFilter.java index bfc5b779ba..b887a77da3 100644 --- a/surefire-providers/common-java5/src/main/java/org/apache/maven/surefire/report/ClassNameStackTraceFilter.java +++ b/surefire-providers/common-java5/src/main/java/org/apache/maven/surefire/report/ClassNameStackTraceFilter.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.report; /* @@ -22,19 +40,15 @@ /** * Filters stacktrace element by class name. */ -final class ClassNameStackTraceFilter - implements StackTraceFilter -{ +final class ClassNameStackTraceFilter implements StackTraceFilter { private final String className; - ClassNameStackTraceFilter( String className ) - { + ClassNameStackTraceFilter(String className) { this.className = className; } @Override - public boolean matches( StackTraceElement element ) - { - return className.equals( element.getClassName() ); + public boolean matches(StackTraceElement element) { + return className.equals(element.getClassName()); } } diff --git a/surefire-providers/common-java5/src/main/java/org/apache/maven/surefire/report/NullStackTraceFilter.java b/surefire-providers/common-java5/src/main/java/org/apache/maven/surefire/report/NullStackTraceFilter.java index 3172320928..8f732eb7b4 100644 --- a/surefire-providers/common-java5/src/main/java/org/apache/maven/surefire/report/NullStackTraceFilter.java +++ b/surefire-providers/common-java5/src/main/java/org/apache/maven/surefire/report/NullStackTraceFilter.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.report; /* @@ -22,12 +40,9 @@ /** * always returns true */ -final class NullStackTraceFilter - implements StackTraceFilter -{ +final class NullStackTraceFilter implements StackTraceFilter { @Override - public boolean matches( StackTraceElement element ) - { + public boolean matches(StackTraceElement element) { return true; } } diff --git a/surefire-providers/common-java5/src/main/java/org/apache/maven/surefire/report/PojoStackTraceWriter.java b/surefire-providers/common-java5/src/main/java/org/apache/maven/surefire/report/PojoStackTraceWriter.java index d6d9703abd..1e1599cc34 100644 --- a/surefire-providers/common-java5/src/main/java/org/apache/maven/surefire/report/PojoStackTraceWriter.java +++ b/surefire-providers/common-java5/src/main/java/org/apache/maven/surefire/report/PojoStackTraceWriter.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.report; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,55 +16,47 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.report; +import java.io.PrintWriter; +import java.io.StringWriter; +import java.util.Objects; import org.apache.maven.surefire.api.report.SafeThrowable; import org.apache.maven.surefire.api.report.StackTraceWriter; import org.apache.maven.surefire.api.util.internal.StringUtils; -import java.io.PrintWriter; -import java.io.StringWriter; -import java.util.Objects; - /** * Write the trace out for a POJO test. * * @author Brett Porter */ -public class PojoStackTraceWriter - implements StackTraceWriter -{ +public class PojoStackTraceWriter implements StackTraceWriter { private final Throwable t; private final String testClass; private final String testMethod; - public PojoStackTraceWriter( String testClass, String testMethod, Throwable t ) - { + public PojoStackTraceWriter(String testClass, String testMethod, Throwable t) { this.testClass = testClass; this.testMethod = testMethod; this.t = t; } @Override - public String writeTraceToString() - { - if ( t != null ) - { + public String writeTraceToString() { + if (t != null) { StringWriter w = new StringWriter(); - try ( PrintWriter stackTrace = new PrintWriter( w ) ) - { - t.printStackTrace( stackTrace ); + try (PrintWriter stackTrace = new PrintWriter(w)) { + t.printStackTrace(stackTrace); } StringBuffer builder = w.getBuffer(); - if ( isMultiLineExceptionMessage( t ) ) - { + if (isMultiLineExceptionMessage(t)) { // SUREFIRE-986 String exc = t.getClass().getName() + ": "; - if ( StringUtils.startsWith( builder, exc ) ) - { - builder.insert( exc.length(), '\n' ); + if (StringUtils.startsWith(builder, exc)) { + builder.insert(exc.length(), '\n'); } } return builder.toString(); @@ -75,64 +65,52 @@ public String writeTraceToString() } @Override - public String smartTrimmedStackTrace() - { - return t == null ? "" : new SmartStackTraceParser( testClass, t, testMethod ).getString(); + public String smartTrimmedStackTrace() { + return t == null ? "" : new SmartStackTraceParser(testClass, t, testMethod).getString(); } @Override - public String writeTrimmedTraceToString() - { - return t == null ? "" : SmartStackTraceParser.stackTraceWithFocusOnClassAsString( t, testClass ); + public String writeTrimmedTraceToString() { + return t == null ? "" : SmartStackTraceParser.stackTraceWithFocusOnClassAsString(t, testClass); } @Override - public SafeThrowable getThrowable() - { - return t == null ? null : new SafeThrowable( t ); + public SafeThrowable getThrowable() { + return t == null ? null : new SafeThrowable(t); } - private static boolean isMultiLineExceptionMessage( Throwable t ) - { + private static boolean isMultiLineExceptionMessage(Throwable t) { String msg = t.getLocalizedMessage(); - if ( msg != null ) - { + if (msg != null) { int countNewLines = 0; - for ( int i = 0, length = msg.length(); i < length; i++ ) - { - if ( msg.charAt( i ) == '\n' ) - { - if ( ++countNewLines == 2 ) - { + for (int i = 0, length = msg.length(); i < length; i++) { + if (msg.charAt(i) == '\n') { + if (++countNewLines == 2) { break; } } } - return countNewLines > 1 || countNewLines == 1 && !msg.trim().endsWith( "\n" ); + return countNewLines > 1 || countNewLines == 1 && !msg.trim().endsWith("\n"); } return false; } @Override - public boolean equals( Object o ) - { - if ( this == o ) - { + public boolean equals(Object o) { + if (this == o) { return true; } - if ( o == null || getClass() != o.getClass() ) - { + if (o == null || getClass() != o.getClass()) { return false; } - PojoStackTraceWriter that = ( PojoStackTraceWriter ) o; - return Objects.equals( t, that.t ) - && Objects.equals( testClass, that.testClass ) - && Objects.equals( testMethod, that.testMethod ); + PojoStackTraceWriter that = (PojoStackTraceWriter) o; + return Objects.equals(t, that.t) + && Objects.equals(testClass, that.testClass) + && Objects.equals(testMethod, that.testMethod); } @Override - public int hashCode() - { - return Objects.hash( t, testClass, testMethod ); + public int hashCode() { + return Objects.hash(t, testClass, testMethod); } } diff --git a/surefire-providers/common-java5/src/main/java/org/apache/maven/surefire/report/RunModeSetter.java b/surefire-providers/common-java5/src/main/java/org/apache/maven/surefire/report/RunModeSetter.java index 5836a3de86..a7c68f12b1 100644 --- a/surefire-providers/common-java5/src/main/java/org/apache/maven/surefire/report/RunModeSetter.java +++ b/surefire-providers/common-java5/src/main/java/org/apache/maven/surefire/report/RunModeSetter.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.report; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.report; import org.apache.maven.surefire.api.report.RunMode; @@ -26,7 +25,6 @@ * * @since 3.0.0-M6 */ -public interface RunModeSetter -{ - void setRunMode( RunMode runMode ); +public interface RunModeSetter { + void setRunMode(RunMode runMode); } diff --git a/surefire-providers/common-java5/src/main/java/org/apache/maven/surefire/report/SmartStackTraceParser.java b/surefire-providers/common-java5/src/main/java/org/apache/maven/surefire/report/SmartStackTraceParser.java index 3770f2bab4..e5c66dde8a 100644 --- a/surefire-providers/common-java5/src/main/java/org/apache/maven/surefire/report/SmartStackTraceParser.java +++ b/surefire-providers/common-java5/src/main/java/org/apache/maven/surefire/report/SmartStackTraceParser.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.report; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,13 +16,14 @@ * specific language governing permissions and limitations * under the License. */ - -import org.apache.maven.surefire.api.report.SafeThrowable; +package org.apache.maven.surefire.report; import java.util.ArrayList; import java.util.Collections; import java.util.List; +import org.apache.maven.surefire.api.report.SafeThrowable; + import static java.util.Arrays.asList; import static java.util.Collections.reverse; import static org.apache.maven.surefire.shared.utils.StringUtils.chompLast; @@ -33,9 +32,8 @@ /** * @author Kristian Rosenvold */ -@SuppressWarnings( "ThrowableResultOfMethodCallIgnored" ) -public class SmartStackTraceParser -{ +@SuppressWarnings("ThrowableResultOfMethodCallIgnored") +public class SmartStackTraceParser { private final SafeThrowable throwable; private final StackTraceElement[] stackTrace; @@ -46,82 +44,64 @@ public class SmartStackTraceParser private final String testMethodName; - public SmartStackTraceParser( String testClassName, Throwable throwable, String testMethodName ) - { + public SmartStackTraceParser(String testClassName, Throwable throwable, String testMethodName) { this.testMethodName = testMethodName; this.testClassName = testClassName; - testClass = toClass( testClassName ); - this.throwable = new SafeThrowable( throwable ); + testClass = toClass(testClassName); + this.throwable = new SafeThrowable(throwable); stackTrace = throwable.getStackTrace(); } - private static Class toClass( String name ) - { - try - { + private static Class toClass(String name) { + try { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); - return classLoader == null ? null : classLoader.loadClass( name ); - } - catch ( ClassNotFoundException e ) - { + return classLoader == null ? null : classLoader.loadClass(name); + } catch (ClassNotFoundException e) { return null; } } - private static String toSimpleClassName( String className ) - { - int i = className.lastIndexOf( "." ); - return className.substring( i + 1 ); + private static String toSimpleClassName(String className) { + int i = className.lastIndexOf("."); + return className.substring(i + 1); } - @SuppressWarnings( "ThrowableResultOfMethodCallIgnored" ) - public String getString() - { - if ( testClass == null ) - { + @SuppressWarnings("ThrowableResultOfMethodCallIgnored") + public String getString() { + if (testClass == null) { return throwable.getLocalizedMessage(); } final StringBuilder result = new StringBuilder(); - final List stackTraceElements = focusOnClass( stackTrace, testClass ); - reverse( stackTraceElements ); - final String testClassSimpleName = toSimpleClassName( testClassName ); - if ( stackTraceElements.isEmpty() ) - { - result.append( testClassSimpleName ); - if ( isNotEmpty( testMethodName ) ) - { - result.append( "." ) - .append( testMethodName ); + final List stackTraceElements = focusOnClass(stackTrace, testClass); + reverse(stackTraceElements); + final String testClassSimpleName = toSimpleClassName(testClassName); + if (stackTraceElements.isEmpty()) { + result.append(testClassSimpleName); + if (isNotEmpty(testMethodName)) { + result.append(".").append(testMethodName); } - } - else - { - for ( int i = 0, size = stackTraceElements.size(); i < size; i++ ) - { - final StackTraceElement stackTraceElement = stackTraceElements.get( i ); - final boolean isTestClassName = stackTraceElement.getClassName().equals( testClassName ); - if ( i == 0 ) - { - result.append( testClassSimpleName ) - .append( isTestClassName ? '.' : '>' ); + } else { + for (int i = 0, size = stackTraceElements.size(); i < size; i++) { + final StackTraceElement stackTraceElement = stackTraceElements.get(i); + final boolean isTestClassName = stackTraceElement.getClassName().equals(testClassName); + if (i == 0) { + result.append(testClassSimpleName).append(isTestClassName ? '.' : '>'); } - if ( !isTestClassName ) - { - result.append( toSimpleClassName( stackTraceElement.getClassName() ) ) - .append( '.' ); + if (!isTestClassName) { + result.append(toSimpleClassName(stackTraceElement.getClassName())) + .append('.'); } - result.append( stackTraceElement.getMethodName() ) - .append( ':' ) - .append( stackTraceElement.getLineNumber() ) - .append( "->" ); + result.append(stackTraceElement.getMethodName()) + .append(':') + .append(stackTraceElement.getLineNumber()) + .append("->"); } - if ( result.length() >= 2 ) - { - result.setLength( result.length() - 2 ); + if (result.length() >= 2) { + result.setLength(result.length() - 2); } } @@ -130,179 +110,141 @@ public String getString() final String excClassName = excType.getName(); final String msg = throwable.getMessage(); - if ( ! ( target instanceof AssertionError - || "junit.framework.AssertionFailedError".equals( excClassName ) - || "junit.framework.ComparisonFailure".equals( excClassName ) - || excClassName.startsWith( "org.opentest4j." ) ) ) - { - result.append( rootIsInclass() ? " " : " » " ) - .append( toMinimalThrowableMiniMessage( excType ) ); + if (!(target instanceof AssertionError + || "junit.framework.AssertionFailedError".equals(excClassName) + || "junit.framework.ComparisonFailure".equals(excClassName) + || excClassName.startsWith("org.opentest4j."))) { + result.append(rootIsInclass() ? " " : " » ").append(toMinimalThrowableMiniMessage(excType)); } - if ( isNotEmpty( msg ) ) - { - result.append( ' ' ) - .append( msg ); + if (isNotEmpty(msg)) { + result.append(' ').append(msg); } return result.toString(); } - private static String toMinimalThrowableMiniMessage( Class excType ) - { + private static String toMinimalThrowableMiniMessage(Class excType) { String name = excType.getSimpleName(); - if ( name.endsWith( "Exception" ) ) - { - return chompLast( name, "Exception" ); + if (name.endsWith("Exception")) { + return chompLast(name, "Exception"); } - if ( name.endsWith( "Error" ) ) - { - return chompLast( name, "Error" ); + if (name.endsWith("Error")) { + return chompLast(name, "Error"); } return name; } - private boolean rootIsInclass() - { - return stackTrace != null && stackTrace.length > 0 && stackTrace[0].getClassName().equals( testClassName ); + private boolean rootIsInclass() { + return stackTrace != null + && stackTrace.length > 0 + && stackTrace[0].getClassName().equals(testClassName); } - private static List focusOnClass( StackTraceElement[] stackTrace, Class clazz ) - { - if ( stackTrace == null ) - { + private static List focusOnClass(StackTraceElement[] stackTrace, Class clazz) { + if (stackTrace == null) { return Collections.emptyList(); } List result = new ArrayList<>(); - for ( StackTraceElement element : stackTrace ) - { - if ( element != null && isInSupers( clazz, element.getClassName() ) ) - { - result.add( element ); + for (StackTraceElement element : stackTrace) { + if (element != null && isInSupers(clazz, element.getClassName())) { + result.add(element); } } return result; } - private static boolean isInSupers( Class testClass, String lookFor ) - { - if ( lookFor.startsWith( "junit.framework." ) ) - { + private static boolean isInSupers(Class testClass, String lookFor) { + if (lookFor.startsWith("junit.framework.")) { return false; } - while ( !testClass.getName().equals( lookFor ) && testClass.getSuperclass() != null ) - { + while (!testClass.getName().equals(lookFor) && testClass.getSuperclass() != null) { testClass = testClass.getSuperclass(); } - return testClass.getName().equals( lookFor ); + return testClass.getName().equals(lookFor); } - static Throwable findTopmostWithClass( final Throwable t, StackTraceFilter filter ) - { + static Throwable findTopmostWithClass(final Throwable t, StackTraceFilter filter) { Throwable n = t; - do - { - if ( containsClassName( n.getStackTrace(), filter ) ) - { + do { + if (containsClassName(n.getStackTrace(), filter)) { return n; } n = n.getCause(); - } - while ( n != null ); + } while (n != null); return t; } - public static String stackTraceWithFocusOnClassAsString( Throwable t, String className ) - { - StackTraceFilter filter = new ClassNameStackTraceFilter( className ); - Throwable topmost = findTopmostWithClass( t, filter ); - List stackTraceElements = focusInsideClass( topmost.getStackTrace(), filter ); - String s = causeToString( topmost.getCause(), filter ); - return toString( t, stackTraceElements, filter ) + s; + public static String stackTraceWithFocusOnClassAsString(Throwable t, String className) { + StackTraceFilter filter = new ClassNameStackTraceFilter(className); + Throwable topmost = findTopmostWithClass(t, filter); + List stackTraceElements = focusInsideClass(topmost.getStackTrace(), filter); + String s = causeToString(topmost.getCause(), filter); + return toString(t, stackTraceElements, filter) + s; } - static List focusInsideClass( StackTraceElement[] stackTrace, StackTraceFilter filter ) - { + static List focusInsideClass(StackTraceElement[] stackTrace, StackTraceFilter filter) { List result = new ArrayList<>(); - for ( StackTraceElement element : stackTrace ) - { - if ( filter.matches( element ) ) - { - result.add( element ); + for (StackTraceElement element : stackTrace) { + if (filter.matches(element)) { + result.add(element); } } return result; } - private static boolean containsClassName( StackTraceElement[] stackTrace, StackTraceFilter filter ) - { - for ( StackTraceElement element : stackTrace ) - { - if ( filter.matches( element ) ) - { + private static boolean containsClassName(StackTraceElement[] stackTrace, StackTraceFilter filter) { + for (StackTraceElement element : stackTrace) { + if (filter.matches(element)) { return true; } } return false; } - private static String causeToString( Throwable cause, StackTraceFilter filter ) - { + private static String causeToString(Throwable cause, StackTraceFilter filter) { StringBuilder resp = new StringBuilder(); - while ( cause != null ) - { - resp.append( "Caused by: " ); - resp.append( toString( cause, asList( cause.getStackTrace() ), filter ) ); + while (cause != null) { + resp.append("Caused by: "); + resp.append(toString(cause, asList(cause.getStackTrace()), filter)); cause = cause.getCause(); } return resp.toString(); } - private static String toString( Throwable t, Iterable elements, StackTraceFilter filter ) - { + private static String toString(Throwable t, Iterable elements, StackTraceFilter filter) { StringBuilder result = new StringBuilder(); - if ( t != null ) - { - result.append( t.getClass().getName() ); + if (t != null) { + result.append(t.getClass().getName()); String msg = t.getMessage(); - if ( msg != null ) - { - result.append( ": " ); - if ( isMultiLine( msg ) ) - { + if (msg != null) { + result.append(": "); + if (isMultiLine(msg)) { // SUREFIRE-986 - result.append( '\n' ); + result.append('\n'); } - result.append( msg ); + result.append(msg); } - result.append( '\n' ); + result.append('\n'); } - for ( StackTraceElement element : elements ) - { - if ( filter.matches( element ) ) - { - result.append( "\tat " ) - .append( element ) - .append( '\n' ); + for (StackTraceElement element : elements) { + if (filter.matches(element)) { + result.append("\tat ").append(element).append('\n'); } } return result.toString(); } - private static boolean isMultiLine( String msg ) - { + private static boolean isMultiLine(String msg) { int countNewLines = 0; - for ( int i = 0, length = msg.length(); i < length; i++ ) - { - if ( msg.charAt( i ) == '\n' ) - { - if ( ++countNewLines == 2 ) - { + for (int i = 0, length = msg.length(); i < length; i++) { + if (msg.charAt(i) == '\n') { + if (++countNewLines == 2) { break; } } } - return countNewLines > 1 || countNewLines == 1 && !msg.trim().endsWith( "\n" ); + return countNewLines > 1 || countNewLines == 1 && !msg.trim().endsWith("\n"); } } diff --git a/surefire-providers/common-java5/src/main/java/org/apache/maven/surefire/report/StackTraceFilter.java b/surefire-providers/common-java5/src/main/java/org/apache/maven/surefire/report/StackTraceFilter.java index 3124544408..2dcf4c2804 100644 --- a/surefire-providers/common-java5/src/main/java/org/apache/maven/surefire/report/StackTraceFilter.java +++ b/surefire-providers/common-java5/src/main/java/org/apache/maven/surefire/report/StackTraceFilter.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.report; /* @@ -22,7 +40,6 @@ /** * StackTrace element filter. */ -interface StackTraceFilter -{ - boolean matches( StackTraceElement element ); +interface StackTraceFilter { + boolean matches(StackTraceElement element); } diff --git a/surefire-providers/common-java5/src/test/java/org/apache/maven/surefire/report/ABaseClass.java b/surefire-providers/common-java5/src/test/java/org/apache/maven/surefire/report/ABaseClass.java index 3f8692d5e0..fd897233e0 100644 --- a/surefire-providers/common-java5/src/test/java/org/apache/maven/surefire/report/ABaseClass.java +++ b/surefire-providers/common-java5/src/test/java/org/apache/maven/surefire/report/ABaseClass.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.report; /* @@ -22,10 +40,8 @@ /** * */ -public class ABaseClass -{ - public void npe() - { - throw new NullPointerException( "It was null" ); +public class ABaseClass { + public void npe() { + throw new NullPointerException("It was null"); } } diff --git a/surefire-providers/common-java5/src/test/java/org/apache/maven/surefire/report/ADifferen0tTestClass.java b/surefire-providers/common-java5/src/test/java/org/apache/maven/surefire/report/ADifferen0tTestClass.java index 3b58a81ddd..bbf65b380f 100644 --- a/surefire-providers/common-java5/src/test/java/org/apache/maven/surefire/report/ADifferen0tTestClass.java +++ b/surefire-providers/common-java5/src/test/java/org/apache/maven/surefire/report/ADifferen0tTestClass.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.report; /* @@ -19,7 +37,4 @@ * under the License. */ - -class ADifferen0tTestClass -{ -} +class ADifferen0tTestClass {} diff --git a/surefire-providers/common-java5/src/test/java/org/apache/maven/surefire/report/ASubClass.java b/surefire-providers/common-java5/src/test/java/org/apache/maven/surefire/report/ASubClass.java index 77e6d8e76c..6eb37e030d 100644 --- a/surefire-providers/common-java5/src/test/java/org/apache/maven/surefire/report/ASubClass.java +++ b/surefire-providers/common-java5/src/test/java/org/apache/maven/surefire/report/ASubClass.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.report; /* @@ -22,6 +40,4 @@ /** * */ -public class ASubClass extends ABaseClass -{ -} +public class ASubClass extends ABaseClass {} diff --git a/surefire-providers/common-java5/src/test/java/org/apache/maven/surefire/report/ATestClass.java b/surefire-providers/common-java5/src/test/java/org/apache/maven/surefire/report/ATestClass.java index 0fb2a7442d..8981f94266 100644 --- a/surefire-providers/common-java5/src/test/java/org/apache/maven/surefire/report/ATestClass.java +++ b/surefire-providers/common-java5/src/test/java/org/apache/maven/surefire/report/ATestClass.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.report; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,54 +16,46 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.report; import java.io.File; /** * */ -@SuppressWarnings( "UnusedDeclaration" ) -public class ATestClass -{ +@SuppressWarnings("UnusedDeclaration") +public class ATestClass { - public void failInAssert() - { - throw new AssertionError( "X is not Z" ); + public void failInAssert() { + throw new AssertionError("X is not Z"); } - public void nestedFailInAssert() - { + public void nestedFailInAssert() { failInAssert(); } - public void npe() - { - throw new NullPointerException( "It was null" ); + public void npe() { + throw new NullPointerException("It was null"); } - public void nestedNpe() - { + public void nestedNpe() { npe(); } - public void npeOutsideTest() - { - File file = new File( (String) null ); + public void npeOutsideTest() { + File file = new File((String) null); } - public void nestedNpeOutsideTest() - { + public void nestedNpeOutsideTest() { npeOutsideTest(); } - public void aLongTestErrorMessage() - { - throw new RuntimeException( "This message won't be truncated, somewhere over the rainbow. " - + "Gangnam style, Gangnam style, Gangnam style, , Gangnam style, Gangnam style" ); + public void aLongTestErrorMessage() { + throw new RuntimeException("This message won't be truncated, somewhere over the rainbow. " + + "Gangnam style, Gangnam style, Gangnam style, , Gangnam style, Gangnam style"); } - public void aMockedException() - { + public void aMockedException() { throw new SomeMockedException(); } } diff --git a/surefire-providers/common-java5/src/test/java/org/apache/maven/surefire/report/AssertionNoMessage.java b/surefire-providers/common-java5/src/test/java/org/apache/maven/surefire/report/AssertionNoMessage.java index 7c1e3a3c2b..ac9fa7af5e 100644 --- a/surefire-providers/common-java5/src/test/java/org/apache/maven/surefire/report/AssertionNoMessage.java +++ b/surefire-providers/common-java5/src/test/java/org/apache/maven/surefire/report/AssertionNoMessage.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.report; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,14 +16,12 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.report; import junit.framework.TestCase; -class AssertionNoMessage - extends TestCase -{ - public void testThrowSomething() - { - assertEquals( "abc", "xyz" ); +class AssertionNoMessage extends TestCase { + public void testThrowSomething() { + assertEquals("abc", "xyz"); } } diff --git a/surefire-providers/common-java5/src/test/java/org/apache/maven/surefire/report/CaseThatWillFail.java b/surefire-providers/common-java5/src/test/java/org/apache/maven/surefire/report/CaseThatWillFail.java index dc31fbb3c3..c3872ddf08 100644 --- a/surefire-providers/common-java5/src/test/java/org/apache/maven/surefire/report/CaseThatWillFail.java +++ b/surefire-providers/common-java5/src/test/java/org/apache/maven/surefire/report/CaseThatWillFail.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.report; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,14 +16,12 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.report; import junit.framework.TestCase; -class CaseThatWillFail - extends TestCase -{ - public void testThatWillFail() - { - assertEquals( "abc", "def" ); +class CaseThatWillFail extends TestCase { + public void testThatWillFail() { + assertEquals("abc", "def"); } } diff --git a/surefire-providers/common-java5/src/test/java/org/apache/maven/surefire/report/ClassMethodIndexerTest.java b/surefire-providers/common-java5/src/test/java/org/apache/maven/surefire/report/ClassMethodIndexerTest.java index bef648d470..10b578d02c 100644 --- a/surefire-providers/common-java5/src/test/java/org/apache/maven/surefire/report/ClassMethodIndexerTest.java +++ b/surefire-providers/common-java5/src/test/java/org/apache/maven/surefire/report/ClassMethodIndexerTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.report; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.report; import junit.framework.TestCase; @@ -26,50 +25,36 @@ /** * */ -@SuppressWarnings( "checkstyle:magicnumber" ) -public class ClassMethodIndexerTest - extends TestCase -{ - public void testNPE() - { +@SuppressWarnings("checkstyle:magicnumber") +public class ClassMethodIndexerTest extends TestCase { + public void testNPE() { ClassMethodIndexer indexer = new ClassMethodIndexer(); - try - { - indexer.indexClass( null ); - fail( "NPE expected" ); - } - catch ( NullPointerException e ) - { + try { + indexer.indexClass(null); + fail("NPE expected"); + } catch (NullPointerException e) { // expected } } - public void testClass() - { + public void testClass() { ClassMethodIndexer indexer = new ClassMethodIndexer(); - long index = indexer.indexClass( getClass().getName() ); - assertThat( index ) - .isEqualTo( 0x0000000100000000L ); + long index = indexer.indexClass(getClass().getName()); + assertThat(index).isEqualTo(0x0000000100000000L); } - public void testClassMethod() - { + public void testClassMethod() { ClassMethodIndexer indexer = new ClassMethodIndexer(); - long index = indexer.indexClassMethod( getClass().getName(), "methodName" ); - assertThat( index ) - .isEqualTo( 0x0000000100000001L ); + long index = indexer.indexClassMethod(getClass().getName(), "methodName"); + assertThat(index).isEqualTo(0x0000000100000001L); } - public void testRun() - { + public void testRun() { ClassMethodIndexer indexer = new ClassMethodIndexer(); - long index = indexer.indexClass( getClass().getName() ); - indexer.indexClass( "dummy" ); - assertThat( index ) - .isEqualTo( 0x0000000100000000L ); - index = indexer.indexClassMethod( getClass().getName(), "methodName" ); - assertThat( index ) - .isEqualTo( 0x0000000100000001L ); - + long index = indexer.indexClass(getClass().getName()); + indexer.indexClass("dummy"); + assertThat(index).isEqualTo(0x0000000100000000L); + index = indexer.indexClassMethod(getClass().getName(), "methodName"); + assertThat(index).isEqualTo(0x0000000100000001L); } } diff --git a/surefire-providers/common-java5/src/test/java/org/apache/maven/surefire/report/FailWithFail.java b/surefire-providers/common-java5/src/test/java/org/apache/maven/surefire/report/FailWithFail.java index 4acfe1b028..0406ffd8ce 100644 --- a/surefire-providers/common-java5/src/test/java/org/apache/maven/surefire/report/FailWithFail.java +++ b/surefire-providers/common-java5/src/test/java/org/apache/maven/surefire/report/FailWithFail.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.report; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,14 +16,12 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.report; import junit.framework.TestCase; -class FailWithFail - extends TestCase -{ - public void testThatWillFail() - { - fail( "abc" ); +class FailWithFail extends TestCase { + public void testThatWillFail() { + fail("abc"); } } diff --git a/surefire-providers/common-java5/src/test/java/org/apache/maven/surefire/report/InnerATestClass.java b/surefire-providers/common-java5/src/test/java/org/apache/maven/surefire/report/InnerATestClass.java index c85d230d03..9f626850e9 100644 --- a/surefire-providers/common-java5/src/test/java/org/apache/maven/surefire/report/InnerATestClass.java +++ b/surefire-providers/common-java5/src/test/java/org/apache/maven/surefire/report/InnerATestClass.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.report; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,25 +16,23 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.report; import junit.framework.Assert; /** -* Created with IntelliJ IDEA. -* User: kristian -* Date: 12/21/12 -* Time: 2:32 AM -* To change this template use File | Settings | File Templates. -*/ -class InnerATestClass -{ - public static void testFake() - { + * Created with IntelliJ IDEA. + * User: kristian + * Date: 12/21/12 + * Time: 2:32 AM + * To change this template use File | Settings | File Templates. + */ +class InnerATestClass { + public static void testFake() { innerMethod(); } - private static void innerMethod() - { - Assert.assertTrue( false ); + private static void innerMethod() { + Assert.assertTrue(false); } } diff --git a/surefire-providers/common-java5/src/test/java/org/apache/maven/surefire/report/OutermostClass.java b/surefire-providers/common-java5/src/test/java/org/apache/maven/surefire/report/OutermostClass.java index 91e723f526..62e4de0def 100644 --- a/surefire-providers/common-java5/src/test/java/org/apache/maven/surefire/report/OutermostClass.java +++ b/surefire-providers/common-java5/src/test/java/org/apache/maven/surefire/report/OutermostClass.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.report; /* @@ -19,10 +37,8 @@ * under the License. */ -class OutermostClass -{ - void junit() - { +class OutermostClass { + void junit() { new ATestClass().failInAssert(); } } diff --git a/surefire-providers/common-java5/src/test/java/org/apache/maven/surefire/report/PojoStackTraceWriterTest.java b/surefire-providers/common-java5/src/test/java/org/apache/maven/surefire/report/PojoStackTraceWriterTest.java index 69a3db06d7..8914ff49f0 100644 --- a/surefire-providers/common-java5/src/test/java/org/apache/maven/surefire/report/PojoStackTraceWriterTest.java +++ b/surefire-providers/common-java5/src/test/java/org/apache/maven/surefire/report/PojoStackTraceWriterTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.report; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,65 +16,48 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.report; import junit.framework.TestCase; /** * */ -public class PojoStackTraceWriterTest - extends TestCase -{ +public class PojoStackTraceWriterTest extends TestCase { - public void testTrimmedThrowableReal() - { + public void testTrimmedThrowableReal() { PojoStackTraceWriter w = - new PojoStackTraceWriter( ATestClass.AnotherTestClass.class.getName(), "testQuote", getAThrowAble() ); + new PojoStackTraceWriter(ATestClass.AnotherTestClass.class.getName(), "testQuote", getAThrowAble()); String out = w.writeTrimmedTraceToString(); String expected = "org.apache.maven.surefire.report.PojoStackTraceWriterTest$ATestClass$AnotherTestClass" + ".getAThrowable(PojoStackTraceWriterTest.java"; - assertTrue( out.contains( expected ) ); + assertTrue(out.contains(expected)); } - public void testMultiLineMessage() - { - String msg = - "assert \"foo\" == \"bar\"\n" - + " |\n" - + " false"; - try - { - throw new RuntimeException( msg ); - } - catch ( Throwable t ) - { - PojoStackTraceWriter writer = new PojoStackTraceWriter( null, null, t ); + public void testMultiLineMessage() { + String msg = "assert \"foo\" == \"bar\"\n" + " |\n" + " false"; + try { + throw new RuntimeException(msg); + } catch (Throwable t) { + PojoStackTraceWriter writer = new PojoStackTraceWriter(null, null, t); String stackTrace = writer.writeTraceToString(); - assertTrue( stackTrace.startsWith( "java.lang.RuntimeException: \n" + msg ) ); + assertTrue(stackTrace.startsWith("java.lang.RuntimeException: \n" + msg)); } } - static class ATestClass - { - static class AnotherTestClass - { - public static Throwable getAThrowable() - { - try - { - throw new Exception( "Hey ho, hey ho, a throwable we throw!" ); - } - catch ( Exception e ) - { + static class ATestClass { + static class AnotherTestClass { + public static Throwable getAThrowable() { + try { + throw new Exception("Hey ho, hey ho, a throwable we throw!"); + } catch (Exception e) { return e; } } } } - private Throwable getAThrowAble() - { + private Throwable getAThrowAble() { return ATestClass.AnotherTestClass.getAThrowable(); } - } diff --git a/surefire-providers/common-java5/src/test/java/org/apache/maven/surefire/report/RunnableTestClass1.java b/surefire-providers/common-java5/src/test/java/org/apache/maven/surefire/report/RunnableTestClass1.java index 9c72a6e2a3..2ac9a0ea2a 100644 --- a/surefire-providers/common-java5/src/test/java/org/apache/maven/surefire/report/RunnableTestClass1.java +++ b/surefire-providers/common-java5/src/test/java/org/apache/maven/surefire/report/RunnableTestClass1.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.report; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,38 +16,29 @@ * specific language governing permissions and limitations * under the License. */ - -import org.apache.maven.surefire.api.util.internal.DaemonThreadFactory; +package org.apache.maven.surefire.report; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.FutureTask; -class RunnableTestClass1 - implements Callable -{ +import org.apache.maven.surefire.api.util.internal.DaemonThreadFactory; + +class RunnableTestClass1 implements Callable { @Override - public Object call() - throws Exception - { + public Object call() throws Exception { doSomethingThatThrows(); return "yo"; } - private void doSomethingThatThrows() - throws ExecutionException - { + private void doSomethingThatThrows() throws ExecutionException { RunnableTestClass2 rt2 = new RunnableTestClass2(); - FutureTask futureTask = new FutureTask<>( rt2 ); - DaemonThreadFactory.newDaemonThread( futureTask ).start(); - try - { + FutureTask futureTask = new FutureTask<>(rt2); + DaemonThreadFactory.newDaemonThread(futureTask).start(); + try { futureTask.get(); - } - catch ( InterruptedException e ) - { + } catch (InterruptedException e) { throw new RuntimeException(); } } - } diff --git a/surefire-providers/common-java5/src/test/java/org/apache/maven/surefire/report/RunnableTestClass2.java b/surefire-providers/common-java5/src/test/java/org/apache/maven/surefire/report/RunnableTestClass2.java index 77da1c713e..0e7dcaf96e 100644 --- a/surefire-providers/common-java5/src/test/java/org/apache/maven/surefire/report/RunnableTestClass2.java +++ b/surefire-providers/common-java5/src/test/java/org/apache/maven/surefire/report/RunnableTestClass2.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.report; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,28 +16,21 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.report; import java.util.concurrent.Callable; -class RunnableTestClass2 - implements Callable - -{ +class RunnableTestClass2 implements Callable { @Override - public Object call() - throws Exception - { + public Object call() throws Exception { InnerRunnableTestClass.cThrows(); return null; } - static class InnerRunnableTestClass - { - public static void cThrows() - throws Exception - { - throw new Exception( "Hey ho, hey ho, a throwable we throw!" ); + static class InnerRunnableTestClass { + public static void cThrows() throws Exception { + throw new Exception("Hey ho, hey ho, a throwable we throw!"); } } } diff --git a/surefire-providers/common-java5/src/test/java/org/apache/maven/surefire/report/SmartStackTraceParserTest.java b/surefire-providers/common-java5/src/test/java/org/apache/maven/surefire/report/SmartStackTraceParserTest.java index f14784c734..303e763cf8 100644 --- a/surefire-providers/common-java5/src/test/java/org/apache/maven/surefire/report/SmartStackTraceParserTest.java +++ b/surefire-providers/common-java5/src/test/java/org/apache/maven/surefire/report/SmartStackTraceParserTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.report; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.report; import java.lang.reflect.Field; import java.util.List; @@ -36,359 +35,273 @@ /** * */ -@SuppressWarnings( "ThrowableResultOfMethodCallIgnored" ) -public class SmartStackTraceParserTest - extends TestCase -{ - public void testGetString() - { +@SuppressWarnings("ThrowableResultOfMethodCallIgnored") +public class SmartStackTraceParserTest extends TestCase { + public void testGetString() { ATestClass aTestClass = new ATestClass(); - try - { + try { aTestClass.failInAssert(); - } - catch ( AssertionError e ) - { + } catch (AssertionError e) { SmartStackTraceParser smartStackTraceParser = - new SmartStackTraceParser( ATestClass.class.getName(), e, null ); + new SmartStackTraceParser(ATestClass.class.getName(), e, null); String res = smartStackTraceParser.getString(); - assertEquals( "ATestClass.failInAssert:33 X is not Z", res ); + assertEquals("ATestClass.failInAssert:30 X is not Z", res); } } - public void testGetStringFromNested() - { + public void testGetStringFromNested() { OutermostClass aTestClass = new OutermostClass(); - try - { + try { aTestClass.junit(); - } - catch ( AssertionError e ) - { + } catch (AssertionError e) { SmartStackTraceParser smartStackTraceParser = - new SmartStackTraceParser( ATestClass.class.getName(), e, null ); + new SmartStackTraceParser(ATestClass.class.getName(), e, null); String res = smartStackTraceParser.getString(); - assertEquals( "ATestClass.failInAssert:33 X is not Z", res ); + assertEquals("ATestClass.failInAssert:30 X is not Z", res); } } - public void testGetStringWithMethod() - { + public void testGetStringWithMethod() { OutermostClass aTestClass = new OutermostClass(); - try - { + try { aTestClass.junit(); - } - catch ( AssertionError e ) - { + } catch (AssertionError e) { SmartStackTraceParser smartStackTraceParser = - new SmartStackTraceParser( InnerATestClass.class.getName(), e, "myMethod" ); + new SmartStackTraceParser(InnerATestClass.class.getName(), e, "myMethod"); String res = smartStackTraceParser.getString(); - assertEquals( "InnerATestClass.myMethod X is not Z", res ); + assertEquals("InnerATestClass.myMethod X is not Z", res); } } - public void testNestedFailure() - { + public void testNestedFailure() { ATestClass aTestClass = new ATestClass(); - try - { + try { aTestClass.nestedFailInAssert(); - } - catch ( AssertionError e ) - { + } catch (AssertionError e) { SmartStackTraceParser smartStackTraceParser = - new SmartStackTraceParser( ATestClass.class.getName(), e, null ); + new SmartStackTraceParser(ATestClass.class.getName(), e, null); String res = smartStackTraceParser.getString(); - assertEquals( "ATestClass.nestedFailInAssert:38->failInAssert:33 X is not Z", res ); + assertEquals("ATestClass.nestedFailInAssert:34->failInAssert:30 X is not Z", res); } } - public void testNestedNpe() - { + public void testNestedNpe() { ATestClass aTestClass = new ATestClass(); - try - { + try { aTestClass.nestedNpe(); - } - catch ( NullPointerException e ) - { + } catch (NullPointerException e) { SmartStackTraceParser smartStackTraceParser = - new SmartStackTraceParser( ATestClass.class.getName(), e, null ); + new SmartStackTraceParser(ATestClass.class.getName(), e, null); String res = smartStackTraceParser.getString(); - assertEquals( "ATestClass.nestedNpe:48->npe:43 NullPointer It was null", res ); + assertEquals("ATestClass.nestedNpe:42->npe:38 NullPointer It was null", res); } } - public void testNestedNpeOutsideTest() - { + public void testNestedNpeOutsideTest() { ATestClass aTestClass = new ATestClass(); - try - { + try { aTestClass.nestedNpeOutsideTest(); - } - catch ( NullPointerException e ) - { + } catch (NullPointerException e) { SmartStackTraceParser smartStackTraceParser = - new SmartStackTraceParser( ATestClass.class.getName(), e, null ); + new SmartStackTraceParser(ATestClass.class.getName(), e, null); String res = smartStackTraceParser.getString(); - assertEquals( "ATestClass.nestedNpeOutsideTest:58->npeOutsideTest:53 » NullPointer", res ); + assertEquals("ATestClass.nestedNpeOutsideTest:50->npeOutsideTest:46 » NullPointer", res); } } - public void testLongMessageHandling() - { + public void testLongMessageHandling() { ATestClass aTestClass = new ATestClass(); - try - { + try { aTestClass.aLongTestErrorMessage(); - } - catch ( RuntimeException e ) - { + } catch (RuntimeException e) { SmartStackTraceParser smartStackTraceParser = - new SmartStackTraceParser( ATestClass.class.getName(), e, null ); + new SmartStackTraceParser(ATestClass.class.getName(), e, null); String res = smartStackTraceParser.getString(); - assertEquals( "ATestClass.aLongTestErrorMessage:63 Runtime " + e.getMessage(), - res ); + assertEquals("ATestClass.aLongTestErrorMessage:54 Runtime " + e.getMessage(), res); } } - public void testFailureInBaseClass() - { + public void testFailureInBaseClass() { ASubClass aTestClass = new ASubClass(); - try - { + try { aTestClass.npe(); - } - catch ( NullPointerException e ) - { - SmartStackTraceParser smartStackTraceParser = - new SmartStackTraceParser( ASubClass.class.getName(), e, null ); + } catch (NullPointerException e) { + SmartStackTraceParser smartStackTraceParser = new SmartStackTraceParser(ASubClass.class.getName(), e, null); String res = smartStackTraceParser.getString(); - assertEquals( "ASubClass>ABaseClass.npe:29 » NullPointer It was null", res ); + assertEquals("ASubClass>ABaseClass.npe:45 » NullPointer It was null", res); } } - public void testClassThatWillFail() - { + public void testClassThatWillFail() { CaseThatWillFail aTestClass = new CaseThatWillFail(); - try - { + try { aTestClass.testThatWillFail(); - } - catch ( ComparisonFailure e ) - { + } catch (ComparisonFailure e) { SmartStackTraceParser smartStackTraceParser = - new SmartStackTraceParser( CaseThatWillFail.class.getName(), e, null ); + new SmartStackTraceParser(CaseThatWillFail.class.getName(), e, null); String res = smartStackTraceParser.getString(); - assertEquals( "CaseThatWillFail.testThatWillFail:29 expected:<[abc]> but was:<[def]>", res ); + assertEquals("CaseThatWillFail.testThatWillFail:25 expected:<[abc]> but was:<[def]>", res); } } - private static Throwable getAThrownException() - { - try - { + private static Throwable getAThrownException() { + try { TestClass1.InnerBTestClass.throwSomething(); - } - catch ( Throwable t ) - { + } catch (Throwable t) { return t; } return null; } - public void testCollections() - { + public void testCollections() { Throwable aThrownException = getAThrownException(); - List innerMost = - focusInsideClass( aThrownException.getCause().getStackTrace(), - new ClassNameStackTraceFilter( TestClass1.InnerBTestClass.class.getName() ) ); - assertEquals( 2, innerMost.size() ); - StackTraceElement inner = innerMost.get( 0 ); - assertEquals( TestClass1.InnerBTestClass.class.getName(), inner.getClassName() ); - StackTraceElement outer = innerMost.get( 1 ); - assertEquals( TestClass1.InnerBTestClass.class.getName(), outer.getClassName() ); + List innerMost = focusInsideClass( + aThrownException.getCause().getStackTrace(), + new ClassNameStackTraceFilter(TestClass1.InnerBTestClass.class.getName())); + assertEquals(2, innerMost.size()); + StackTraceElement inner = innerMost.get(0); + assertEquals(TestClass1.InnerBTestClass.class.getName(), inner.getClassName()); + StackTraceElement outer = innerMost.get(1); + assertEquals(TestClass1.InnerBTestClass.class.getName(), outer.getClassName()); } - public void testAssertionWithNoMessage() - { - try - { + public void testAssertionWithNoMessage() { + try { new AssertionNoMessage().testThrowSomething(); - } - catch ( ComparisonFailure e ) - { + } catch (ComparisonFailure e) { SmartStackTraceParser smartStackTraceParser = - new SmartStackTraceParser( AssertionNoMessage.class.getName(), e, null ); + new SmartStackTraceParser(AssertionNoMessage.class.getName(), e, null); String res = smartStackTraceParser.getString(); - assertEquals( "AssertionNoMessage.testThrowSomething:29 expected:<[abc]> but was:<[xyz]>", res ); + assertEquals("AssertionNoMessage.testThrowSomething:25 expected:<[abc]> but was:<[xyz]>", res); } } - public void testFailWithFail() - { - try - { + public void testFailWithFail() { + try { new FailWithFail().testThatWillFail(); - } - catch ( AssertionFailedError e ) - { + } catch (AssertionFailedError e) { SmartStackTraceParser smartStackTraceParser = - new SmartStackTraceParser( FailWithFail.class.getName(), e, null ); + new SmartStackTraceParser(FailWithFail.class.getName(), e, null); String res = smartStackTraceParser.getString(); - assertEquals( "FailWithFail.testThatWillFail:29 abc", res ); + assertEquals("FailWithFail.testThatWillFail:25 abc", res); } } - public void testCollectorWithNested() - { - try - { + public void testCollectorWithNested() { + try { InnerATestClass.testFake(); - } - catch ( Throwable t ) - { + } catch (Throwable t) { List stackTraceElements = - focusInsideClass( t.getStackTrace(), - new ClassNameStackTraceFilter( InnerATestClass.class.getName() ) ); - assertNotNull( stackTraceElements ); - assertEquals( 2, stackTraceElements.size() ); - StackTraceElement innerMost = stackTraceElements.get( 0 ); - assertEquals( InnerATestClass.class.getName(), innerMost.getClassName() ); - StackTraceElement outer = stackTraceElements.get( 1 ); - assertEquals( InnerATestClass.class.getName(), outer.getClassName() ); + focusInsideClass(t.getStackTrace(), new ClassNameStackTraceFilter(InnerATestClass.class.getName())); + assertNotNull(stackTraceElements); + assertEquals(2, stackTraceElements.size()); + StackTraceElement innerMost = stackTraceElements.get(0); + assertEquals(InnerATestClass.class.getName(), innerMost.getClassName()); + StackTraceElement outer = stackTraceElements.get(1); + assertEquals(InnerATestClass.class.getName(), outer.getClassName()); } } - public void testNonClassNameStacktrace() - { + public void testNonClassNameStacktrace() { SmartStackTraceParser smartStackTraceParser = - new SmartStackTraceParser( "Not a class name", new Throwable( "my message" ), null ); - assertEquals( "my message", smartStackTraceParser.getString() ); + new SmartStackTraceParser("Not a class name", new Throwable("my message"), null); + assertEquals("my message", smartStackTraceParser.getString()); } - public void testNullElementInStackTrace() - throws Exception - { + public void testNullElementInStackTrace() throws Exception { ATestClass aTestClass = new ATestClass(); - try - { + try { aTestClass.failInAssert(); - } - catch ( AssertionError e ) - { + } catch (AssertionError e) { SmartStackTraceParser smartStackTraceParser = - new SmartStackTraceParser( ATestClass.class.getName(), e, null ); - Field stackTrace = SmartStackTraceParser.class.getDeclaredField( "stackTrace" ); - stackTrace.setAccessible( true ); - stackTrace.set( smartStackTraceParser, new StackTraceElement[0] ); + new SmartStackTraceParser(ATestClass.class.getName(), e, null); + Field stackTrace = SmartStackTraceParser.class.getDeclaredField("stackTrace"); + stackTrace.setAccessible(true); + stackTrace.set(smartStackTraceParser, new StackTraceElement[0]); String res = smartStackTraceParser.getString(); - assertEquals( "ATestClass X is not Z", res ); + assertEquals("ATestClass X is not Z", res); } } - public void testSingleNestedWithThread() - { + public void testSingleNestedWithThread() { ExecutionException e = getSingleNested(); String name = getClass().getName(); - Throwable focus = findTopmostWithClass( e, new ClassNameStackTraceFilter( name ) ); - assertSame( e, focus ); + Throwable focus = findTopmostWithClass(e, new ClassNameStackTraceFilter(name)); + assertSame(e, focus); List stackTraceElements = - focusInsideClass( focus.getStackTrace(), new ClassNameStackTraceFilter( name ) ); - assertEquals( stackTraceElements.get( stackTraceElements.size() - 1 ).getClassName(), name ); + focusInsideClass(focus.getStackTrace(), new ClassNameStackTraceFilter(name)); + assertEquals(stackTraceElements.get(stackTraceElements.size() - 1).getClassName(), name); } - public void testDoubleNestedWithThread() - { + public void testDoubleNestedWithThread() { ExecutionException e = getDoubleNestedException(); String name = getClass().getName(); - Throwable focus = findTopmostWithClass( e, new ClassNameStackTraceFilter( name ) ); - assertSame( e, focus ); + Throwable focus = findTopmostWithClass(e, new ClassNameStackTraceFilter(name)); + assertSame(e, focus); List stackTraceElements = - focusInsideClass( focus.getStackTrace(), new ClassNameStackTraceFilter( name ) ); - assertEquals( stackTraceElements.get( stackTraceElements.size() - 1 ).getClassName(), name ); + focusInsideClass(focus.getStackTrace(), new ClassNameStackTraceFilter(name)); + assertEquals(stackTraceElements.get(stackTraceElements.size() - 1).getClassName(), name); name = RunnableTestClass1.class.getName(); - focus = findTopmostWithClass( e, new ClassNameStackTraceFilter( name ) ); - assertSame( e.getCause(), focus ); - stackTraceElements = focusInsideClass( focus.getStackTrace(), new ClassNameStackTraceFilter( name ) ); - assertEquals( stackTraceElements.get( stackTraceElements.size() - 1 ).getClassName(), name ); + focus = findTopmostWithClass(e, new ClassNameStackTraceFilter(name)); + assertSame(e.getCause(), focus); + stackTraceElements = focusInsideClass(focus.getStackTrace(), new ClassNameStackTraceFilter(name)); + assertEquals(stackTraceElements.get(stackTraceElements.size() - 1).getClassName(), name); } - public void testStackTraceWithFocusOnClassAsString() - { - try - { + public void testStackTraceWithFocusOnClassAsString() { + try { new StackTraceFocusedOnClass.C().c(); fail(); - } - catch ( Exception e ) - { - String trace = stackTraceWithFocusOnClassAsString( e, StackTraceFocusedOnClass.B.class.getName() ); + } catch (Exception e) { + String trace = stackTraceWithFocusOnClassAsString(e, StackTraceFocusedOnClass.B.class.getName()); assertEquals( "java.lang.RuntimeException: java.lang.IllegalStateException: java.io.IOException: I/O error\n" - + "\tat org.apache.maven.surefire.report.StackTraceFocusedOnClass$B.b(StackTraceFocusedOnClass.java:65)\n" - + "Caused by: java.lang.IllegalStateException: java.io.IOException: I/O error\n" - + "\tat org.apache.maven.surefire.report.StackTraceFocusedOnClass$B.b(StackTraceFocusedOnClass.java:61)\n" - + "Caused by: java.io.IOException: I/O error\n" - + "\tat org.apache.maven.surefire.report.StackTraceFocusedOnClass$B.abs(StackTraceFocusedOnClass.java:73)\n" - + "\tat org.apache.maven.surefire.report.StackTraceFocusedOnClass$B.b(StackTraceFocusedOnClass.java:61)\n", - trace ); + + "\tat org.apache.maven.surefire.report.StackTraceFocusedOnClass$B.b(StackTraceFocusedOnClass.java:49)\n" + + "Caused by: java.lang.IllegalStateException: java.io.IOException: I/O error\n" + + "\tat org.apache.maven.surefire.report.StackTraceFocusedOnClass$B.b(StackTraceFocusedOnClass.java:47)\n" + + "Caused by: java.io.IOException: I/O error\n" + + "\tat org.apache.maven.surefire.report.StackTraceFocusedOnClass$B.abs(StackTraceFocusedOnClass.java:55)\n" + + "\tat org.apache.maven.surefire.report.StackTraceFocusedOnClass$B.b(StackTraceFocusedOnClass.java:47)\n", + trace); } } - public void testNullStackTrace() - { - try - { + public void testNullStackTrace() { + try { new ATestClass().aMockedException(); - } - catch ( Exception e ) - { + } catch (Exception e) { SmartStackTraceParser smartStackTraceParser = - new SmartStackTraceParser( ATestClass.class.getName(), e, null ); + new SmartStackTraceParser(ATestClass.class.getName(), e, null); String res = smartStackTraceParser.getString(); - assertEquals( "ATestClass » SomeMocked", res ); + assertEquals("ATestClass » SomeMocked", res); } } - private ExecutionException getSingleNested() - { - FutureTask futureTask = new FutureTask<>( new RunnableTestClass2() ); - DaemonThreadFactory.newDaemonThread( futureTask ).start(); - try - { + private ExecutionException getSingleNested() { + FutureTask futureTask = new FutureTask<>(new RunnableTestClass2()); + DaemonThreadFactory.newDaemonThread(futureTask).start(); + try { futureTask.get(); - } - catch ( InterruptedException e ) - { + } catch (InterruptedException e) { fail(); - } - catch ( ExecutionException e ) - { + } catch (ExecutionException e) { return e; } fail(); return null; } - private ExecutionException getDoubleNestedException() - { - FutureTask futureTask = new FutureTask<>( new RunnableTestClass1() ); - DaemonThreadFactory.newDaemonThread( futureTask ).start(); - try - { + private ExecutionException getDoubleNestedException() { + FutureTask futureTask = new FutureTask<>(new RunnableTestClass1()); + DaemonThreadFactory.newDaemonThread(futureTask).start(); + try { futureTask.get(); - } - catch ( InterruptedException e ) - { + } catch (InterruptedException e) { fail(); - } - catch ( ExecutionException e ) - { + } catch (ExecutionException e) { return e; } return null; diff --git a/surefire-providers/common-java5/src/test/java/org/apache/maven/surefire/report/SomeMockedException.java b/surefire-providers/common-java5/src/test/java/org/apache/maven/surefire/report/SomeMockedException.java index 5852db23ba..782a8bb668 100644 --- a/surefire-providers/common-java5/src/test/java/org/apache/maven/surefire/report/SomeMockedException.java +++ b/surefire-providers/common-java5/src/test/java/org/apache/maven/surefire/report/SomeMockedException.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.report; /* @@ -22,39 +40,31 @@ /** * @author Adam Jones */ -public class SomeMockedException extends RuntimeException -{ - public SomeMockedException() - { - } +public class SomeMockedException extends RuntimeException { + public SomeMockedException() {} @Override - public String getMessage() - { + public String getMessage() { return null; } @Override - public String getLocalizedMessage() - { + public String getLocalizedMessage() { return null; } @Override - public Throwable getCause() - { + public Throwable getCause() { return null; } @Override - public String toString() - { + public String toString() { return null; } @Override - public StackTraceElement[] getStackTrace() - { + public StackTraceElement[] getStackTrace() { return null; } } diff --git a/surefire-providers/common-java5/src/test/java/org/apache/maven/surefire/report/StackTraceFocusedOnClass.java b/surefire-providers/common-java5/src/test/java/org/apache/maven/surefire/report/StackTraceFocusedOnClass.java index b544c0478d..b6fadfb15b 100644 --- a/surefire-providers/common-java5/src/test/java/org/apache/maven/surefire/report/StackTraceFocusedOnClass.java +++ b/surefire-providers/common-java5/src/test/java/org/apache/maven/surefire/report/StackTraceFocusedOnClass.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.report; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,68 +16,50 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.report; import java.io.IOException; -final class StackTraceFocusedOnClass -{ - static class JRE - { - void throwException() - throws IOException - { - throw new IOException( "I/O error" ); +final class StackTraceFocusedOnClass { + static class JRE { + void throwException() throws IOException { + throw new IOException("I/O error"); } } - abstract static class A - { - abstract void abs() - throws IOException; + abstract static class A { + abstract void abs() throws IOException; - void a() - { - try - { + void a() { + try { abs(); - } - catch ( Exception e ) - { - throw new IllegalStateException( e ); + } catch (Exception e) { + throw new IllegalStateException(e); } } } - static class B extends A - { + static class B extends A { private final JRE jre = new JRE(); - void b() - { - try - { + void b() { + try { a(); - } - catch ( Exception e ) - { - throw new RuntimeException( e ); + } catch (Exception e) { + throw new RuntimeException(e); } } @Override - void abs() - throws IOException - { + void abs() throws IOException { jre.throwException(); } } - static class C - { + static class C { private final B b = new B(); - void c() - { + void c() { b.b(); } } diff --git a/surefire-providers/common-java5/src/test/java/org/apache/maven/surefire/report/TestClass1.java b/surefire-providers/common-java5/src/test/java/org/apache/maven/surefire/report/TestClass1.java index e878fd03c3..e2a0e66b3f 100644 --- a/surefire-providers/common-java5/src/test/java/org/apache/maven/surefire/report/TestClass1.java +++ b/surefire-providers/common-java5/src/test/java/org/apache/maven/surefire/report/TestClass1.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.report; /* @@ -19,24 +37,17 @@ * under the License. */ -class TestClass1 -{ - static class InnerBTestClass - { - public static void throwSomething() - { +class TestClass1 { + static class InnerBTestClass { + public static void throwSomething() { innerThrowSomething(); } - public static void innerThrowSomething() - { - try - { + public static void innerThrowSomething() { + try { TestClass2.InnerCTestClass.cThrows(); - } - catch ( Exception e ) - { - throw new RuntimeException( e ); + } catch (Exception e) { + throw new RuntimeException(e); } } } diff --git a/surefire-providers/common-java5/src/test/java/org/apache/maven/surefire/report/TestClass2.java b/surefire-providers/common-java5/src/test/java/org/apache/maven/surefire/report/TestClass2.java index 4c986f0b32..0fb2eb2a82 100644 --- a/surefire-providers/common-java5/src/test/java/org/apache/maven/surefire/report/TestClass2.java +++ b/surefire-providers/common-java5/src/test/java/org/apache/maven/surefire/report/TestClass2.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.report; /* @@ -19,14 +37,10 @@ * under the License. */ -class TestClass2 -{ - static class InnerCTestClass - { - public static void cThrows() - throws Exception - { - throw new Exception( "Hey ho, hey ho, a throwable we throw!" ); +class TestClass2 { + static class InnerCTestClass { + public static void cThrows() throws Exception { + throw new Exception("Hey ho, hey ho, a throwable we throw!"); } } } diff --git a/surefire-providers/common-junit3/pom.xml b/surefire-providers/common-junit3/pom.xml index 06ff3da8e7..3e6be7557e 100644 --- a/surefire-providers/common-junit3/pom.xml +++ b/surefire-providers/common-junit3/pom.xml @@ -1,3 +1,4 @@ + - 4.0.0 @@ -31,6 +31,10 @@ Shared JUnit3 Provider Code Shared JUnit3 Provider Code + + surefire-3.0.0-M8 + + junit @@ -45,6 +49,9 @@ org.jacoco jacoco-maven-plugin + + jacoco.agent + jacoco-agent @@ -53,9 +60,6 @@ - - jacoco.agent - maven-surefire-plugin @@ -66,14 +70,11 @@ org.apache.maven.surefire surefire-shadefire - 3.0.0-M7 + 3.0.0-M7 + - - - surefire-3.0.0-M8 - diff --git a/surefire-providers/common-junit3/src/main/java/org/apache/maven/surefire/common/junit3/JUnit3Reflector.java b/surefire-providers/common-junit3/src/main/java/org/apache/maven/surefire/common/junit3/JUnit3Reflector.java index 9a7b032931..ed76798749 100644 --- a/surefire-providers/common-junit3/src/main/java/org/apache/maven/surefire/common/junit3/JUnit3Reflector.java +++ b/surefire-providers/common-junit3/src/main/java/org/apache/maven/surefire/common/junit3/JUnit3Reflector.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.common.junit3; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,19 +16,20 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.common.junit3; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; + import org.apache.maven.surefire.api.util.ReflectionUtils; /** * Reflection facade for JUnit3 classes * */ -public final class JUnit3Reflector -{ +public final class JUnit3Reflector { private static final String TEST_CASE = "junit.framework.Test"; private static final String TEST_RESULT = "junit.framework.TestResult"; @@ -45,9 +44,9 @@ public final class JUnit3Reflector private static final String TEST_SUITE = "junit.framework.TestSuite"; - private static final Class[] EMPTY_CLASS_ARRAY = { }; + private static final Class[] EMPTY_CLASS_ARRAY = {}; - private static final Object[] EMPTY_OBJECT_ARRAY = { }; + private static final Object[] EMPTY_OBJECT_ARRAY = {}; private final Class[] interfacesImplementedByDynamicProxy; @@ -63,29 +62,24 @@ public final class JUnit3Reflector private final Constructor testsSuiteConstructor; - public JUnit3Reflector( ClassLoader testClassLoader ) - { - testResultClass = ReflectionUtils.tryLoadClass( testClassLoader, TEST_RESULT ); - testCase = ReflectionUtils.tryLoadClass( testClassLoader, TEST_CASE ); - testInterface = ReflectionUtils.tryLoadClass( testClassLoader, TEST ); + public JUnit3Reflector(ClassLoader testClassLoader) { + testResultClass = ReflectionUtils.tryLoadClass(testClassLoader, TEST_RESULT); + testCase = ReflectionUtils.tryLoadClass(testClassLoader, TEST_CASE); + testInterface = ReflectionUtils.tryLoadClass(testClassLoader, TEST); interfacesImplementedByDynamicProxy = - new Class[]{ ReflectionUtils.tryLoadClass( testClassLoader, TEST_LISTENER ) }; - Class[] constructorParamTypes = { Class.class }; + new Class[] {ReflectionUtils.tryLoadClass(testClassLoader, TEST_LISTENER)}; + Class[] constructorParamTypes = {Class.class}; - Class testSuite = ReflectionUtils.tryLoadClass( testClassLoader, TEST_SUITE ); + Class testSuite = ReflectionUtils.tryLoadClass(testClassLoader, TEST_SUITE); // The interface implemented by the dynamic proxy (TestListener), happens to be // the same as the param types of TestResult.addTestListener - if ( isJUnit3Available() ) - { - testsSuiteConstructor = ReflectionUtils.getConstructor( testSuite, constructorParamTypes ); - addListenerMethod = - tryGetMethod( testResultClass, ADD_LISTENER_METHOD, interfacesImplementedByDynamicProxy ); - testInterfaceRunMethod = getMethod( testInterface, RUN_METHOD, testResultClass ); - } - else - { + if (isJUnit3Available()) { + testsSuiteConstructor = ReflectionUtils.getConstructor(testSuite, constructorParamTypes); + addListenerMethod = tryGetMethod(testResultClass, ADD_LISTENER_METHOD, interfacesImplementedByDynamicProxy); + testInterfaceRunMethod = getMethod(testInterface, RUN_METHOD, testResultClass); + } else { testsSuiteConstructor = null; addListenerMethod = null; testInterfaceRunMethod = null; @@ -93,122 +87,90 @@ public JUnit3Reflector( ClassLoader testClassLoader ) } // Switch to reflectionutils when building with 2.7.2 - private static Method tryGetMethod( Class clazz, String methodName, Class... parameters ) - { - try - { - return clazz.getMethod( methodName, parameters ); - } - catch ( NoSuchMethodException e ) - { + private static Method tryGetMethod(Class clazz, String methodName, Class... parameters) { + try { + return clazz.getMethod(methodName, parameters); + } catch (NoSuchMethodException e) { return null; } } - private static Method getMethod( Class clazz, String methodName, Class... parameters ) - { - try - { - return clazz.getMethod( methodName, parameters ); - } - catch ( NoSuchMethodException e ) - { - throw new RuntimeException( "When finding method " + methodName, e ); + private static Method getMethod(Class clazz, String methodName, Class... parameters) { + try { + return clazz.getMethod(methodName, parameters); + } catch (NoSuchMethodException e) { + throw new RuntimeException("When finding method " + methodName, e); } } + public Object constructTestObject(Class testClass) + throws IllegalAccessException, InvocationTargetException, NoSuchMethodException, InstantiationException { + Object testObject = createInstanceFromSuiteMethod(testClass); - public Object constructTestObject( Class testClass ) - throws IllegalAccessException, InvocationTargetException, NoSuchMethodException, InstantiationException - { - Object testObject = createInstanceFromSuiteMethod( testClass ); - - if ( testObject == null && testCase.isAssignableFrom( testClass ) ) - { - testObject = testsSuiteConstructor.newInstance( testClass ); + if (testObject == null && testCase.isAssignableFrom(testClass)) { + testObject = testsSuiteConstructor.newInstance(testClass); } - if ( testObject == null ) - { - Constructor testConstructor = getTestConstructor( testClass ); + if (testObject == null) { + Constructor testConstructor = getTestConstructor(testClass); - if ( testConstructor.getParameterTypes().length == 0 ) - { - testObject = testConstructor.newInstance( EMPTY_OBJECT_ARRAY ); - } - else - { - testObject = testConstructor.newInstance( testClass.getName() ); + if (testConstructor.getParameterTypes().length == 0) { + testObject = testConstructor.newInstance(EMPTY_OBJECT_ARRAY); + } else { + testObject = testConstructor.newInstance(testClass.getName()); } } return testObject; } - private static Object createInstanceFromSuiteMethod( Class testClass ) - throws IllegalAccessException, InvocationTargetException - { + private static Object createInstanceFromSuiteMethod(Class testClass) + throws IllegalAccessException, InvocationTargetException { Object testObject = null; - try - { - Method suiteMethod = testClass.getMethod( "suite", EMPTY_CLASS_ARRAY ); + try { + Method suiteMethod = testClass.getMethod("suite", EMPTY_CLASS_ARRAY); - if ( Modifier.isPublic( suiteMethod.getModifiers() ) && Modifier.isStatic( suiteMethod.getModifiers() ) ) - { - testObject = suiteMethod.invoke( null, EMPTY_OBJECT_ARRAY ); + if (Modifier.isPublic(suiteMethod.getModifiers()) && Modifier.isStatic(suiteMethod.getModifiers())) { + testObject = suiteMethod.invoke(null, EMPTY_OBJECT_ARRAY); } - } - catch ( NoSuchMethodException e ) - { + } catch (NoSuchMethodException e) { // No suite method } return testObject; } - private static Constructor getTestConstructor( Class testClass ) - throws NoSuchMethodException - { - try - { - return testClass.getConstructor( String.class ); - } - catch ( NoSuchMethodException e ) - { - return testClass.getConstructor( EMPTY_CLASS_ARRAY ); + private static Constructor getTestConstructor(Class testClass) throws NoSuchMethodException { + try { + return testClass.getConstructor(String.class); + } catch (NoSuchMethodException e) { + return testClass.getConstructor(EMPTY_CLASS_ARRAY); } } - public Class[] getInterfacesImplementedByDynamicProxy() - { + public Class[] getInterfacesImplementedByDynamicProxy() { return interfacesImplementedByDynamicProxy; } - public Class getTestResultClass() - { + public Class getTestResultClass() { return testResultClass; } - public Method getAddListenerMethod() - { + public Method getAddListenerMethod() { return addListenerMethod; } - public Method getTestInterfaceRunMethod() - { + public Method getTestInterfaceRunMethod() { return testInterfaceRunMethod; } - public Class getTestInterface() - { + public Class getTestInterface() { return testInterface; } - public Method getRunMethod( Class testClass ) - { - return getMethod( testClass, RUN_METHOD, getTestResultClass() ); + public Method getRunMethod(Class testClass) { + return getMethod(testClass, RUN_METHOD, getTestResultClass()); } - public boolean isJUnit3Available() - { + public boolean isJUnit3Available() { return testResultClass != null; } } diff --git a/surefire-providers/common-junit3/src/main/java/org/apache/maven/surefire/common/junit3/JUnit3TestChecker.java b/surefire-providers/common-junit3/src/main/java/org/apache/maven/surefire/common/junit3/JUnit3TestChecker.java index 4feeb3cd68..da655560cb 100644 --- a/surefire-providers/common-junit3/src/main/java/org/apache/maven/surefire/common/junit3/JUnit3TestChecker.java +++ b/surefire-providers/common-junit3/src/main/java/org/apache/maven/surefire/common/junit3/JUnit3TestChecker.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.common.junit3; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,8 +16,10 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.common.junit3; import java.lang.reflect.Method; + import org.apache.maven.surefire.api.filter.NonAbstractClassFilter; import org.apache.maven.surefire.api.util.ScannerFilter; @@ -36,43 +36,34 @@ * * @author Kristian Rosenvold */ -public class JUnit3TestChecker - implements ScannerFilter -{ +public class JUnit3TestChecker implements ScannerFilter { private static final Class[] EMPTY_CLASS_ARRAY = new Class[0]; private final Class junitClass; private final NonAbstractClassFilter nonAbstractClassFilter = new NonAbstractClassFilter(); - public JUnit3TestChecker( ClassLoader testClassLoader ) - { - junitClass = tryLoadClass( testClassLoader, "junit.framework.Test" ); + public JUnit3TestChecker(ClassLoader testClassLoader) { + junitClass = tryLoadClass(testClassLoader, "junit.framework.Test"); } @Override - public boolean accept( Class testClass ) - { - return nonAbstractClassFilter.accept( testClass ) && isValidJUnit3Test( testClass ); + public boolean accept(Class testClass) { + return nonAbstractClassFilter.accept(testClass) && isValidJUnit3Test(testClass); } - private boolean isValidJUnit3Test( Class testClass ) - { - return junitClass != null && ( junitClass.isAssignableFrom( testClass ) || isSuiteOnly( testClass ) ); + private boolean isValidJUnit3Test(Class testClass) { + return junitClass != null && (junitClass.isAssignableFrom(testClass) || isSuiteOnly(testClass)); } - private boolean isSuiteOnly( Class testClass ) - { - final Method suite = tryGetMethod( testClass, "suite", EMPTY_CLASS_ARRAY ); - if ( suite != null ) - { + private boolean isSuiteOnly(Class testClass) { + final Method suite = tryGetMethod(testClass, "suite", EMPTY_CLASS_ARRAY); + if (suite != null) { final int modifiers = suite.getModifiers(); - if ( isPublic( modifiers ) && isStatic( modifiers ) ) - { - return junit.framework.Test.class.isAssignableFrom( suite.getReturnType() ); + if (isPublic(modifiers) && isStatic(modifiers)) { + return junit.framework.Test.class.isAssignableFrom(suite.getReturnType()); } } return false; } - } diff --git a/surefire-providers/common-junit3/src/test/java/org/apache/maven/surefire/common/junit3/JUnit3TestCheckerTest.java b/surefire-providers/common-junit3/src/test/java/org/apache/maven/surefire/common/junit3/JUnit3TestCheckerTest.java index 7fd71f5fea..efb89fe247 100644 --- a/surefire-providers/common-junit3/src/test/java/org/apache/maven/surefire/common/junit3/JUnit3TestCheckerTest.java +++ b/surefire-providers/common-junit3/src/test/java/org/apache/maven/surefire/common/junit3/JUnit3TestCheckerTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.common.junit3; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.common.junit3; import junit.framework.TestCase; import junit.framework.TestResult; @@ -25,71 +24,55 @@ /** * @author Kristian Rosenvold */ -public class JUnit3TestCheckerTest - extends TestCase -{ - private final JUnit3TestChecker jUnit3TestChecker = new JUnit3TestChecker( this.getClass().getClassLoader() ); - - public void testValidJunit4Annotated() - { - assertTrue( jUnit3TestChecker.accept( JUnit3TestCheckerTest.class ) ); +public class JUnit3TestCheckerTest extends TestCase { + private final JUnit3TestChecker jUnit3TestChecker = + new JUnit3TestChecker(this.getClass().getClassLoader()); + + public void testValidJunit4Annotated() { + assertTrue(jUnit3TestChecker.accept(JUnit3TestCheckerTest.class)); } - public void testValidJunit4itsAJunit3Test() - { - assertTrue( jUnit3TestChecker.accept( AlsoValid.class ) ); + public void testValidJunit4itsAJunit3Test() { + assertTrue(jUnit3TestChecker.accept(AlsoValid.class)); } - public void testValidJunitSubclassWithoutOwnTestmethods() - { - assertTrue( jUnit3TestChecker.accept( SubClassWithoutOwnTestMethods.class ) ); + public void testValidJunitSubclassWithoutOwnTestmethods() { + assertTrue(jUnit3TestChecker.accept(SubClassWithoutOwnTestMethods.class)); } - public void testInvalidTest() - { - assertFalse( jUnit3TestChecker.accept( NotValidTest.class ) ); + public void testInvalidTest() { + assertFalse(jUnit3TestChecker.accept(NotValidTest.class)); } - public void testDontAcceptAbstractClasses() - { - assertFalse( jUnit3TestChecker.accept( BaseClassWithTest.class ) ); + public void testDontAcceptAbstractClasses() { + assertFalse(jUnit3TestChecker.accept(BaseClassWithTest.class)); } - public void testSuiteOnlyTest() - { - assertTrue( jUnit3TestChecker.accept( SuiteOnlyTest.class ) ); + public void testSuiteOnlyTest() { + assertTrue(jUnit3TestChecker.accept(SuiteOnlyTest.class)); } - public void testCustomSuiteOnlyTest() - { - assertTrue( jUnit3TestChecker.accept( CustomSuiteOnlyTest.class ) ); + public void testCustomSuiteOnlyTest() { + assertTrue(jUnit3TestChecker.accept(CustomSuiteOnlyTest.class)); } - public void testIinnerClassNotAutomaticallyTc() - { - assertTrue( jUnit3TestChecker.accept( NestedTC.class ) ); - assertFalse( jUnit3TestChecker.accept( NestedTC.Inner.class ) ); + public void testIinnerClassNotAutomaticallyTc() { + assertTrue(jUnit3TestChecker.accept(NestedTC.class)); + assertFalse(jUnit3TestChecker.accept(NestedTC.Inner.class)); } /** * */ - public static class AlsoValid - extends TestCase - { - public void testSomething() - { - - } + public static class AlsoValid extends TestCase { + public void testSomething() {} } /** * */ - public static class SuiteOnlyTest - { - public static junit.framework.Test suite() - { + public static class SuiteOnlyTest { + public static junit.framework.Test suite() { return null; } } @@ -97,10 +80,8 @@ public static junit.framework.Test suite() /** * */ - public static class CustomSuiteOnlyTest - { - public static MySuite2 suite() - { + public static class CustomSuiteOnlyTest { + public static MySuite2 suite() { return null; } } @@ -108,58 +89,36 @@ public static MySuite2 suite() /** * */ - public static class MySuite2 - implements junit.framework.Test - { + public static class MySuite2 implements junit.framework.Test { @Override - public int countTestCases() - { + public int countTestCases() { return 0; } @Override - public void run( TestResult testResult ) - { - } + public void run(TestResult testResult) {} } - /** * */ - public static class NotValidTest - { - public void testSomething() - { - } + public static class NotValidTest { + public void testSomething() {} } /** * */ - public abstract static class BaseClassWithTest - extends TestCase - { - public void testWeAreAlsoATest() - { - } + public abstract static class BaseClassWithTest extends TestCase { + public void testWeAreAlsoATest() {} } /** * */ - public static class SubClassWithoutOwnTestMethods - extends BaseClassWithTest - { - } + public static class SubClassWithoutOwnTestMethods extends BaseClassWithTest {} - class NestedTC - extends TestCase - { - public class Inner - { - - } + class NestedTC extends TestCase { + public class Inner {} } - } diff --git a/surefire-providers/common-junit4/pom.xml b/surefire-providers/common-junit4/pom.xml index 4d2f36e557..5ad54898b2 100644 --- a/surefire-providers/common-junit4/pom.xml +++ b/surefire-providers/common-junit4/pom.xml @@ -1,3 +1,4 @@ + - 4.0.0 @@ -31,6 +31,10 @@ Shared JUnit4 Provider Code Shared JUnit4 Provider Code + + surefire-3.0.0-M8 + + junit @@ -55,6 +59,9 @@ org.jacoco jacoco-maven-plugin + + jacoco.agent + jacoco-agent @@ -63,9 +70,6 @@ - - jacoco.agent - maven-surefire-plugin @@ -76,14 +80,11 @@ org.apache.maven.surefire surefire-shadefire - 3.0.0-M7 + 3.0.0-M7 + - - - surefire-3.0.0-M8 - diff --git a/surefire-providers/common-junit4/src/main/java/org/apache/maven/surefire/common/junit4/JUnit4ProviderUtil.java b/surefire-providers/common-junit4/src/main/java/org/apache/maven/surefire/common/junit4/JUnit4ProviderUtil.java index 520685d87d..4b88aadc00 100644 --- a/surefire-providers/common-junit4/src/main/java/org/apache/maven/surefire/common/junit4/JUnit4ProviderUtil.java +++ b/surefire-providers/common-junit4/src/main/java/org/apache/maven/surefire/common/junit4/JUnit4ProviderUtil.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.common.junit4; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.common.junit4; import java.util.HashSet; import java.util.Iterator; @@ -40,11 +39,9 @@ * @author Qingzhou Luo * */ -public final class JUnit4ProviderUtil -{ - private JUnit4ProviderUtil() - { - throw new IllegalStateException( "Cannot instantiate." ); +public final class JUnit4ProviderUtil { + private JUnit4ProviderUtil() { + throw new IllegalStateException("Cannot instantiate."); } /** @@ -53,24 +50,20 @@ private JUnit4ProviderUtil() * @param allFailures the list of failures for a given test class * @return the list of descriptions */ - public static Set generateFailingTestDescriptions( List allFailures ) - { + public static Set generateFailingTestDescriptions(List allFailures) { Set failingTestDescriptions = new HashSet<>(); - for ( Failure failure : allFailures ) - { + for (Failure failure : allFailures) { Description description = failure.getDescription(); - if ( description.isTest() && !isFailureInsideJUnitItself( description ) ) - { - failingTestDescriptions.add( description ); + if (description.isTest() && !isFailureInsideJUnitItself(description)) { + failingTestDescriptions.add(description); } } return failingTestDescriptions; } - public static boolean isFailureInsideJUnitItself( Description failure ) - { - return TEST_MECHANISM.equals( failure ); + public static boolean isFailureInsideJUnitItself(Description failure) { + return TEST_MECHANISM.equals(failure); } /** @@ -78,34 +71,28 @@ public static boolean isFailureInsideJUnitItself( Description failure ) * @param description method(class) or method[#](class) or method[#whatever-literals](class) * @return method JUnit test method */ - public static ClassMethod toClassMethod( Description description ) - { - String clazz = extractClassName( description.getDisplayName() ); - if ( clazz == null || isInsaneJunitNullString( clazz ) ) - { + public static ClassMethod toClassMethod(Description description) { + String clazz = extractClassName(description.getDisplayName()); + if (clazz == null || isInsaneJunitNullString(clazz)) { // This can happen upon early failures (class instantiation error etc) Iterator it = description.getChildren().iterator(); - if ( it.hasNext() ) - { + if (it.hasNext()) { description = it.next(); - clazz = extractClassName( description.getDisplayName() ); + clazz = extractClassName(description.getDisplayName()); } - if ( clazz == null ) - { + if (clazz == null) { clazz = "Test Instantiation Error"; } } - String method = extractMethodName( description.getDisplayName() ); - return new ClassMethod( clazz, method ); + String method = extractMethodName(description.getDisplayName()); + return new ClassMethod(clazz, method); } - private static boolean isInsaneJunitNullString( String value ) - { - return "null".equals( value ); + private static boolean isInsaneJunitNullString(String value) { + return "null".equals(value); } - public static Filter createMatchAnyDescriptionFilter( Iterable descriptions ) - { - return new MatchDescriptions( descriptions ); + public static Filter createMatchAnyDescriptionFilter(Iterable descriptions) { + return new MatchDescriptions(descriptions); } } diff --git a/surefire-providers/common-junit4/src/main/java/org/apache/maven/surefire/common/junit4/JUnit4Reflector.java b/surefire-providers/common-junit4/src/main/java/org/apache/maven/surefire/common/junit4/JUnit4Reflector.java index 1274603468..ba919b30d6 100644 --- a/surefire-providers/common-junit4/src/main/java/org/apache/maven/surefire/common/junit4/JUnit4Reflector.java +++ b/surefire-providers/common-junit4/src/main/java/org/apache/maven/surefire/common/junit4/JUnit4Reflector.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.common.junit4; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,117 +16,99 @@ * specific language governing permissions and limitations * under the License. */ - -import org.junit.Ignore; -import org.junit.runner.Description; +package org.apache.maven.surefire.common.junit4; import java.lang.annotation.Annotation; import java.lang.reflect.Method; -import static org.apache.maven.surefire.api.util.ReflectionUtils.invokeMethodWithArray; +import org.junit.Ignore; +import org.junit.runner.Description; + import static org.apache.maven.surefire.api.util.ReflectionUtils.getMethod; +import static org.apache.maven.surefire.api.util.ReflectionUtils.invokeMethodWithArray; import static org.apache.maven.surefire.api.util.ReflectionUtils.tryGetMethod; /** * JUnit4 reflection helper * */ -public final class JUnit4Reflector -{ - private static final Class[] PARAMS = { Class.class }; +public final class JUnit4Reflector { + private static final Class[] PARAMS = {Class.class}; - private static final Object[] IGNORE_PARAMS = { Ignore.class }; + private static final Object[] IGNORE_PARAMS = {Ignore.class}; - private static final Class[] PARAMS_WITH_ANNOTATIONS = { String.class, Annotation[].class }; + private static final Class[] PARAMS_WITH_ANNOTATIONS = {String.class, Annotation[].class}; - private JUnit4Reflector() - { - throw new IllegalStateException( "not instantiable constructor" ); + private JUnit4Reflector() { + throw new IllegalStateException("not instantiable constructor"); } - public static Ignore getAnnotatedIgnore( Description d ) - { - Method getAnnotation = tryGetMethod( d.getClass(), "getAnnotation", PARAMS ); - return getAnnotation == null ? null : (Ignore) invokeMethodWithArray( d, getAnnotation, IGNORE_PARAMS ); + public static Ignore getAnnotatedIgnore(Description d) { + Method getAnnotation = tryGetMethod(d.getClass(), "getAnnotation", PARAMS); + return getAnnotation == null ? null : (Ignore) invokeMethodWithArray(d, getAnnotation, IGNORE_PARAMS); } - static String getAnnotatedIgnoreValue( Description description ) - { - final Ignore ignore = getAnnotatedIgnore( description ); + static String getAnnotatedIgnoreValue(Description description) { + final Ignore ignore = getAnnotatedIgnore(description); return ignore != null ? ignore.value() : null; } - public static Description createDescription( String description ) - { - try - { - return Description.createSuiteDescription( description ); - } - catch ( NoSuchMethodError e ) - { - Method method = getMethod( Description.class, "createSuiteDescription", PARAMS_WITH_ANNOTATIONS ); + public static Description createDescription(String description) { + try { + return Description.createSuiteDescription(description); + } catch (NoSuchMethodError e) { + Method method = getMethod(Description.class, "createSuiteDescription", PARAMS_WITH_ANNOTATIONS); // may throw exception probably with broken JUnit 4.x - return invokeMethodWithArray( null, method, description, new Annotation[0] ); + return invokeMethodWithArray(null, method, description, new Annotation[0]); } } - public static Description createDescription( String description, Annotation... annotations ) - { - Method method = tryGetMethod( Description.class, "createSuiteDescription", PARAMS_WITH_ANNOTATIONS ); + public static Description createDescription(String description, Annotation... annotations) { + Method method = tryGetMethod(Description.class, "createSuiteDescription", PARAMS_WITH_ANNOTATIONS); return method == null - ? Description.createSuiteDescription( description ) - : (Description) invokeMethodWithArray( null, method, description, annotations ); + ? Description.createSuiteDescription(description) + : (Description) invokeMethodWithArray(null, method, description, annotations); } - public static Ignore createIgnored( String value ) - { - return new IgnoredWithUserError( value ); + public static Ignore createIgnored(String value) { + return new IgnoredWithUserError(value); } - @SuppressWarnings( "ClassExplicitlyAnnotation" ) - private static class IgnoredWithUserError - implements Annotation, Ignore - { + @SuppressWarnings("ClassExplicitlyAnnotation") + private static class IgnoredWithUserError implements Annotation, Ignore { private final String value; - IgnoredWithUserError( String value ) - { + IgnoredWithUserError(String value) { this.value = value; } @Override - public String value() - { + public String value() { return value; } @Override - public Class annotationType() - { + public Class annotationType() { return Ignore.class; } @Override - public int hashCode() - { + public int hashCode() { return value == null ? 0 : value.hashCode(); } @Override - public boolean equals( Object obj ) - { - return obj instanceof Ignore && equalValue( ( Ignore ) obj ); + public boolean equals(Object obj) { + return obj instanceof Ignore && equalValue((Ignore) obj); } @Override - public String toString() - { - return String.format( "%s(%s)", Ignore.class, value ); + public String toString() { + return String.format("%s(%s)", Ignore.class, value); } - private boolean equalValue( Ignore ignore ) - { - return ignore != null && ignore.value().equals( value ); + private boolean equalValue(Ignore ignore) { + return ignore != null && ignore.value().equals(value); } } } diff --git a/surefire-providers/common-junit4/src/main/java/org/apache/maven/surefire/common/junit4/JUnit4RunListener.java b/surefire-providers/common-junit4/src/main/java/org/apache/maven/surefire/common/junit4/JUnit4RunListener.java index b9890acec7..09f7abc68b 100644 --- a/surefire-providers/common-junit4/src/main/java/org/apache/maven/surefire/common/junit4/JUnit4RunListener.java +++ b/surefire-providers/common-junit4/src/main/java/org/apache/maven/surefire/common/junit4/JUnit4RunListener.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.common.junit4; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.common.junit4; import org.apache.maven.plugin.surefire.log.api.ConsoleLogger; import org.apache.maven.surefire.api.report.OutputReportEntry; @@ -37,21 +36,18 @@ import org.junit.runner.notification.Failure; import org.junit.runner.notification.RunListener; -import static org.apache.maven.surefire.common.junit4.JUnit4ProviderUtil.isFailureInsideJUnitItself; -import static org.apache.maven.surefire.common.junit4.JUnit4ProviderUtil.toClassMethod; -import static org.apache.maven.surefire.common.junit4.JUnit4Reflector.getAnnotatedIgnoreValue; import static org.apache.maven.surefire.api.report.SimpleReportEntry.assumption; import static org.apache.maven.surefire.api.report.SimpleReportEntry.ignored; import static org.apache.maven.surefire.api.report.SimpleReportEntry.withException; +import static org.apache.maven.surefire.common.junit4.JUnit4ProviderUtil.isFailureInsideJUnitItself; +import static org.apache.maven.surefire.common.junit4.JUnit4ProviderUtil.toClassMethod; +import static org.apache.maven.surefire.common.junit4.JUnit4Reflector.getAnnotatedIgnoreValue; /** * RunListener for JUnit4, delegates to our own RunListener * */ -public class JUnit4RunListener - extends RunListener - implements TestOutputReceiver, RunModeSetter -{ +public class JUnit4RunListener extends RunListener implements TestOutputReceiver, RunModeSetter { protected final ClassMethodIndexer classMethodIndexer = new ClassMethodIndexer(); protected final TestReportListener reporter; private volatile RunMode runMode; @@ -70,24 +66,20 @@ public class JUnit4RunListener * * @param reporter the reporter to log testing events to */ - public JUnit4RunListener( TestReportListener reporter ) - { + public JUnit4RunListener(TestReportListener reporter) { this.reporter = reporter; } - public final ConsoleLogger getConsoleLogger() - { + public final ConsoleLogger getConsoleLogger() { return reporter; } @Override - public void setRunMode( RunMode runMode ) - { + public void setRunMode(RunMode runMode) { this.runMode = runMode; } - protected final RunMode getRunMode() - { + protected final RunMode getRunMode() { return runMode; } @@ -99,14 +91,12 @@ protected final RunMode getRunMode() * @see org.junit.runner.notification.RunListener#testIgnored(org.junit.runner.Description) */ @Override - public void testIgnored( Description description ) - throws Exception - { - String reason = getAnnotatedIgnoreValue( description ); - ClassMethod classMethod = toClassMethod( description ); - long testRunId = classMethodIndexer.indexClassMethod( classMethod.getClazz(), classMethod.getMethod() ); - reporter.testSkipped( ignored( runMode, testRunId, classMethod.getClazz(), null, - classMethod.getMethod(), null, reason ) ); + public void testIgnored(Description description) throws Exception { + String reason = getAnnotatedIgnoreValue(description); + ClassMethod classMethod = toClassMethod(description); + long testRunId = classMethodIndexer.indexClassMethod(classMethod.getClazz(), classMethod.getMethod()); + reporter.testSkipped( + ignored(runMode, testRunId, classMethod.getClazz(), null, classMethod.getMethod(), null, reason)); } /** @@ -115,15 +105,10 @@ public void testIgnored( Description description ) * @see org.junit.runner.notification.RunListener#testStarted(org.junit.runner.Description) */ @Override - public void testStarted( Description description ) - throws Exception - { - try - { - reporter.testStarting( createReportEntry( description ) ); - } - finally - { + public void testStarted(Description description) throws Exception { + try { + reporter.testStarting(createReportEntry(description)); + } finally { failureFlag.remove(); } } @@ -134,47 +119,41 @@ public void testStarted( Description description ) * @see org.junit.runner.notification.RunListener#testFailure(org.junit.runner.notification.Failure) */ @Override - @SuppressWarnings( { "ThrowableResultOfMethodCallIgnored" } ) - public void testFailure( Failure failure ) - throws Exception - { - try - { - StackTraceWriter stackTrace = createStackTraceWriter( failure ); - ClassMethod classMethod = toClassMethod( failure.getDescription() ); - long testRunId = classMethodIndexer.indexClassMethod( classMethod.getClazz(), classMethod.getMethod() ); - ReportEntry report = withException( runMode, testRunId, classMethod.getClazz(), null, - classMethod.getMethod(), null, stackTrace ); - - if ( failure.getException() instanceof AssertionError ) - { - reporter.testFailed( report ); + @SuppressWarnings({"ThrowableResultOfMethodCallIgnored"}) + public void testFailure(Failure failure) throws Exception { + try { + StackTraceWriter stackTrace = createStackTraceWriter(failure); + ClassMethod classMethod = toClassMethod(failure.getDescription()); + long testRunId = classMethodIndexer.indexClassMethod(classMethod.getClazz(), classMethod.getMethod()); + ReportEntry report = withException( + runMode, testRunId, classMethod.getClazz(), null, classMethod.getMethod(), null, stackTrace); + + if (failure.getException() instanceof AssertionError) { + reporter.testFailed(report); + } else { + reporter.testError(report); } - else - { - reporter.testError( report ); - } - } - finally - { - failureFlag.set( true ); + } finally { + failureFlag.set(true); } } - public void testAssumptionFailure( Failure failure ) - { - try - { + public void testAssumptionFailure(Failure failure) { + try { Description desc = failure.getDescription(); - ClassMethod classMethod = toClassMethod( desc ); - long testRunId = classMethodIndexer.indexClassMethod( classMethod.getClazz(), classMethod.getMethod() ); - ReportEntry report = assumption( runMode, testRunId, classMethod.getClazz(), null, - classMethod.getMethod(), null, failure.getMessage() ); - reporter.testAssumptionFailure( report ); - } - finally - { - failureFlag.set( true ); + ClassMethod classMethod = toClassMethod(desc); + long testRunId = classMethodIndexer.indexClassMethod(classMethod.getClazz(), classMethod.getMethod()); + ReportEntry report = assumption( + runMode, + testRunId, + classMethod.getClazz(), + null, + classMethod.getMethod(), + null, + failure.getMessage()); + reporter.testAssumptionFailure(report); + } finally { + failureFlag.set(true); } } @@ -184,54 +163,42 @@ public void testAssumptionFailure( Failure failure ) * @see org.junit.runner.notification.RunListener#testFinished(org.junit.runner.Description) */ @Override - public void testFinished( Description description ) - throws Exception - { + public void testFinished(Description description) throws Exception { Boolean failure = failureFlag.get(); - if ( failure == null ) - { - reporter.testSucceeded( createReportEntry( description ) ); + if (failure == null) { + reporter.testSucceeded(createReportEntry(description)); } } /** * Delegates to {@link org.apache.maven.surefire.api.report.RunListener#testExecutionSkippedByUser()}. */ - public void testExecutionSkippedByUser() - { + public void testExecutionSkippedByUser() { reporter.testExecutionSkippedByUser(); } - protected StackTraceWriter createStackTraceWriter( Failure failure ) - { - return new JUnit4StackTraceWriter( failure ); + protected StackTraceWriter createStackTraceWriter(Failure failure) { + return new JUnit4StackTraceWriter(failure); } - protected SimpleReportEntry createReportEntry( Description description ) - { - ClassMethod classMethod = toClassMethod( description ); - long testRunId = classMethodIndexer.indexClassMethod( classMethod.getClazz(), classMethod.getMethod() ); - return new SimpleReportEntry( runMode, testRunId, classMethod.getClazz(), null, - classMethod.getMethod(), null ); + protected SimpleReportEntry createReportEntry(Description description) { + ClassMethod classMethod = toClassMethod(description); + long testRunId = classMethodIndexer.indexClassMethod(classMethod.getClazz(), classMethod.getMethod()); + return new SimpleReportEntry(runMode, testRunId, classMethod.getClazz(), null, classMethod.getMethod(), null); } - public static void rethrowAnyTestMechanismFailures( Result run ) - throws TestSetFailedException - { - for ( Failure failure : run.getFailures() ) - { - if ( isFailureInsideJUnitItself( failure.getDescription() ) ) - { - throw new TestSetFailedException( failure.getTestHeader() + " :: " + failure.getMessage(), - failure.getException() ); + public static void rethrowAnyTestMechanismFailures(Result run) throws TestSetFailedException { + for (Failure failure : run.getFailures()) { + if (isFailureInsideJUnitItself(failure.getDescription())) { + throw new TestSetFailedException( + failure.getTestHeader() + " :: " + failure.getMessage(), failure.getException()); } } } @Override - public void writeTestOutput( OutputReportEntry reportEntry ) - { + public void writeTestOutput(OutputReportEntry reportEntry) { Long testRunId = classMethodIndexer.getLocalIndex(); - reporter.writeTestOutput( new TestOutputReportEntry( reportEntry, runMode, testRunId ) ); + reporter.writeTestOutput(new TestOutputReportEntry(reportEntry, runMode, testRunId)); } } diff --git a/surefire-providers/common-junit4/src/main/java/org/apache/maven/surefire/common/junit4/JUnit4RunListenerFactory.java b/surefire-providers/common-junit4/src/main/java/org/apache/maven/surefire/common/junit4/JUnit4RunListenerFactory.java index f1f54e076c..b0a74a4f79 100644 --- a/surefire-providers/common-junit4/src/main/java/org/apache/maven/surefire/common/junit4/JUnit4RunListenerFactory.java +++ b/surefire-providers/common-junit4/src/main/java/org/apache/maven/surefire/common/junit4/JUnit4RunListenerFactory.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.common.junit4; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,12 +16,12 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.common.junit4; import java.util.ArrayList; import java.util.List; import org.apache.maven.surefire.api.util.ReflectionUtils; - import org.junit.runner.notification.RunListener; import static org.apache.maven.surefire.shared.utils.StringUtils.isNotBlank; @@ -31,23 +29,17 @@ /** * @author Kristian Rosenvold */ -public class JUnit4RunListenerFactory -{ - public static List createCustomListeners( String listeners ) - { +public class JUnit4RunListenerFactory { + public static List createCustomListeners(String listeners) { List result = new ArrayList<>(); - if ( isNotBlank( listeners ) ) - { + if (isNotBlank(listeners)) { ClassLoader cl = Thread.currentThread().getContextClassLoader(); - for ( String listener : listeners.split( "," ) ) - { - if ( isNotBlank( listener ) ) - { - result.add( ReflectionUtils.instantiate( cl, listener, RunListener.class ) ); + for (String listener : listeners.split(",")) { + if (isNotBlank(listener)) { + result.add(ReflectionUtils.instantiate(cl, listener, RunListener.class)); } } } return result; } - } diff --git a/surefire-providers/common-junit4/src/main/java/org/apache/maven/surefire/common/junit4/JUnit4StackTraceWriter.java b/surefire-providers/common-junit4/src/main/java/org/apache/maven/surefire/common/junit4/JUnit4StackTraceWriter.java index 76a3b61ff2..e0a9c9de12 100644 --- a/surefire-providers/common-junit4/src/main/java/org/apache/maven/surefire/common/junit4/JUnit4StackTraceWriter.java +++ b/surefire-providers/common-junit4/src/main/java/org/apache/maven/surefire/common/junit4/JUnit4StackTraceWriter.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.common.junit4; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,11 +16,12 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.common.junit4; import org.apache.maven.surefire.api.report.SafeThrowable; -import org.apache.maven.surefire.report.SmartStackTraceParser; import org.apache.maven.surefire.api.report.StackTraceWriter; import org.apache.maven.surefire.api.util.internal.ClassMethod; +import org.apache.maven.surefire.report.SmartStackTraceParser; import org.junit.runner.notification.Failure; import static org.apache.maven.surefire.common.junit4.JUnit4ProviderUtil.toClassMethod; @@ -34,9 +33,7 @@ * * @author Karl M. Davis */ -public class JUnit4StackTraceWriter - implements StackTraceWriter -{ +public class JUnit4StackTraceWriter implements StackTraceWriter { private final Failure junitFailure; /** @@ -44,31 +41,26 @@ public class JUnit4StackTraceWriter * * @param junitFailure the {@link Failure} that this will be operating on */ - public JUnit4StackTraceWriter( Failure junitFailure ) - { + public JUnit4StackTraceWriter(Failure junitFailure) { this.junitFailure = junitFailure; } /* - * (non-Javadoc) - * - * @see org.apache.maven.surefire.report.StackTraceWriter#writeTraceToString() - */ + * (non-Javadoc) + * + * @see org.apache.maven.surefire.report.StackTraceWriter#writeTraceToString() + */ @Override - public String writeTraceToString() - { + public String writeTraceToString() { Throwable t = junitFailure.getException(); - if ( t != null ) - { + if (t != null) { String originalTrace = junitFailure.getTrace(); - if ( isMultiLineExceptionMessage( t ) ) - { + if (isMultiLineExceptionMessage(t)) { // SUREFIRE-986 - StringBuilder builder = new StringBuilder( originalTrace ); + StringBuilder builder = new StringBuilder(originalTrace); String exc = t.getClass().getName() + ": "; - if ( originalTrace.startsWith( exc ) ) - { - builder.insert( exc.length(), '\n' ); + if (originalTrace.startsWith(exc)) { + builder.insert(exc.length(), '\n'); } return builder.toString(); } @@ -78,13 +70,12 @@ public String writeTraceToString() } @Override - public String smartTrimmedStackTrace() - { + public String smartTrimmedStackTrace() { Throwable exception = junitFailure.getException(); - ClassMethod classMethod = toClassMethod( junitFailure.getDescription() ); + ClassMethod classMethod = toClassMethod(junitFailure.getDescription()); return exception == null - ? junitFailure.getMessage() - : new SmartStackTraceParser( classMethod.getClazz(), exception, classMethod.getMethod() ).getString(); + ? junitFailure.getMessage() + : new SmartStackTraceParser(classMethod.getClazz(), exception, classMethod.getMethod()).getString(); } /** @@ -93,17 +84,13 @@ public String smartTrimmedStackTrace() * @see StackTraceWriter#writeTrimmedTraceToString() */ @Override - public String writeTrimmedTraceToString() - { - String testClass = toClassMethod( junitFailure.getDescription() ).getClazz(); - try - { + public String writeTrimmedTraceToString() { + String testClass = toClassMethod(junitFailure.getDescription()).getClazz(); + try { Throwable e = junitFailure.getException(); - return stackTraceWithFocusOnClassAsString( e, testClass ); - } - catch ( Throwable t ) - { - return stackTraceWithFocusOnClassAsString( t, testClass ); + return stackTraceWithFocusOnClassAsString(e, testClass); + } catch (Throwable t) { + return stackTraceWithFocusOnClassAsString(t, testClass); } } @@ -113,30 +100,23 @@ public String writeTrimmedTraceToString() * @see StackTraceWriter#getThrowable() */ @Override - public SafeThrowable getThrowable() - { - return new SafeThrowable( junitFailure.getException() ); + public SafeThrowable getThrowable() { + return new SafeThrowable(junitFailure.getException()); } - private static boolean isMultiLineExceptionMessage( Throwable t ) - { + private static boolean isMultiLineExceptionMessage(Throwable t) { String msg = t.getLocalizedMessage(); - if ( msg != null ) - { + if (msg != null) { int countNewLines = 0; - for ( int i = 0, length = msg.length(); i < length; i++ ) - { - if ( msg.charAt( i ) == '\n' ) - { - if ( ++countNewLines == 2 ) - { + for (int i = 0, length = msg.length(); i < length; i++) { + if (msg.charAt(i) == '\n') { + if (++countNewLines == 2) { break; } } } - return countNewLines > 1 || countNewLines == 1 && !msg.trim().endsWith( "\n" ); + return countNewLines > 1 || countNewLines == 1 && !msg.trim().endsWith("\n"); } return false; } - } diff --git a/surefire-providers/common-junit4/src/main/java/org/apache/maven/surefire/common/junit4/JUnit4TestChecker.java b/surefire-providers/common-junit4/src/main/java/org/apache/maven/surefire/common/junit4/JUnit4TestChecker.java index f746cf6b26..88a1cd2ccc 100644 --- a/surefire-providers/common-junit4/src/main/java/org/apache/maven/surefire/common/junit4/JUnit4TestChecker.java +++ b/surefire-providers/common-junit4/src/main/java/org/apache/maven/surefire/common/junit4/JUnit4TestChecker.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.common.junit4; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,68 +16,58 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.common.junit4; import java.lang.annotation.Annotation; import java.lang.reflect.Method; + import org.apache.maven.surefire.api.filter.NonAbstractClassFilter; -import org.apache.maven.surefire.common.junit3.JUnit3TestChecker; import org.apache.maven.surefire.api.util.ScannerFilter; +import org.apache.maven.surefire.common.junit3.JUnit3TestChecker; import static org.apache.maven.surefire.api.util.ReflectionUtils.tryLoadClass; /** * @author Kristian Rosenvold */ -public class JUnit4TestChecker - implements ScannerFilter -{ +public class JUnit4TestChecker implements ScannerFilter { private final NonAbstractClassFilter nonAbstractClassFilter; private final Class runWith; private final JUnit3TestChecker jUnit3TestChecker; - - public JUnit4TestChecker( ClassLoader testClassLoader ) - { - jUnit3TestChecker = new JUnit3TestChecker( testClassLoader ); - runWith = tryLoadClass( testClassLoader, org.junit.runner.RunWith.class.getName() ); + public JUnit4TestChecker(ClassLoader testClassLoader) { + jUnit3TestChecker = new JUnit3TestChecker(testClassLoader); + runWith = tryLoadClass(testClassLoader, org.junit.runner.RunWith.class.getName()); nonAbstractClassFilter = new NonAbstractClassFilter(); } @Override - public boolean accept( Class testClass ) - { - return jUnit3TestChecker.accept( testClass ) || isValidJUnit4Test( testClass ); + public boolean accept(Class testClass) { + return jUnit3TestChecker.accept(testClass) || isValidJUnit4Test(testClass); } - @SuppressWarnings( { "unchecked" } ) - private boolean isValidJUnit4Test( Class testClass ) - { - if ( !nonAbstractClassFilter.accept( testClass ) ) - { + @SuppressWarnings({"unchecked"}) + private boolean isValidJUnit4Test(Class testClass) { + if (!nonAbstractClassFilter.accept(testClass)) { return false; } - if ( isRunWithPresentInClassLoader() ) - { - Annotation runWithAnnotation = testClass.getAnnotation( runWith ); - if ( runWithAnnotation != null ) - { + if (isRunWithPresentInClassLoader()) { + Annotation runWithAnnotation = testClass.getAnnotation(runWith); + if (runWithAnnotation != null) { return true; } } - return lookForTestAnnotatedMethods( testClass ); + return lookForTestAnnotatedMethods(testClass); } - private boolean lookForTestAnnotatedMethods( Class testClass ) - { + private boolean lookForTestAnnotatedMethods(Class testClass) { Class classToCheck = testClass; - while ( classToCheck != null ) - { - if ( checkforTestAnnotatedMethod( classToCheck ) ) - { + while (classToCheck != null) { + if (checkforTestAnnotatedMethod(classToCheck)) { return true; } classToCheck = classToCheck.getSuperclass(); @@ -87,14 +75,10 @@ private boolean lookForTestAnnotatedMethods( Class testClass ) return false; } - public boolean checkforTestAnnotatedMethod( Class testClass ) - { - for ( Method lMethod : testClass.getDeclaredMethods() ) - { - for ( Annotation lAnnotation : lMethod.getAnnotations() ) - { - if ( org.junit.Test.class.isAssignableFrom( lAnnotation.annotationType() ) ) - { + public boolean checkforTestAnnotatedMethod(Class testClass) { + for (Method lMethod : testClass.getDeclaredMethods()) { + for (Annotation lAnnotation : lMethod.getAnnotations()) { + if (org.junit.Test.class.isAssignableFrom(lAnnotation.annotationType())) { return true; } } @@ -102,8 +86,7 @@ public boolean checkforTestAnnotatedMethod( Class testClass ) return false; } - public boolean isRunWithPresentInClassLoader() - { + public boolean isRunWithPresentInClassLoader() { return runWith != null; } } diff --git a/surefire-providers/common-junit4/src/main/java/org/apache/maven/surefire/common/junit4/JUnitTestFailureListener.java b/surefire-providers/common-junit4/src/main/java/org/apache/maven/surefire/common/junit4/JUnitTestFailureListener.java index 203a888564..dc477d132b 100644 --- a/surefire-providers/common-junit4/src/main/java/org/apache/maven/surefire/common/junit4/JUnitTestFailureListener.java +++ b/surefire-providers/common-junit4/src/main/java/org/apache/maven/surefire/common/junit4/JUnitTestFailureListener.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.common.junit4; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,40 +16,34 @@ * specific language governing permissions and limitations * under the License. */ - -import org.junit.runner.notification.Failure; -import org.junit.runner.notification.RunListener; +package org.apache.maven.surefire.common.junit4; import java.util.ArrayList; import java.util.List; +import org.junit.runner.notification.Failure; +import org.junit.runner.notification.RunListener; + /** * Test listener to record all the failures during one run * * @author Qingzhou Luo */ -public class JUnitTestFailureListener - extends RunListener -{ +public class JUnitTestFailureListener extends RunListener { private final List allFailures = new ArrayList<>(); @Override - public void testFailure( Failure failure ) - throws Exception - { - if ( failure != null ) - { - allFailures.add( failure ); + public void testFailure(Failure failure) throws Exception { + if (failure != null) { + allFailures.add(failure); } } - public List getAllFailures() - { + public List getAllFailures() { return allFailures; } - public void reset() - { + public void reset() { allFailures.clear(); } } diff --git a/surefire-providers/common-junit4/src/main/java/org/apache/maven/surefire/common/junit4/MatchDescriptions.java b/surefire-providers/common-junit4/src/main/java/org/apache/maven/surefire/common/junit4/MatchDescriptions.java index 22fdd25220..78ec311246 100644 --- a/surefire-providers/common-junit4/src/main/java/org/apache/maven/surefire/common/junit4/MatchDescriptions.java +++ b/surefire-providers/common-junit4/src/main/java/org/apache/maven/surefire/common/junit4/MatchDescriptions.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.common.junit4; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,38 +16,32 @@ * specific language governing permissions and limitations * under the License. */ - -import org.junit.runner.Description; -import org.junit.runner.manipulation.Filter; +package org.apache.maven.surefire.common.junit4; import java.util.ArrayList; import java.util.List; +import org.junit.runner.Description; +import org.junit.runner.manipulation.Filter; + /** * Only run test methods in the given failure set. * * @author mpkorstanje */ -public final class MatchDescriptions - extends Filter -{ +public final class MatchDescriptions extends Filter { private final List filters = new ArrayList<>(); - public MatchDescriptions( Iterable descriptions ) - { - for ( Description description : descriptions ) - { - filters.add( matchDescription( description ) ); + public MatchDescriptions(Iterable descriptions) { + for (Description description : descriptions) { + filters.add(matchDescription(description)); } } @Override - public boolean shouldRun( Description description ) - { - for ( Filter filter : filters ) - { - if ( filter.shouldRun( description ) ) - { + public boolean shouldRun(Description description) { + for (Filter filter : filters) { + if (filter.shouldRun(description)) { return true; } } @@ -57,36 +49,27 @@ public boolean shouldRun( Description description ) } @Override - public String describe() - { - StringBuilder description = new StringBuilder( "Matching description " ); - for ( int i = 0; i < filters.size(); i++ ) - { - description.append( filters.get( i ).describe() ); - if ( i != filters.size() - 1 ) - { - description.append( " OR " ); + public String describe() { + StringBuilder description = new StringBuilder("Matching description "); + for (int i = 0; i < filters.size(); i++) { + description.append(filters.get(i).describe()); + if (i != filters.size() - 1) { + description.append(" OR "); } } return description.toString(); } - private static Filter matchDescription( final Description desiredDescription ) - { - return new Filter() - { + private static Filter matchDescription(final Description desiredDescription) { + return new Filter() { @Override - public boolean shouldRun( Description description ) - { - if ( description.isTest() ) - { - return desiredDescription.equals( description ); + public boolean shouldRun(Description description) { + if (description.isTest()) { + return desiredDescription.equals(description); } - for ( Description each : description.getChildren() ) - { - if ( shouldRun( each ) ) - { + for (Description each : description.getChildren()) { + if (shouldRun(each)) { return true; } } @@ -95,9 +78,8 @@ public boolean shouldRun( Description description ) } @Override - public String describe() - { - return String.format( "Method %s", desiredDescription.getDisplayName() ); + public String describe() { + return String.format("Method %s", desiredDescription.getDisplayName()); } }; } diff --git a/surefire-providers/common-junit4/src/main/java/org/apache/maven/surefire/common/junit4/Notifier.java b/surefire-providers/common-junit4/src/main/java/org/apache/maven/surefire/common/junit4/Notifier.java index 927df00bb0..e467304055 100644 --- a/surefire-providers/common-junit4/src/main/java/org/apache/maven/surefire/common/junit4/Notifier.java +++ b/surefire-providers/common-junit4/src/main/java/org/apache/maven/surefire/common/junit4/Notifier.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.common.junit4; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,12 +16,7 @@ * specific language governing permissions and limitations * under the License. */ - -import org.junit.runner.Description; -import org.junit.runner.notification.Failure; -import org.junit.runner.notification.RunListener; -import org.junit.runner.notification.RunNotifier; -import org.junit.runner.notification.StoppedByUserException; +package org.apache.maven.surefire.common.junit4; import java.util.ArrayList; import java.util.Collection; @@ -32,8 +25,14 @@ import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.atomic.AtomicInteger; -import static org.apache.maven.surefire.common.junit4.JUnit4ProviderUtil.toClassMethod; +import org.junit.runner.Description; +import org.junit.runner.notification.Failure; +import org.junit.runner.notification.RunListener; +import org.junit.runner.notification.RunNotifier; +import org.junit.runner.notification.StoppedByUserException; + import static org.apache.maven.surefire.api.util.internal.ConcurrencyUtils.runIfZeroCountDown; +import static org.apache.maven.surefire.common.junit4.JUnit4ProviderUtil.toClassMethod; /** * Extends {@link RunNotifier JUnit notifier}, @@ -43,9 +42,7 @@ * @author Tibor Digana (tibor17) * @since 2.19 */ -public class Notifier - extends RunNotifier -{ +public class Notifier extends RunNotifier { private final Collection listeners = new ArrayList<>(); private final Queue testClassNames = new ConcurrentLinkedQueue<>(); @@ -56,123 +53,101 @@ public class Notifier private volatile boolean failFast; - public Notifier( JUnit4RunListener reporter, int skipAfterFailureCount ) - { - addListener( reporter ); + public Notifier(JUnit4RunListener reporter, int skipAfterFailureCount) { + addListener(reporter); this.reporter = reporter; - this.skipAfterFailureCount = new AtomicInteger( skipAfterFailureCount ); + this.skipAfterFailureCount = new AtomicInteger(skipAfterFailureCount); } - private Notifier() - { + private Notifier() { reporter = null; skipAfterFailureCount = null; } - public static Notifier pureNotifier() - { - return new Notifier() - { + public static Notifier pureNotifier() { + return new Notifier() { @Override - public void asFailFast( @SuppressWarnings( { "unused", "checkstyle:hiddenfieldcheck" } ) boolean failFast ) - { - throw new UnsupportedOperationException( "pure notifier" ); + public void asFailFast(@SuppressWarnings({"unused", "checkstyle:hiddenfieldcheck"}) boolean failFast) { + throw new UnsupportedOperationException("pure notifier"); } }; } - public void asFailFast( boolean enableFailFast ) - { + public void asFailFast(boolean enableFailFast) { failFast = enableFailFast; } - public final boolean isFailFast() - { + public final boolean isFailFast() { return failFast; } @Override - @SuppressWarnings( "checkstyle:redundantthrowscheck" ) // checkstyle is wrong here, see super.fireTestStarted() - public final void fireTestStarted( Description description ) throws StoppedByUserException - { + @SuppressWarnings("checkstyle:redundantthrowscheck") // checkstyle is wrong here, see super.fireTestStarted() + public final void fireTestStarted(Description description) throws StoppedByUserException { // If fireTestStarted() throws exception (== skipped test), the class must not be removed from testClassNames. // Therefore this class will be removed only if test class started with some test method. - super.fireTestStarted( description ); - if ( !testClassNames.isEmpty() ) - { - testClassNames.remove( toClassMethod( description ).getClazz() ); + super.fireTestStarted(description); + if (!testClassNames.isEmpty()) { + testClassNames.remove(toClassMethod(description).getClazz()); } } @Override - public final void fireTestFailure( Failure failure ) - { - if ( failFast ) - { + public final void fireTestFailure(Failure failure) { + if (failFast) { fireStopEvent(); } - super.fireTestFailure( failure ); + super.fireTestFailure(failure); } @Override - public final void addListener( RunListener listener ) - { - listeners.add( listener ); - super.addListener( listener ); + public final void addListener(RunListener listener) { + listeners.add(listener); + super.addListener(listener); } - public final Notifier addListeners( Collection given ) - { - for ( RunListener listener : given ) - { - addListener( listener ); + public final Notifier addListeners(Collection given) { + for (RunListener listener : given) { + addListener(listener); } return this; } - @SuppressWarnings( "unused" ) - public final Notifier addListeners( RunListener... given ) - { - for ( RunListener listener : given ) - { - addListener( listener ); + @SuppressWarnings("unused") + public final Notifier addListeners(RunListener... given) { + for (RunListener listener : given) { + addListener(listener); } return this; } @Override - public final void removeListener( RunListener listener ) - { - listeners.remove( listener ); - super.removeListener( listener ); + public final void removeListener(RunListener listener) { + listeners.remove(listener); + super.removeListener(listener); } - public final void removeListeners() - { - for ( Iterator it = listeners.iterator(); it.hasNext(); ) - { + public final void removeListeners() { + for (Iterator it = listeners.iterator(); it.hasNext(); ) { RunListener listener = it.next(); it.remove(); - super.removeListener( listener ); + super.removeListener(listener); } } - public final Queue getRemainingTestClasses() - { + public final Queue getRemainingTestClasses() { return failFast ? testClassNames : null; } - public final void copyListenersTo( Notifier copyTo ) - { - copyTo.addListeners( listeners ); + public final void copyListenersTo(Notifier copyTo) { + copyTo.addListeners(listeners); } /** * Fire stop even to plugin process and/or call {@link org.junit.runner.notification.RunNotifier#pleaseStop()}. */ - private void fireStopEvent() - { - runIfZeroCountDown( this::pleaseStop, skipAfterFailureCount ); + private void fireStopEvent() { + runIfZeroCountDown(this::pleaseStop, skipAfterFailureCount); reporter.testExecutionSkippedByUser(); } } diff --git a/surefire-providers/common-junit4/src/test/java/org/apache/maven/surefire/common/junit4/JUnit4ProviderUtilTest.java b/surefire-providers/common-junit4/src/test/java/org/apache/maven/surefire/common/junit4/JUnit4ProviderUtilTest.java index 060c3d28c2..51199bbac1 100644 --- a/surefire-providers/common-junit4/src/test/java/org/apache/maven/surefire/common/junit4/JUnit4ProviderUtilTest.java +++ b/surefire-providers/common-junit4/src/test/java/org/apache/maven/surefire/common/junit4/JUnit4ProviderUtilTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.common.junit4; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,83 +16,72 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.common.junit4; + +import java.util.ArrayList; +import java.util.List; +import java.util.Set; import junit.framework.TestCase; import org.apache.maven.surefire.api.util.internal.ClassMethod; import org.junit.runner.Description; import org.junit.runner.notification.Failure; -import java.util.ArrayList; -import java.util.List; -import java.util.Set; - import static org.apache.maven.surefire.common.junit4.JUnit4ProviderUtil.generateFailingTestDescriptions; /** * @author Qingzhou Luo */ -public class JUnit4ProviderUtilTest - extends TestCase -{ - public void testGenerateFailingTestDescriptions() - { +public class JUnit4ProviderUtilTest extends TestCase { + public void testGenerateFailingTestDescriptions() { List failures = new ArrayList<>(); - Description test1Description = Description.createTestDescription( T1.class, "testOne" ); - Description test2Description = Description.createTestDescription( T1.class, "testTwo" ); - Description test3Description = Description.createTestDescription( T2.class, "testThree" ); - Description test4Description = Description.createTestDescription( T2.class, "testFour" ); - Description test5Description = Description.createSuiteDescription( "Test mechanism" ); + Description test1Description = Description.createTestDescription(T1.class, "testOne"); + Description test2Description = Description.createTestDescription(T1.class, "testTwo"); + Description test3Description = Description.createTestDescription(T2.class, "testThree"); + Description test4Description = Description.createTestDescription(T2.class, "testFour"); + Description test5Description = Description.createSuiteDescription("Test mechanism"); - failures.add( new Failure( test1Description, new AssertionError() ) ); - failures.add( new Failure( test2Description, new AssertionError() ) ); - failures.add( new Failure( test3Description, new RuntimeException() ) ); - failures.add( new Failure( test4Description, new AssertionError() ) ); - failures.add( new Failure( test5Description, new RuntimeException() ) ); + failures.add(new Failure(test1Description, new AssertionError())); + failures.add(new Failure(test2Description, new AssertionError())); + failures.add(new Failure(test3Description, new RuntimeException())); + failures.add(new Failure(test4Description, new AssertionError())); + failures.add(new Failure(test5Description, new RuntimeException())); - Set result = generateFailingTestDescriptions( failures ); + Set result = generateFailingTestDescriptions(failures); - assertEquals( 4, result.size() ); + assertEquals(4, result.size()); - assertTrue( result.contains( test1Description ) ); - assertTrue( result.contains( test2Description ) ); - assertTrue( result.contains( test3Description ) ); - assertTrue( result.contains( test4Description ) ); + assertTrue(result.contains(test1Description)); + assertTrue(result.contains(test2Description)); + assertTrue(result.contains(test3Description)); + assertTrue(result.contains(test4Description)); } - public void testIllegalTestDescriptionNegativeTest() - { - Description test = Description.createSuiteDescription( "someTestMethod" ); - ClassMethod classMethod = JUnit4ProviderUtil.toClassMethod( test ); - assertFalse( classMethod.isValidTest() ); + public void testIllegalTestDescriptionNegativeTest() { + Description test = Description.createSuiteDescription("someTestMethod"); + ClassMethod classMethod = JUnit4ProviderUtil.toClassMethod(test); + assertFalse(classMethod.isValidTest()); } - public void testOldJUnitParameterizedDescriptionParser() - { - Description test = Description.createTestDescription( T1.class, " \n testMethod[5] " ); - assertEquals( " \n testMethod[5] (" + T1.class.getName() + ")", test.getDisplayName() ); - ClassMethod classMethod = JUnit4ProviderUtil.toClassMethod( test ); - assertTrue( classMethod.isValidTest() ); - assertEquals( " \n testMethod[5] ", classMethod.getMethod() ); - assertEquals( T1.class.getName(), classMethod.getClazz() ); + public void testOldJUnitParameterizedDescriptionParser() { + Description test = Description.createTestDescription(T1.class, " \n testMethod[5] "); + assertEquals(" \n testMethod[5] (" + T1.class.getName() + ")", test.getDisplayName()); + ClassMethod classMethod = JUnit4ProviderUtil.toClassMethod(test); + assertTrue(classMethod.isValidTest()); + assertEquals(" \n testMethod[5] ", classMethod.getMethod()); + assertEquals(T1.class.getName(), classMethod.getClazz()); } - public void testNewJUnitParameterizedDescriptionParser() - { - Description test = Description.createTestDescription( T1.class, "flakyTest[3: (Test11); Test12; Test13;]" ); - ClassMethod classMethod = JUnit4ProviderUtil.toClassMethod( test ); - assertTrue( classMethod.isValidTest() ); - assertEquals( "flakyTest[3: (Test11); Test12; Test13;]", classMethod.getMethod() ); - assertEquals( T1.class.getName(), classMethod.getClazz() ); + public void testNewJUnitParameterizedDescriptionParser() { + Description test = Description.createTestDescription(T1.class, "flakyTest[3: (Test11); Test12; Test13;]"); + ClassMethod classMethod = JUnit4ProviderUtil.toClassMethod(test); + assertTrue(classMethod.isValidTest()); + assertEquals("flakyTest[3: (Test11); Test12; Test13;]", classMethod.getMethod()); + assertEquals(T1.class.getName(), classMethod.getClazz()); } - private static class T1 - { + private static class T1 {} - } - - private static class T2 - { - - } + private static class T2 {} } diff --git a/surefire-providers/common-junit4/src/test/java/org/apache/maven/surefire/common/junit4/JUnit4Reflector40Test.java b/surefire-providers/common-junit4/src/test/java/org/apache/maven/surefire/common/junit4/JUnit4Reflector40Test.java index 94c246171f..ad12f5d466 100644 --- a/surefire-providers/common-junit4/src/test/java/org/apache/maven/surefire/common/junit4/JUnit4Reflector40Test.java +++ b/surefire-providers/common-junit4/src/test/java/org/apache/maven/surefire/common/junit4/JUnit4Reflector40Test.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.common.junit4; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.common.junit4; import junit.framework.TestCase; import org.junit.Ignore; @@ -27,14 +26,11 @@ /** * @author Kristian Rosenvold */ -public class JUnit4Reflector40Test - extends TestCase -{ - public void testGetAnnotatedIgnore() - { - Description desc = Description.createTestDescription( IgnoreWithDescription.class, "testSomething2" ); - Ignore annotatedIgnore = JUnit4Reflector.getAnnotatedIgnore( desc ); - assertNull( annotatedIgnore ); +public class JUnit4Reflector40Test extends TestCase { + public void testGetAnnotatedIgnore() { + Description desc = Description.createTestDescription(IgnoreWithDescription.class, "testSomething2"); + Ignore annotatedIgnore = JUnit4Reflector.getAnnotatedIgnore(desc); + assertNull(annotatedIgnore); } private static final String REASON = "Ignorance is bliss"; @@ -42,43 +38,35 @@ public void testGetAnnotatedIgnore() /** * */ - public static class IgnoreWithDescription - { + public static class IgnoreWithDescription { @Test - @Ignore( REASON ) - public void testSomething2() - { - } + @Ignore(REASON) + public void testSomething2() {} } - public void testCreateIgnored() - { - Ignore ignore = JUnit4Reflector.createIgnored( "error" ); - assertNotNull( ignore ); - assertNotNull( ignore.value() ); - assertEquals( "error", ignore.value() ); + public void testCreateIgnored() { + Ignore ignore = JUnit4Reflector.createIgnored("error"); + assertNotNull(ignore); + assertNotNull(ignore.value()); + assertEquals("error", ignore.value()); } - public void testCreateDescription() - { - Ignore ignore = JUnit4Reflector.createIgnored( "error" ); - Description description = JUnit4Reflector.createDescription( "exception", ignore ); - assertEquals( "exception", description.getDisplayName() ); - assertEquals( "exception", description.toString() ); - assertEquals( 0, description.getChildren().size() ); + public void testCreateDescription() { + Ignore ignore = JUnit4Reflector.createIgnored("error"); + Description description = JUnit4Reflector.createDescription("exception", ignore); + assertEquals("exception", description.getDisplayName()); + assertEquals("exception", description.toString()); + assertEquals(0, description.getChildren().size()); // JUnit 4 description does not get annotations - Ignore annotatedIgnore = JUnit4Reflector.getAnnotatedIgnore( description ); - assertNull( annotatedIgnore ); + Ignore annotatedIgnore = JUnit4Reflector.getAnnotatedIgnore(description); + assertNull(annotatedIgnore); } - public void testCreatePureDescription() - { - Description description = JUnit4Reflector.createDescription( "exception" ); - assertEquals( "exception", description.getDisplayName() ); - assertEquals( "exception", description.toString() ); - assertEquals( 0, description.getChildren().size() ); + public void testCreatePureDescription() { + Description description = JUnit4Reflector.createDescription("exception"); + assertEquals("exception", description.getDisplayName()); + assertEquals("exception", description.toString()); + assertEquals(0, description.getChildren().size()); } } - - diff --git a/surefire-providers/common-junit4/src/test/java/org/apache/maven/surefire/common/junit4/JUnit4RunListenerTest.java b/surefire-providers/common-junit4/src/test/java/org/apache/maven/surefire/common/junit4/JUnit4RunListenerTest.java index 2e5aad9a1f..1d22b0d085 100644 --- a/surefire-providers/common-junit4/src/test/java/org/apache/maven/surefire/common/junit4/JUnit4RunListenerTest.java +++ b/surefire-providers/common-junit4/src/test/java/org/apache/maven/surefire/common/junit4/JUnit4RunListenerTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.common.junit4; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,12 +16,12 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.common.junit4; import java.util.concurrent.CountDownLatch; -import junit.framework.TestCase; - import junit.framework.Assert; +import junit.framework.TestCase; import org.apache.maven.surefire.api.util.internal.DaemonThreadFactory; import org.junit.Test; import org.junit.runner.Description; @@ -36,76 +34,60 @@ /** * @author Kristian Rosenvold */ -public class JUnit4RunListenerTest - extends TestCase -{ - public void testTestStarted() - { - RunListener jUnit4TestSetReporter = new JUnit4RunListener( new MockReporter() ); - Runner junitTestRunner = Request.classes( "abc", STest1.class, STest2.class ).getRunner(); +public class JUnit4RunListenerTest extends TestCase { + public void testTestStarted() { + RunListener jUnit4TestSetReporter = new JUnit4RunListener(new MockReporter()); + Runner junitTestRunner = + Request.classes("abc", STest1.class, STest2.class).getRunner(); RunNotifier runNotifier = new RunNotifier(); - runNotifier.addListener( jUnit4TestSetReporter ); - junitTestRunner.run( runNotifier ); + runNotifier.addListener(jUnit4TestSetReporter); + junitTestRunner.run(runNotifier); } - public void testParallelInvocations() - throws Exception - { + public void testParallelInvocations() throws Exception { final MockReporter reporter = new MockReporter(); - final RunListener jUnit4TestSetReporter = new JUnit4RunListener( reporter ); - final CountDownLatch countDownLatch = new CountDownLatch( 1 ); - final Description testSomething = Description.createTestDescription( STest1.class, "testSomething" ); - final Description testSomething2 = Description.createTestDescription( STest2.class, "testSomething2" ); + final RunListener jUnit4TestSetReporter = new JUnit4RunListener(reporter); + final CountDownLatch countDownLatch = new CountDownLatch(1); + final Description testSomething = Description.createTestDescription(STest1.class, "testSomething"); + final Description testSomething2 = Description.createTestDescription(STest2.class, "testSomething2"); - jUnit4TestSetReporter.testStarted( testSomething ); + jUnit4TestSetReporter.testStarted(testSomething); - DaemonThreadFactory.newDaemonThread( new Runnable() - { - @Override - public void run() - { - try - { - jUnit4TestSetReporter.testStarted( testSomething2 ); - jUnit4TestSetReporter.testFailure( new Failure( testSomething2, new AssertionError( "Fud" ) ) ); - jUnit4TestSetReporter.testFinished( testSomething2 ); - countDownLatch.countDown(); - } - catch ( Exception e ) - { - throw new RuntimeException( e ); - } - } - } ).start(); + DaemonThreadFactory.newDaemonThread(new Runnable() { + @Override + public void run() { + try { + jUnit4TestSetReporter.testStarted(testSomething2); + jUnit4TestSetReporter.testFailure(new Failure(testSomething2, new AssertionError("Fud"))); + jUnit4TestSetReporter.testFinished(testSomething2); + countDownLatch.countDown(); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + }) + .start(); countDownLatch.await(); - jUnit4TestSetReporter.testFinished( testSomething ); + jUnit4TestSetReporter.testFinished(testSomething); - Assert.assertEquals( "Failing tests", 1, reporter.getTestFailed() ); - Assert.assertEquals( "Succeeded tests", 1, reporter.getTestSucceeded() ); + Assert.assertEquals("Failing tests", 1, reporter.getTestFailed()); + Assert.assertEquals("Succeeded tests", 1, reporter.getTestSucceeded()); } /** * */ - public static class STest1 - { + public static class STest1 { @Test - public void testSomething() - { - - } + public void testSomething() {} } /** * */ - public static class STest2 - { + public static class STest2 { @Test - public void testSomething2() - { - - } + public void testSomething2() {} } } diff --git a/surefire-providers/common-junit4/src/test/java/org/apache/maven/surefire/common/junit4/MockReporter.java b/surefire-providers/common-junit4/src/test/java/org/apache/maven/surefire/common/junit4/MockReporter.java index bce301ca13..eb5baf092a 100644 --- a/surefire-providers/common-junit4/src/test/java/org/apache/maven/surefire/common/junit4/MockReporter.java +++ b/surefire-providers/common-junit4/src/test/java/org/apache/maven/surefire/common/junit4/MockReporter.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.common.junit4; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.common.junit4; import java.util.ArrayList; import java.util.List; @@ -31,9 +30,7 @@ /** * Internal tests use only. */ -final class MockReporter - implements TestReportListener -{ +final class MockReporter implements TestReportListener { private final List events = new ArrayList<>(); private static final String SET_STARTED = "SET_STARTED"; @@ -54,136 +51,97 @@ final class MockReporter private final AtomicInteger testError = new AtomicInteger(); - MockReporter() - { - } + MockReporter() {} @Override - public void testSetStarting( TestSetReportEntry report ) - { - events.add( SET_STARTED ); + public void testSetStarting(TestSetReportEntry report) { + events.add(SET_STARTED); } @Override - public void testSetCompleted( TestSetReportEntry report ) - { - events.add( SET_COMPLETED ); + public void testSetCompleted(TestSetReportEntry report) { + events.add(SET_COMPLETED); } @Override - public void testStarting( ReportEntry report ) - { - events.add( TEST_STARTED ); + public void testStarting(ReportEntry report) { + events.add(TEST_STARTED); } @Override - public void testSucceeded( ReportEntry report ) - { - events.add( TEST_COMPLETED ); + public void testSucceeded(ReportEntry report) { + events.add(TEST_COMPLETED); testSucceeded.incrementAndGet(); } @Override - public void testSkipped( ReportEntry report ) - { - events.add( TEST_SKIPPED ); + public void testSkipped(ReportEntry report) { + events.add(TEST_SKIPPED); testIgnored.incrementAndGet(); } @Override - public void testExecutionSkippedByUser() - { - } + public void testExecutionSkippedByUser() {} - public int getTestSucceeded() - { + public int getTestSucceeded() { return testSucceeded.get(); } - public int getTestFailed() - { + public int getTestFailed() { return testFailed.get(); } @Override - public void testError( ReportEntry report ) - { + public void testError(ReportEntry report) { testError.incrementAndGet(); } @Override - public void testFailed( ReportEntry report ) - { + public void testFailed(ReportEntry report) { testFailed.incrementAndGet(); } @Override - public void testAssumptionFailure( ReportEntry report ) - { - } + public void testAssumptionFailure(ReportEntry report) {} @Override - public void writeTestOutput( TestOutputReportEntry reportEntry ) - { - } + public void writeTestOutput(TestOutputReportEntry reportEntry) {} @Override - public boolean isDebugEnabled() - { + public boolean isDebugEnabled() { return false; } @Override - public void debug( String message ) - { - - } + public void debug(String message) {} @Override - public boolean isInfoEnabled() - { + public boolean isInfoEnabled() { return false; } @Override - public void info( String message ) - { - - } + public void info(String message) {} @Override - public boolean isWarnEnabled() - { + public boolean isWarnEnabled() { return false; } @Override - public void warning( String message ) - { - - } + public void warning(String message) {} @Override - public boolean isErrorEnabled() - { + public boolean isErrorEnabled() { return false; } @Override - public void error( String message ) - { - - } + public void error(String message) {} @Override - public void error( String message, Throwable t ) - { - - } + public void error(String message, Throwable t) {} @Override - public void error( Throwable t ) - { - - } + public void error(Throwable t) {} } diff --git a/surefire-providers/common-junit4/src/test/java/org/apache/maven/surefire/junit4/JUnit4TestCheckerTest.java b/surefire-providers/common-junit4/src/test/java/org/apache/maven/surefire/junit4/JUnit4TestCheckerTest.java index 07f90ab120..23a9c6673c 100644 --- a/surefire-providers/common-junit4/src/test/java/org/apache/maven/surefire/junit4/JUnit4TestCheckerTest.java +++ b/surefire-providers/common-junit4/src/test/java/org/apache/maven/surefire/junit4/JUnit4TestCheckerTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.junit4; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,14 +16,15 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.junit4; import java.util.Collections; import java.util.Set; -import org.apache.maven.surefire.common.junit4.JUnit4TestChecker; -import org.apache.maven.surefire.api.testset.TestSetFailedException; import junit.framework.TestCase; import junit.framework.TestResult; +import org.apache.maven.surefire.api.testset.TestSetFailedException; +import org.apache.maven.surefire.common.junit4.JUnit4TestChecker; import org.junit.Test; import org.junit.internal.runners.InitializationError; import org.junit.runner.Description; @@ -37,109 +36,81 @@ /** * @author Kristian Rosenvold */ -public class JUnit4TestCheckerTest - extends TestCase -{ - private final JUnit4TestChecker jUnit4TestChecker = new JUnit4TestChecker( this.getClass().getClassLoader() ); +public class JUnit4TestCheckerTest extends TestCase { + private final JUnit4TestChecker jUnit4TestChecker = + new JUnit4TestChecker(this.getClass().getClassLoader()); - public void testValidJunit4Annotated() - throws TestSetFailedException - { - assertTrue( jUnit4TestChecker.accept( JUnit4TestCheckerTest.class ) ); + public void testValidJunit4Annotated() throws TestSetFailedException { + assertTrue(jUnit4TestChecker.accept(JUnit4TestCheckerTest.class)); } - public void testValidJunit4itsAJunit3Test() - throws TestSetFailedException - { - assertTrue( jUnit4TestChecker.accept( AlsoValid.class ) ); + public void testValidJunit4itsAJunit3Test() throws TestSetFailedException { + assertTrue(jUnit4TestChecker.accept(AlsoValid.class)); } - public void testValidJunitSubclassWithoutOwnTestmethods() - throws TestSetFailedException - { - assertTrue( jUnit4TestChecker.accept( SubClassWithoutOwnTestMethods.class ) ); + public void testValidJunitSubclassWithoutOwnTestmethods() throws TestSetFailedException { + assertTrue(jUnit4TestChecker.accept(SubClassWithoutOwnTestMethods.class)); } - public void testValidSuite() - throws TestSetFailedException - { - assertTrue( jUnit4TestChecker.accept( SuiteValid1.class ) ); + public void testValidSuite() throws TestSetFailedException { + assertTrue(jUnit4TestChecker.accept(SuiteValid1.class)); } - public void testValidCustomSuite() - throws TestSetFailedException - { - assertTrue( jUnit4TestChecker.accept( SuiteValid2.class ) ); + public void testValidCustomSuite() throws TestSetFailedException { + assertTrue(jUnit4TestChecker.accept(SuiteValid2.class)); } - public void testValidCustomRunner() - throws TestSetFailedException - { - assertTrue( jUnit4TestChecker.accept( SuiteValidCustomRunner.class ) ); + public void testValidCustomRunner() throws TestSetFailedException { + assertTrue(jUnit4TestChecker.accept(SuiteValidCustomRunner.class)); } - public void testInvalidTest() - throws TestSetFailedException - { - assertFalse( jUnit4TestChecker.accept( NotValidTest.class ) ); + public void testInvalidTest() throws TestSetFailedException { + assertFalse(jUnit4TestChecker.accept(NotValidTest.class)); } - public void testDontAcceptAbstractClasses() - { - assertFalse( jUnit4TestChecker.accept( BaseClassWithTest.class ) ); + public void testDontAcceptAbstractClasses() { + assertFalse(jUnit4TestChecker.accept(BaseClassWithTest.class)); } - public void testSuiteOnlyTest() - { - assertTrue( jUnit4TestChecker.accept( SuiteOnlyTest.class ) ); + public void testSuiteOnlyTest() { + assertTrue(jUnit4TestChecker.accept(SuiteOnlyTest.class)); } - public void testCustomSuiteOnlyTest() - { - assertTrue( jUnit4TestChecker.accept( CustomSuiteOnlyTest.class ) ); + public void testCustomSuiteOnlyTest() { + assertTrue(jUnit4TestChecker.accept(CustomSuiteOnlyTest.class)); } - public void testInnerClassNotAutomaticallyTc() - { - assertTrue( jUnit4TestChecker.accept( NestedTC.class ) ); - assertFalse( jUnit4TestChecker.accept( NestedTC.Inner.class ) ); + public void testInnerClassNotAutomaticallyTc() { + assertTrue(jUnit4TestChecker.accept(NestedTC.class)); + assertFalse(jUnit4TestChecker.accept(NestedTC.Inner.class)); } - public void testCannotLoadRunWithAnnotation() - throws Exception - { + public void testCannotLoadRunWithAnnotation() throws Exception { Class testClass = SimpleJUnit4TestClass.class; ClassLoader testClassLoader = testClass.getClassLoader(); // Emulate an OSGi classloader which filters on package level. // Use a classloader which can only load classes in package org.junit, // e.g. org.junit.Test, but no classes from other packages, // in particular org.junit.runner.RunWith can't be loaded - Set visiblePackages = Collections.singleton( "org.junit" ); + Set visiblePackages = Collections.singleton("org.junit"); PackageFilteringClassLoader filteringTestClassloader = - new PackageFilteringClassLoader( testClassLoader, visiblePackages ); - JUnit4TestChecker checker = new JUnit4TestChecker( filteringTestClassloader ); - assertTrue( checker.accept( testClass ) ); + new PackageFilteringClassLoader(testClassLoader, visiblePackages); + JUnit4TestChecker checker = new JUnit4TestChecker(filteringTestClassloader); + assertTrue(checker.accept(testClass)); } /** * */ - public static class AlsoValid - extends TestCase - { - public void testSomething() - { - - } + public static class AlsoValid extends TestCase { + public void testSomething() {} } /** * */ - public static class SuiteOnlyTest - { - public static junit.framework.Test suite() - { + public static class SuiteOnlyTest { + public static junit.framework.Test suite() { return null; } } @@ -147,10 +118,8 @@ public static junit.framework.Test suite() /** * */ - public static class CustomSuiteOnlyTest - { - public static MySuite2 suite() - { + public static class CustomSuiteOnlyTest { + public static MySuite2 suite() { return null; } } @@ -158,130 +127,86 @@ public static MySuite2 suite() /** * */ - public static class MySuite2 - implements junit.framework.Test - { + public static class MySuite2 implements junit.framework.Test { @Override - public int countTestCases() - { + public int countTestCases() { return 0; } @Override - public void run( TestResult testResult ) - { - } + public void run(TestResult testResult) {} } /** * */ - @SuppressWarnings( { "UnusedDeclaration" } ) - public static class NotValidTest - { - public void testSomething() - { - } + @SuppressWarnings({"UnusedDeclaration"}) + public static class NotValidTest { + public void testSomething() {} } /** * */ - public abstract static class BaseClassWithTest - { + public abstract static class BaseClassWithTest { @Test - public void weAreAlsoATest() - { - } + public void weAreAlsoATest() {} } /** * */ - public static class SubClassWithoutOwnTestMethods - extends BaseClassWithTest - { - } + public static class SubClassWithoutOwnTestMethods extends BaseClassWithTest {} /** * */ - @RunWith( Suite.class ) - public static class SuiteValid1 - { - public void testSomething() - { - - } + @RunWith(Suite.class) + public static class SuiteValid1 { + public void testSomething() {} } - class CustomRunner - extends Runner - { + class CustomRunner extends Runner { @Override - public Description getDescription() - { - return Description.createSuiteDescription( "CustomRunner" ); + public Description getDescription() { + return Description.createSuiteDescription("CustomRunner"); } @Override - public void run( RunNotifier runNotifier ) - { - } + public void run(RunNotifier runNotifier) {} } /** * */ - @RunWith( CustomRunner.class ) - public static class SuiteValidCustomRunner - { - public void testSomething() - { - - } + @RunWith(CustomRunner.class) + public static class SuiteValidCustomRunner { + public void testSomething() {} } - /** * */ - @RunWith( MySuite.class ) - public static class SuiteValid2 - { - public void testSomething() - { - - } + @RunWith(MySuite.class) + public static class SuiteValid2 { + public void testSomething() {} } /** * */ - public static class SimpleJUnit4TestClass - { + public static class SimpleJUnit4TestClass { @Test - public void testMethod() - { - } + public void testMethod() {} } - class MySuite - extends Suite - { - MySuite( Class klass ) - throws InitializationError - { - super( klass ); + class MySuite extends Suite { + MySuite(Class klass) throws InitializationError { + super(klass); } } - class NestedTC - extends TestCase - { - public class Inner - { - - } + class NestedTC extends TestCase { + public class Inner {} } } diff --git a/surefire-providers/common-junit4/src/test/java/org/apache/maven/surefire/junit4/PackageFilteringClassLoader.java b/surefire-providers/common-junit4/src/test/java/org/apache/maven/surefire/junit4/PackageFilteringClassLoader.java index 68c4434bb8..8e5e54fd47 100644 --- a/surefire-providers/common-junit4/src/test/java/org/apache/maven/surefire/junit4/PackageFilteringClassLoader.java +++ b/surefire-providers/common-junit4/src/test/java/org/apache/maven/surefire/junit4/PackageFilteringClassLoader.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.junit4; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,44 +16,35 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.junit4; import java.util.Set; /** * Emulate an OSGi classloader which only loads packages that have been imported via Import-Package MANIFEST header. */ -public class PackageFilteringClassLoader - extends ClassLoader -{ +public class PackageFilteringClassLoader extends ClassLoader { private ClassLoader wrapped; private Set visiblePackages; - public PackageFilteringClassLoader( ClassLoader wrapped, Set visiblePackages ) - { + public PackageFilteringClassLoader(ClassLoader wrapped, Set visiblePackages) { this.wrapped = wrapped; this.visiblePackages = visiblePackages; } @Override - public Class loadClass( String className ) - throws ClassNotFoundException - { + public Class loadClass(String className) throws ClassNotFoundException { String packageName = ""; - int lastDot = className.lastIndexOf( '.' ); - if ( lastDot != -1 ) - { - packageName = className.substring( 0, lastDot ); + int lastDot = className.lastIndexOf('.'); + if (lastDot != -1) { + packageName = className.substring(0, lastDot); } - if ( visiblePackages.contains( packageName ) ) - { - return wrapped.loadClass( className ); - } - else - { - throw new ClassNotFoundException( className ); + if (visiblePackages.contains(packageName)) { + return wrapped.loadClass(className); + } else { + throw new ClassNotFoundException(className); } } - } diff --git a/surefire-providers/common-junit48/pom.xml b/surefire-providers/common-junit48/pom.xml index 42124ce818..00e89008ed 100644 --- a/surefire-providers/common-junit48/pom.xml +++ b/surefire-providers/common-junit48/pom.xml @@ -1,3 +1,4 @@ + - - 4.0.0 - - - org.apache.maven.surefire - surefire-providers - 3.0.0-M10-SNAPSHOT - + 4.0.0 - common-junit48 + + org.apache.maven.surefire + surefire-providers + 3.0.0-M10-SNAPSHOT + - Shared JUnit48 Provider Code - Shared JUnit48 Provider Code - - - - junit - junit - 4.8.1 - provided - - - org.apache.maven.surefire - common-junit4 - ${project.version} - - - org.apache.maven.surefire - surefire-grouper - ${project.version} - - + common-junit48 - - - - org.jacoco - jacoco-maven-plugin - - - jacoco-agent - - prepare-agent - - - - - jacoco.agent - - - - maven-dependency-plugin - - - junit-4.11 - process-test-sources - - copy - - - ${project.build.directory}/endorsed-test - false - - - junit - junit - 4.11 - jar - - - - - - test - process-test-sources - - copy - - - ${project.build.directory}/endorsed-test - false - - - junit - junit - 4.12 - jar - - - - - - - - maven-surefire-plugin - - - default-test - test - - test - - - - **/JUnit4SuiteTest.java - - - - - junit-4.11 - test - - test - - - GroupMatcherCategoryFilterPreJUnit412Test$JUnit4SuiteTest - - junit:junit - - - ${project.build.directory}/endorsed-test/junit-4.11.jar - - - - - junit-4.12 - test - - test - - - GroupMatcherCategoryFilterTest$JUnit4SuiteTest - - junit:junit - - - ${project.build.directory}/endorsed-test/junit-4.12.jar - - - - - - ${jvm.args.tests} ${jacoco.agent} - - - - org.apache.maven.surefire - surefire-shadefire - 3.0.0-M7 - - - - - + Shared JUnit48 Provider Code + Shared JUnit48 Provider Code surefire-3.0.0-M8 + + + + junit + junit + 4.8.1 + provided + + + org.apache.maven.surefire + common-junit4 + ${project.version} + + + org.apache.maven.surefire + surefire-grouper + ${project.version} + + + + + + + org.jacoco + jacoco-maven-plugin + + jacoco.agent + + + + jacoco-agent + + prepare-agent + + + + + + maven-dependency-plugin + + + junit-4.11 + + copy + + process-test-sources + + ${project.build.directory}/endorsed-test + false + + + junit + junit + 4.11 + jar + + + + + + test + + copy + + process-test-sources + + ${project.build.directory}/endorsed-test + false + + + junit + junit + 4.12 + jar + + + + + + + + maven-surefire-plugin + + ${jvm.args.tests} ${jacoco.agent} + + + + org.apache.maven.surefire + surefire-shadefire + 3.0.0-M7 + + + + + + default-test + + test + + test + + + **/JUnit4SuiteTest.java + + + + + junit-4.11 + + test + + test + + GroupMatcherCategoryFilterPreJUnit412Test$JUnit4SuiteTest + + junit:junit + + + ${project.build.directory}/endorsed-test/junit-4.11.jar + + + + + junit-4.12 + + test + + test + + GroupMatcherCategoryFilterTest$JUnit4SuiteTest + + junit:junit + + + ${project.build.directory}/endorsed-test/junit-4.12.jar + + + + + + + diff --git a/surefire-providers/common-junit48/src/main/java/org/apache/maven/surefire/common/junit48/AndFilter.java b/surefire-providers/common-junit48/src/main/java/org/apache/maven/surefire/common/junit48/AndFilter.java index 2890895f45..48a119b256 100644 --- a/surefire-providers/common-junit48/src/main/java/org/apache/maven/surefire/common/junit48/AndFilter.java +++ b/surefire-providers/common-junit48/src/main/java/org/apache/maven/surefire/common/junit48/AndFilter.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.common.junit48; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,27 +16,22 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.common.junit48; import org.junit.runner.Description; import org.junit.runner.manipulation.Filter; -final class AndFilter - extends Filter -{ +final class AndFilter extends Filter { private final Filter[] filters; - AndFilter( Filter... filters ) - { + AndFilter(Filter... filters) { this.filters = filters; } @Override - public boolean shouldRun( Description description ) - { - for ( Filter filter : filters ) - { - if ( !filter.shouldRun( description ) ) - { + public boolean shouldRun(Description description) { + for (Filter filter : filters) { + if (!filter.shouldRun(description)) { return false; } } @@ -46,15 +39,12 @@ public boolean shouldRun( Description description ) } @Override - public String describe() - { + public String describe() { StringBuilder description = new StringBuilder(); - for ( int i = 0; i < filters.length; i++ ) - { - description.append( filters[i].describe() ); - if ( i != filters.length - 1 ) - { - description.append( " AND " ); + for (int i = 0; i < filters.length; i++) { + description.append(filters[i].describe()); + if (i != filters.length - 1) { + description.append(" AND "); } } return description.toString(); diff --git a/surefire-providers/common-junit48/src/main/java/org/apache/maven/surefire/common/junit48/CombinedCategoryFilter.java b/surefire-providers/common-junit48/src/main/java/org/apache/maven/surefire/common/junit48/CombinedCategoryFilter.java index aefc2080ca..075426b1b6 100644 --- a/surefire-providers/common-junit48/src/main/java/org/apache/maven/surefire/common/junit48/CombinedCategoryFilter.java +++ b/surefire-providers/common-junit48/src/main/java/org/apache/maven/surefire/common/junit48/CombinedCategoryFilter.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.common.junit48; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,50 +16,41 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.common.junit48; + +import java.util.Collection; import org.junit.runner.Description; import org.junit.runner.manipulation.Filter; -import java.util.Collection; - -final class CombinedCategoryFilter - extends Filter -{ +final class CombinedCategoryFilter extends Filter { private final Collection includedFilters; private final Collection excludedFilters; - CombinedCategoryFilter( Collection includedFilters, Collection excludedFilters ) - { + CombinedCategoryFilter(Collection includedFilters, Collection excludedFilters) { this.includedFilters = includedFilters; this.excludedFilters = excludedFilters; } @Override - public boolean shouldRun( Description description ) - { - return ( includedFilters.isEmpty() || anyFilterMatchesDescription( includedFilters, description ) ) - && ( excludedFilters.isEmpty() || allFiltersMatchDescription( excludedFilters, description ) ); + public boolean shouldRun(Description description) { + return (includedFilters.isEmpty() || anyFilterMatchesDescription(includedFilters, description)) + && (excludedFilters.isEmpty() || allFiltersMatchDescription(excludedFilters, description)); } - private boolean anyFilterMatchesDescription( Collection filters, Description description ) - { - for ( Filter f : filters ) - { - if ( f.shouldRun( description ) ) - { + private boolean anyFilterMatchesDescription(Collection filters, Description description) { + for (Filter f : filters) { + if (f.shouldRun(description)) { return true; } } return false; } - private boolean allFiltersMatchDescription( Collection filters, Description description ) - { - for ( Filter f : filters ) - { - if ( !f.shouldRun( description ) ) - { + private boolean allFiltersMatchDescription(Collection filters, Description description) { + for (Filter f : filters) { + if (!f.shouldRun(description)) { return false; } } @@ -69,41 +58,34 @@ private boolean allFiltersMatchDescription( Collection filters, Descript } @Override - public String describe() - { + public String describe() { StringBuilder sb = new StringBuilder(); - if ( !includedFilters.isEmpty() ) - { - sb.append( "(" ); - sb.append( joinFilters( includedFilters, " OR " ) ); - sb.append( ")" ); - if ( !excludedFilters.isEmpty() ) - { - sb.append( " AND " ); + if (!includedFilters.isEmpty()) { + sb.append("("); + sb.append(joinFilters(includedFilters, " OR ")); + sb.append(")"); + if (!excludedFilters.isEmpty()) { + sb.append(" AND "); } } - if ( !excludedFilters.isEmpty() ) - { - sb.append( "NOT (" ); - sb.append( joinFilters( includedFilters, " OR " ) ); - sb.append( ")" ); + if (!excludedFilters.isEmpty()) { + sb.append("NOT ("); + sb.append(joinFilters(includedFilters, " OR ")); + sb.append(")"); } return sb.toString(); } - private String joinFilters( Collection filters, String sep ) - { + private String joinFilters(Collection filters, String sep) { boolean isFirst = true; StringBuilder sb = new StringBuilder(); - for ( Filter f : filters ) - { - if ( !isFirst ) - { - sb.append( sep ); + for (Filter f : filters) { + if (!isFirst) { + sb.append(sep); } - sb.append( f.describe() ); + sb.append(f.describe()); isFirst = false; } return sb.toString(); diff --git a/surefire-providers/common-junit48/src/main/java/org/apache/maven/surefire/common/junit48/FilterFactory.java b/surefire-providers/common-junit48/src/main/java/org/apache/maven/surefire/common/junit48/FilterFactory.java index c532404e51..45d21b7513 100644 --- a/surefire-providers/common-junit48/src/main/java/org/apache/maven/surefire/common/junit48/FilterFactory.java +++ b/surefire-providers/common-junit48/src/main/java/org/apache/maven/surefire/common/junit48/FilterFactory.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.common.junit48; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,18 +16,19 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.common.junit48; + +import java.util.Map; import org.apache.maven.surefire.api.booter.ProviderParameterNames; +import org.apache.maven.surefire.api.testset.TestListResolver; import org.apache.maven.surefire.common.junit4.JUnit4ProviderUtil; import org.apache.maven.surefire.group.match.GroupMatcher; import org.apache.maven.surefire.group.parse.GroupMatcherParser; import org.apache.maven.surefire.group.parse.ParseException; -import org.apache.maven.surefire.api.testset.TestListResolver; import org.junit.runner.Description; import org.junit.runner.manipulation.Filter; -import java.util.Map; - import static org.apache.maven.surefire.api.booter.ProviderParameterNames.TESTNG_EXCLUDEDGROUPS_PROP; import static org.apache.maven.surefire.api.booter.ProviderParameterNames.TESTNG_GROUPS_PROP; import static org.apache.maven.surefire.shared.utils.StringUtils.isNotBlank; @@ -37,12 +36,10 @@ /** * @author Todd Lipcon */ -public class FilterFactory -{ +public class FilterFactory { private final ClassLoader testClassLoader; - public FilterFactory( ClassLoader testClassLoader ) - { + public FilterFactory(ClassLoader testClassLoader) { this.testClassLoader = testClassLoader; } @@ -51,11 +48,10 @@ public FilterFactory( ClassLoader testClassLoader ) * {@link ProviderParameterNames#TESTNG_GROUPS_PROP} and/or * {@link ProviderParameterNames#TESTNG_EXCLUDEDGROUPS_PROP} exists. */ - public boolean canCreateGroupFilter( Map providerProperties ) - { - String groups = providerProperties.get( TESTNG_GROUPS_PROP ); - String excludedGroups = providerProperties.get( TESTNG_EXCLUDEDGROUPS_PROP ); - return isNotBlank( groups ) || isNotBlank( excludedGroups ); + public boolean canCreateGroupFilter(Map providerProperties) { + String groups = providerProperties.get(TESTNG_GROUPS_PROP); + String excludedGroups = providerProperties.get(TESTNG_EXCLUDEDGROUPS_PROP); + return isNotBlank(groups) || isNotBlank(excludedGroups); } /** @@ -63,70 +59,55 @@ public boolean canCreateGroupFilter( Map providerProperties ) * {@link ProviderParameterNames#TESTNG_GROUPS_PROP} and/or * {@link ProviderParameterNames#TESTNG_EXCLUDEDGROUPS_PROP}. */ - public Filter createGroupFilter( Map providerProperties ) - { - String groups = providerProperties.get( TESTNG_GROUPS_PROP ); + public Filter createGroupFilter(Map providerProperties) { + String groups = providerProperties.get(TESTNG_GROUPS_PROP); GroupMatcher included = null; - if ( isNotBlank( groups ) ) - { - try - { - included = new GroupMatcherParser( groups ).parse(); - } - catch ( ParseException e ) - { + if (isNotBlank(groups)) { + try { + included = new GroupMatcherParser(groups).parse(); + } catch (ParseException e) { throw new IllegalArgumentException( - "Invalid group expression: '" + groups + "'. Reason: " + e.getMessage(), e ); + "Invalid group expression: '" + groups + "'. Reason: " + e.getMessage(), e); } } - String excludedGroups = providerProperties.get( TESTNG_EXCLUDEDGROUPS_PROP ); + String excludedGroups = providerProperties.get(TESTNG_EXCLUDEDGROUPS_PROP); GroupMatcher excluded = null; - if ( isNotBlank( excludedGroups ) ) - { - try - { - excluded = new GroupMatcherParser( excludedGroups ).parse(); - } - catch ( ParseException e ) - { + if (isNotBlank(excludedGroups)) { + try { + excluded = new GroupMatcherParser(excludedGroups).parse(); + } catch (ParseException e) { throw new IllegalArgumentException( - "Invalid group expression: '" + excludedGroups + "'. Reason: " + e.getMessage(), e ); + "Invalid group expression: '" + excludedGroups + "'. Reason: " + e.getMessage(), e); } } - if ( included != null && testClassLoader != null ) - { - included.loadGroupClasses( testClassLoader ); + if (included != null && testClassLoader != null) { + included.loadGroupClasses(testClassLoader); } - if ( excluded != null && testClassLoader != null ) - { - excluded.loadGroupClasses( testClassLoader ); + if (excluded != null && testClassLoader != null) { + excluded.loadGroupClasses(testClassLoader); } - return new GroupMatcherCategoryFilter( included, excluded ); + return new GroupMatcherCategoryFilter(included, excluded); } - public Filter createMethodFilter( String requestedTestMethod ) - { - return new MethodFilter( requestedTestMethod ); + public Filter createMethodFilter(String requestedTestMethod) { + return new MethodFilter(requestedTestMethod); } - public Filter createMethodFilter( TestListResolver resolver ) - { - return new MethodFilter( resolver ); + public Filter createMethodFilter(TestListResolver resolver) { + return new MethodFilter(resolver); } - public Filter createMatchAnyDescriptionFilter( Iterable descriptions ) - { - return JUnit4ProviderUtil.createMatchAnyDescriptionFilter( descriptions ); + public Filter createMatchAnyDescriptionFilter(Iterable descriptions) { + return JUnit4ProviderUtil.createMatchAnyDescriptionFilter(descriptions); } - public Filter and( Filter filter1, Filter filter2 ) - { - return new AndFilter( filter1, filter2 ); + public Filter and(Filter filter1, Filter filter2) { + return new AndFilter(filter1, filter2); } } diff --git a/surefire-providers/common-junit48/src/main/java/org/apache/maven/surefire/common/junit48/GroupMatcherCategoryFilter.java b/surefire-providers/common-junit48/src/main/java/org/apache/maven/surefire/common/junit48/GroupMatcherCategoryFilter.java index 287d3272de..956c7aa01a 100644 --- a/surefire-providers/common-junit48/src/main/java/org/apache/maven/surefire/common/junit48/GroupMatcherCategoryFilter.java +++ b/surefire-providers/common-junit48/src/main/java/org/apache/maven/surefire/common/junit48/GroupMatcherCategoryFilter.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.common.junit48; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,12 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.common.junit48; + +import java.lang.annotation.Inherited; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.Set; import org.apache.maven.surefire.group.match.AndGroupMatcher; import org.apache.maven.surefire.group.match.GroupMatcher; @@ -26,151 +30,116 @@ import org.junit.runner.Description; import org.junit.runner.manipulation.Filter; -import java.lang.annotation.Inherited; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.Set; - import static java.util.Collections.addAll; import static org.junit.runner.Description.createSuiteDescription; -final class GroupMatcherCategoryFilter extends Filter -{ +final class GroupMatcherCategoryFilter extends Filter { /** * Only traverse the tree if @Category annotation is inherited (since junit 4.12). */ - private static final boolean IS_CATEGORY_INHERITED = Category.class.isAnnotationPresent( Inherited.class ); + private static final boolean IS_CATEGORY_INHERITED = Category.class.isAnnotationPresent(Inherited.class); private final AndGroupMatcher matcher; - GroupMatcherCategoryFilter( GroupMatcher included, GroupMatcher excluded ) - { - GroupMatcher invertedExclude = excluded == null ? null : new InverseGroupMatcher( excluded ); - if ( included != null || invertedExclude != null ) - { + GroupMatcherCategoryFilter(GroupMatcher included, GroupMatcher excluded) { + GroupMatcher invertedExclude = excluded == null ? null : new InverseGroupMatcher(excluded); + if (included != null || invertedExclude != null) { matcher = new AndGroupMatcher(); - if ( included != null ) - { - matcher.addMatcher( included ); + if (included != null) { + matcher.addMatcher(included); } - if ( invertedExclude != null ) - { - matcher.addMatcher( invertedExclude ); + if (invertedExclude != null) { + matcher.addMatcher(invertedExclude); } - } - else - { + } else { matcher = null; } } @Override - public boolean shouldRun( Description description ) - { - if ( invalidTestClass( description ) ) - { - return shouldRun( description, null, null ); + public boolean shouldRun(Description description) { + if (invalidTestClass(description)) { + return shouldRun(description, null, null); } - if ( describesTestClass( description ) ) // is a test class + if (describesTestClass(description)) // is a test class { Class testClass = description.getTestClass(); - return shouldRun( description, null, testClass ); - } - else + return shouldRun(description, null, testClass); + } else // is a test method { Class testClass = description.getTestClass(); - return shouldRun( description, createSuiteDescription( testClass ), testClass ); + return shouldRun(description, createSuiteDescription(testClass), testClass); } } - private boolean describesTestClass( Description description ) - { + private boolean describesTestClass(Description description) { String methodName = description.getMethodName(); // Description parser in Junit 4.8 can return "null" String. - return methodName == null || methodName.equals( "null" ); + return methodName == null || methodName.equals("null"); } - private boolean invalidTestClass( Description description ) - { + private boolean invalidTestClass(Description description) { return description.getTestClass() == null; } - private static void findSuperclassCategories( Set> cats, Class clazz ) - { - if ( IS_CATEGORY_INHERITED && hasSuperclass( clazz ) ) - { - Category cat = clazz.getSuperclass().getAnnotation( Category.class ); - if ( cat != null ) - { + private static void findSuperclassCategories(Set> cats, Class clazz) { + if (IS_CATEGORY_INHERITED && hasSuperclass(clazz)) { + Category cat = clazz.getSuperclass().getAnnotation(Category.class); + if (cat != null) { // Found categories in current superclass - addAll( cats, cat.value() ); + addAll(cats, cat.value()); } // Search the hierarchy - findSuperclassCategories( cats, clazz.getSuperclass() ); + findSuperclassCategories(cats, clazz.getSuperclass()); } } - private static boolean hasSuperclass( Class clazz ) - { + private static boolean hasSuperclass(Class clazz) { return clazz != null && clazz.getSuperclass() != null; } - private boolean shouldRun( Description description, Description parent, Class parentClass ) - { - if ( matcher == null ) - { + private boolean shouldRun(Description description, Description parent, Class parentClass) { + if (matcher == null) { return true; - } - else - { + } else { Set> cats = new HashSet<>(); - Category cat = description.getAnnotation( Category.class ); - if ( cat != null ) - { + Category cat = description.getAnnotation(Category.class); + if (cat != null) { // Found categories in current description - addAll( cats, cat.value() ); + addAll(cats, cat.value()); } - if ( parent != null ) - { - cat = parent.getAnnotation( Category.class ); - if ( cat != null ) - { + if (parent != null) { + cat = parent.getAnnotation(Category.class); + if (cat != null) { // Found categories in current parent - addAll( cats, cat.value() ); + addAll(cats, cat.value()); } } - if ( parentClass != null ) - { - findSuperclassCategories( cats, parentClass ); + if (parentClass != null) { + findSuperclassCategories(cats, parentClass); } Class testClass = description.getTestClass(); - if ( testClass != null ) - { - cat = testClass.getAnnotation( Category.class ); - if ( cat != null ) - { + if (testClass != null) { + cat = testClass.getAnnotation(Category.class); + if (cat != null) { // Found categories in current testClass - addAll( cats, cat.value() ); + addAll(cats, cat.value()); } } - cats.remove( null ); - boolean result = matcher.enabled( cats.toArray( new Class[cats.size()] ) ); + cats.remove(null); + boolean result = matcher.enabled(cats.toArray(new Class[cats.size()])); - if ( !result ) - { + if (!result) { ArrayList children = description.getChildren(); - if ( children != null ) - { - for ( Description child : children ) - { - if ( shouldRun( child, description, null ) ) - { + if (children != null) { + for (Description child : children) { + if (shouldRun(child, description, null)) { result = true; break; } @@ -183,8 +152,7 @@ private boolean shouldRun( Description description, Description parent, Class } @Override - public String describe() - { + public String describe() { return matcher == null ? "ANY" : matcher.toString(); } } diff --git a/surefire-providers/common-junit48/src/main/java/org/apache/maven/surefire/common/junit48/InvertedFilter.java b/surefire-providers/common-junit48/src/main/java/org/apache/maven/surefire/common/junit48/InvertedFilter.java index 1ce0b3c62a..e9021e0fca 100644 --- a/surefire-providers/common-junit48/src/main/java/org/apache/maven/surefire/common/junit48/InvertedFilter.java +++ b/surefire-providers/common-junit48/src/main/java/org/apache/maven/surefire/common/junit48/InvertedFilter.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.common.junit48; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,29 +16,25 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.common.junit48; import org.junit.runner.Description; import org.junit.runner.manipulation.Filter; -final class InvertedFilter - extends Filter -{ +final class InvertedFilter extends Filter { private final Filter filter; - InvertedFilter( Filter filter ) - { + InvertedFilter(Filter filter) { this.filter = filter; } @Override - public boolean shouldRun( Description description ) - { - return !filter.shouldRun( description ); + public boolean shouldRun(Description description) { + return !filter.shouldRun(description); } @Override - public String describe() - { + public String describe() { return filter.describe(); } } diff --git a/surefire-providers/common-junit48/src/main/java/org/apache/maven/surefire/common/junit48/JUnit48Reflector.java b/surefire-providers/common-junit48/src/main/java/org/apache/maven/surefire/common/junit48/JUnit48Reflector.java index 3d57455810..8749f15f54 100644 --- a/surefire-providers/common-junit48/src/main/java/org/apache/maven/surefire/common/junit48/JUnit48Reflector.java +++ b/surefire-providers/common-junit48/src/main/java/org/apache/maven/surefire/common/junit48/JUnit48Reflector.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.common.junit48; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,14 +16,14 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.common.junit48; import static org.apache.maven.surefire.api.util.ReflectionUtils.tryLoadClass; /** * @author Kristian Rosenvold */ -public final class JUnit48Reflector -{ +public final class JUnit48Reflector { private static final String CATEGORIES = "org.junit.experimental.categories.Categories"; private static final String CATEGORY = "org.junit.experimental.categories.Category"; @@ -34,20 +32,18 @@ public final class JUnit48Reflector private final Class category; - public JUnit48Reflector( ClassLoader testClassLoader ) - { - categories = tryLoadClass( testClassLoader, CATEGORIES ); - category = tryLoadClass( testClassLoader, CATEGORY ); + public JUnit48Reflector(ClassLoader testClassLoader) { + categories = tryLoadClass(testClassLoader, CATEGORIES); + category = tryLoadClass(testClassLoader, CATEGORY); } - public boolean isJUnit48Available() - { + public boolean isJUnit48Available() { return categories != null; } - boolean isCategoryAnnotationPresent( Class clazz ) - { - return clazz != null && category != null - && ( clazz.getAnnotation( category ) != null || isCategoryAnnotationPresent( clazz.getSuperclass() ) ); + boolean isCategoryAnnotationPresent(Class clazz) { + return clazz != null + && category != null + && (clazz.getAnnotation(category) != null || isCategoryAnnotationPresent(clazz.getSuperclass())); } } diff --git a/surefire-providers/common-junit48/src/main/java/org/apache/maven/surefire/common/junit48/JUnit48TestChecker.java b/surefire-providers/common-junit48/src/main/java/org/apache/maven/surefire/common/junit48/JUnit48TestChecker.java index 67b2d17e6a..324eb876aa 100644 --- a/surefire-providers/common-junit48/src/main/java/org/apache/maven/surefire/common/junit48/JUnit48TestChecker.java +++ b/surefire-providers/common-junit48/src/main/java/org/apache/maven/surefire/common/junit48/JUnit48TestChecker.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.common.junit48; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,56 +16,48 @@ * specific language governing permissions and limitations * under the License. */ - +package org.apache.maven.surefire.common.junit48; import org.apache.maven.surefire.api.filter.NonAbstractClassFilter; -import org.apache.maven.surefire.common.junit4.JUnit4TestChecker; import org.apache.maven.surefire.api.util.ScannerFilter; +import org.apache.maven.surefire.common.junit4.JUnit4TestChecker; import org.junit.experimental.runners.Enclosed; - /** * Looks for additional junit48-like features * @author Geoff Denning * @author Kristian Rosenvold */ -public class JUnit48TestChecker - implements ScannerFilter -{ +public class JUnit48TestChecker implements ScannerFilter { private final NonAbstractClassFilter nonAbstractClassFilter; private final JUnit4TestChecker jUnit4TestChecker; - - public JUnit48TestChecker( ClassLoader testClassLoader ) - { - this.jUnit4TestChecker = new JUnit4TestChecker( testClassLoader ); + public JUnit48TestChecker(ClassLoader testClassLoader) { + this.jUnit4TestChecker = new JUnit4TestChecker(testClassLoader); this.nonAbstractClassFilter = new NonAbstractClassFilter(); } @Override - public boolean accept( Class testClass ) - { - return jUnit4TestChecker.accept( testClass ) || isAbstractWithEnclosedRunner( testClass ); + public boolean accept(Class testClass) { + return jUnit4TestChecker.accept(testClass) || isAbstractWithEnclosedRunner(testClass); } - @SuppressWarnings( { "unchecked" } ) - private boolean isAbstractWithEnclosedRunner( Class testClass ) - { + @SuppressWarnings({"unchecked"}) + private boolean isAbstractWithEnclosedRunner(Class testClass) { return jUnit4TestChecker.isRunWithPresentInClassLoader() - && isAbstract( testClass ) - && isRunWithEnclosedRunner( testClass ); + && isAbstract(testClass) + && isRunWithEnclosedRunner(testClass); } - private boolean isRunWithEnclosedRunner( Class testClass ) - { - @SuppressWarnings( "unchecked" ) org.junit.runner.RunWith runWithAnnotation = - (org.junit.runner.RunWith) testClass.getAnnotation( org.junit.runner.RunWith.class ); - return ( runWithAnnotation != null && Enclosed.class.equals( runWithAnnotation.value() ) ); + private boolean isRunWithEnclosedRunner(Class testClass) { + @SuppressWarnings("unchecked") + org.junit.runner.RunWith runWithAnnotation = + (org.junit.runner.RunWith) testClass.getAnnotation(org.junit.runner.RunWith.class); + return (runWithAnnotation != null && Enclosed.class.equals(runWithAnnotation.value())); } - private boolean isAbstract( Class testClass ) - { - return !nonAbstractClassFilter.accept( testClass ); + private boolean isAbstract(Class testClass) { + return !nonAbstractClassFilter.accept(testClass); } } diff --git a/surefire-providers/common-junit48/src/main/java/org/apache/maven/surefire/common/junit48/MethodFilter.java b/surefire-providers/common-junit48/src/main/java/org/apache/maven/surefire/common/junit48/MethodFilter.java index 5d158ba7f3..c2e6181c95 100644 --- a/surefire-providers/common-junit48/src/main/java/org/apache/maven/surefire/common/junit48/MethodFilter.java +++ b/surefire-providers/common-junit48/src/main/java/org/apache/maven/surefire/common/junit48/MethodFilter.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.common.junit48; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,57 +16,44 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.common.junit48; + +import java.util.Collection; +import java.util.LinkedHashSet; import org.apache.maven.surefire.api.testset.ResolvedTest; import org.apache.maven.surefire.api.testset.TestListResolver; import org.junit.runner.Description; import org.junit.runner.manipulation.Filter; -import java.util.Collection; -import java.util.LinkedHashSet; - -final class MethodFilter - extends Filter -{ +final class MethodFilter extends Filter { private final CombinedCategoryFilter combinedFilter; - MethodFilter( String requestString ) - { - this( new TestListResolver( requestString ) ); + MethodFilter(String requestString) { + this(new TestListResolver(requestString)); } - MethodFilter( TestListResolver testResolver ) - { + MethodFilter(TestListResolver testResolver) { Collection includedFilters = new LinkedHashSet<>(); Collection excludedFilters = new LinkedHashSet<>(); - for ( ResolvedTest test : testResolver.getIncludedPatterns() ) - { - includedFilters.add( new RequestedTest( test, true ) ); + for (ResolvedTest test : testResolver.getIncludedPatterns()) { + includedFilters.add(new RequestedTest(test, true)); } - for ( ResolvedTest test : testResolver.getExcludedPatterns() ) - { - excludedFilters.add( new RequestedTest( test, false ) ); + for (ResolvedTest test : testResolver.getExcludedPatterns()) { + excludedFilters.add(new RequestedTest(test, false)); } - combinedFilter = new CombinedCategoryFilter( includedFilters, excludedFilters ); + combinedFilter = new CombinedCategoryFilter(includedFilters, excludedFilters); } @Override - public boolean shouldRun( Description description ) - { - if ( description.isEmpty() ) - { + public boolean shouldRun(Description description) { + if (description.isEmpty()) { return false; - } - else if ( description.isTest() ) - { - return combinedFilter.shouldRun( description ); - } - else - { - for ( Description o : description.getChildren() ) - { - if ( combinedFilter.shouldRun( o ) || shouldRun( o ) ) - { + } else if (description.isTest()) { + return combinedFilter.shouldRun(description); + } else { + for (Description o : description.getChildren()) { + if (combinedFilter.shouldRun(o) || shouldRun(o)) { return true; } } @@ -77,8 +62,7 @@ else if ( description.isTest() ) } @Override - public String describe() - { + public String describe() { return combinedFilter.describe(); } } diff --git a/surefire-providers/common-junit48/src/main/java/org/apache/maven/surefire/common/junit48/OrFilter.java b/surefire-providers/common-junit48/src/main/java/org/apache/maven/surefire/common/junit48/OrFilter.java index 0b9feabd01..b11528ae0f 100644 --- a/surefire-providers/common-junit48/src/main/java/org/apache/maven/surefire/common/junit48/OrFilter.java +++ b/surefire-providers/common-junit48/src/main/java/org/apache/maven/surefire/common/junit48/OrFilter.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.common.junit48; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,27 +16,22 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.common.junit48; import org.junit.runner.Description; import org.junit.runner.manipulation.Filter; -final class OrFilter - extends Filter -{ +final class OrFilter extends Filter { private final Filter[] filters; - OrFilter( Filter[] filters ) - { + OrFilter(Filter[] filters) { this.filters = filters; } @Override - public boolean shouldRun( Description description ) - { - for ( Filter filter : filters ) - { - if ( filter.shouldRun( description ) ) - { + public boolean shouldRun(Description description) { + for (Filter filter : filters) { + if (filter.shouldRun(description)) { return true; } } @@ -46,15 +39,12 @@ public boolean shouldRun( Description description ) } @Override - public String describe() - { + public String describe() { StringBuilder description = new StringBuilder(); - for ( int i = 0; i < filters.length; i++ ) - { - description.append( filters[i].describe() ); - if ( i != filters.length - 1 ) - { - description.append( " OR " ); + for (int i = 0; i < filters.length; i++) { + description.append(filters[i].describe()); + if (i != filters.length - 1) { + description.append(" OR "); } } return description.toString(); diff --git a/surefire-providers/common-junit48/src/main/java/org/apache/maven/surefire/common/junit48/RequestedTest.java b/surefire-providers/common-junit48/src/main/java/org/apache/maven/surefire/common/junit48/RequestedTest.java index 0d481d1641..e2f788691d 100644 --- a/surefire-providers/common-junit48/src/main/java/org/apache/maven/surefire/common/junit48/RequestedTest.java +++ b/surefire-providers/common-junit48/src/main/java/org/apache/maven/surefire/common/junit48/RequestedTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.common.junit48; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,69 +16,58 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.common.junit48; import org.apache.maven.surefire.api.testset.ResolvedTest; import org.junit.runner.Description; import org.junit.runner.manipulation.Filter; -final class RequestedTest - extends Filter -{ +final class RequestedTest extends Filter { private static final String CLASS_FILE_EXTENSION = ".class"; private final ResolvedTest test; private final boolean isPositiveFilter; - RequestedTest( ResolvedTest test, boolean isPositiveFilter ) - { + RequestedTest(ResolvedTest test, boolean isPositiveFilter) { this.test = test; this.isPositiveFilter = isPositiveFilter; } @Override - public boolean shouldRun( Description description ) - { + public boolean shouldRun(Description description) { Class realTestClass = description.getTestClass(); String methodName = description.getMethodName(); - if ( realTestClass == null && methodName == null ) - { + if (realTestClass == null && methodName == null) { return true; - } - else - { - String testClass = classFile( realTestClass ); + } else { + String testClass = classFile(realTestClass); return isPositiveFilter - ? test.matchAsInclusive( testClass, methodName ) - : !test.matchAsExclusive( testClass, methodName ); + ? test.matchAsInclusive(testClass, methodName) + : !test.matchAsExclusive(testClass, methodName); } } @Override - public String describe() - { + public String describe() { String description = test.toString(); return description.isEmpty() ? "*" : description; } @Override - public boolean equals( Object o ) - { - return this == o || o != null && getClass() == o.getClass() && equals( (RequestedTest) o ); + public boolean equals(Object o) { + return this == o || o != null && getClass() == o.getClass() && equals((RequestedTest) o); } - private boolean equals( RequestedTest o ) - { - return isPositiveFilter == o.isPositiveFilter && test.equals( o.test ); + private boolean equals(RequestedTest o) { + return isPositiveFilter == o.isPositiveFilter && test.equals(o.test); } @Override - public int hashCode() - { + public int hashCode() { return test.hashCode(); } - private String classFile( Class realTestClass ) - { - return realTestClass == null ? null : realTestClass.getName().replace( '.', '/' ) + CLASS_FILE_EXTENSION; + private String classFile(Class realTestClass) { + return realTestClass == null ? null : realTestClass.getName().replace('.', '/') + CLASS_FILE_EXTENSION; } } diff --git a/surefire-providers/common-junit48/src/test/java/org/apache/maven/surefire/common/junit48/FilterFactoryTest.java b/surefire-providers/common-junit48/src/test/java/org/apache/maven/surefire/common/junit48/FilterFactoryTest.java index a69d870078..ddb772ae68 100644 --- a/surefire-providers/common-junit48/src/test/java/org/apache/maven/surefire/common/junit48/FilterFactoryTest.java +++ b/surefire-providers/common-junit48/src/test/java/org/apache/maven/surefire/common/junit48/FilterFactoryTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.common.junit48; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,11 +16,17 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.common.junit48; + +import java.io.File; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; -import org.apache.maven.surefire.shared.utils.io.MatchPatterns; -import org.apache.maven.surefire.common.junit48.tests.pt.PT; import org.apache.maven.surefire.api.testset.ResolvedTest; import org.apache.maven.surefire.api.testset.TestListResolver; +import org.apache.maven.surefire.common.junit48.tests.pt.PT; +import org.apache.maven.surefire.shared.utils.io.MatchPatterns; import org.junit.Test; import org.junit.runner.Description; import org.junit.runner.JUnitCore; @@ -31,1042 +35,947 @@ import org.junit.runner.RunWith; import org.junit.runner.manipulation.Filter; -import java.io.File; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; - -import static org.junit.runner.Description.createSuiteDescription; -import static org.junit.runner.Description.createTestDescription; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; +import static org.junit.runner.Description.createSuiteDescription; +import static org.junit.runner.Description.createTestDescription; /** * */ -@SuppressWarnings( "checkstyle:constantname" ) -public class FilterFactoryTest -{ +@SuppressWarnings("checkstyle:constantname") +public class FilterFactoryTest { /** * */ - @RunWith( org.junit.runners.Suite.class ) - @org.junit.runners.Suite.SuiteClasses( { FirstClass.class, SecondClass.class } ) - public static class Suite - { - - } + @RunWith(org.junit.runners.Suite.class) + @org.junit.runners.Suite.SuiteClasses({FirstClass.class, SecondClass.class}) + public static class Suite {} /** * */ - public static class FirstClass - { + public static class FirstClass { @Test - public void testMethod() - { - //System.out.println( "FirstClass#testMethod" ); + public void testMethod() { + // System.out.println( "FirstClass#testMethod" ); } @Test - public void secondTestMethod() - { - //System.out.println( "FirstClass#secondTestMethod" ); + public void secondTestMethod() { + // System.out.println( "FirstClass#secondTestMethod" ); } @Test - public void otherMethod() - { - //System.out.println( "FirstClass#otherMethod" ); + public void otherMethod() { + // System.out.println( "FirstClass#otherMethod" ); } } /** * */ - public static class SecondClass - { + public static class SecondClass { @Test - public void testMethod() - { - //System.out.println( "SecondClass#testMethod" ); + public void testMethod() { + // System.out.println( "SecondClass#testMethod" ); } @Test - public void secondTestMethod() - { - //System.out.println( "SecondClass#secondTestMethod" ); + public void secondTestMethod() { + // System.out.println( "SecondClass#secondTestMethod" ); } } /** * */ - public static class ThirdClass - { + public static class ThirdClass { @Test - public void testMethod() - { - //System.out.println( "ThirdClass#testMethod" ); + public void testMethod() { + // System.out.println( "ThirdClass#testMethod" ); } @Test - public void secondTestMethod() - { - //System.out.println( "ThirdClass#secondTestMethod" ); + public void secondTestMethod() { + // System.out.println( "ThirdClass#secondTestMethod" ); } } - private static final Description testMethod = createTestDescription( FirstClass.class, "testMethod" ); + private static final Description testMethod = createTestDescription(FirstClass.class, "testMethod"); - private static final Description secondTestMethod = createTestDescription( FirstClass.class, "secondTestMethod" ); + private static final Description secondTestMethod = createTestDescription(FirstClass.class, "secondTestMethod"); - private static final Description otherMethod = createTestDescription( FirstClass.class, "otherMethod" ); + private static final Description otherMethod = createTestDescription(FirstClass.class, "otherMethod"); - private static final Description testMethodInSecondClass = createTestDescription( SecondClass.class, "testMethod" ); + private static final Description testMethodInSecondClass = createTestDescription(SecondClass.class, "testMethod"); private static final Description secondTestMethodInSecondClass = - createTestDescription( SecondClass.class, "secondTestMethod" ); - - private static final String firstClassName = FirstClass.class.getName().replace( '.', '/' ); - - private static final String secondClassName = SecondClass.class.getName().replace( '.', '/' ); - - private static final String firstClassRegex = FirstClass.class.getName().replace( "$", "\\$" ); - - private static final String secondClassRegex = SecondClass.class.getName().replace( "$", "\\$" ); - - private Filter createMethodFilter( String requestString ) - { - return new FilterFactory( getClass().getClassLoader() ).createMethodFilter( requestString ); - } - - @Test - public void testSanity() - { - ResolvedTest test = new ResolvedTest( ResolvedTest.Type.CLASS, " \t \n ", true ); - assertNull( test.getTestClassPattern() ); - assertNull( test.getTestMethodPattern() ); - assertFalse( test.hasTestClassPattern() ); - assertFalse( test.hasTestMethodPattern() ); - assertTrue( test.isEmpty() ); - assertTrue( test.isRegexTestClassPattern() ); - assertFalse( test.isRegexTestMethodPattern() ); - test = new ResolvedTest( ResolvedTest.Type.METHOD, " \n \t ", true ); - assertNull( test.getTestClassPattern() ); - assertNull( test.getTestMethodPattern() ); - assertFalse( test.hasTestClassPattern() ); - assertFalse( test.hasTestMethodPattern() ); - assertTrue( test.isEmpty() ); - assertFalse( test.isRegexTestClassPattern() ); - assertTrue( test.isRegexTestMethodPattern() ); - test = new ResolvedTest( ResolvedTest.Type.METHOD, " \n ", false ); - assertNull( test.getTestClassPattern() ); - assertNull( test.getTestMethodPattern() ); - assertFalse( test.hasTestClassPattern() ); - assertFalse( test.hasTestMethodPattern() ); - assertTrue( test.isEmpty() ); - assertFalse( test.isRegexTestClassPattern() ); - assertFalse( test.isRegexTestMethodPattern() ); - test = new ResolvedTest( " \n \t ", " \n \t ", false ); - assertNull( test.getTestClassPattern() ); - assertNull( test.getTestMethodPattern() ); - assertFalse( test.hasTestClassPattern() ); - assertFalse( test.hasTestMethodPattern() ); - assertTrue( test.isEmpty() ); - assertFalse( test.isRegexTestClassPattern() ); - assertFalse( test.isRegexTestMethodPattern() ); - } - - @Test - public void testNegativeIllegalRegex() - { - try - { - new TestListResolver( "#%regex[.*.Test.class]" ); - } - catch ( IllegalArgumentException e ) - { + createTestDescription(SecondClass.class, "secondTestMethod"); + + private static final String firstClassName = FirstClass.class.getName().replace('.', '/'); + + private static final String secondClassName = SecondClass.class.getName().replace('.', '/'); + + private static final String firstClassRegex = FirstClass.class.getName().replace("$", "\\$"); + + private static final String secondClassRegex = SecondClass.class.getName().replace("$", "\\$"); + + private Filter createMethodFilter(String requestString) { + return new FilterFactory(getClass().getClassLoader()).createMethodFilter(requestString); + } + + @Test + public void testSanity() { + ResolvedTest test = new ResolvedTest(ResolvedTest.Type.CLASS, " \t \n ", true); + assertNull(test.getTestClassPattern()); + assertNull(test.getTestMethodPattern()); + assertFalse(test.hasTestClassPattern()); + assertFalse(test.hasTestMethodPattern()); + assertTrue(test.isEmpty()); + assertTrue(test.isRegexTestClassPattern()); + assertFalse(test.isRegexTestMethodPattern()); + test = new ResolvedTest(ResolvedTest.Type.METHOD, " \n \t ", true); + assertNull(test.getTestClassPattern()); + assertNull(test.getTestMethodPattern()); + assertFalse(test.hasTestClassPattern()); + assertFalse(test.hasTestMethodPattern()); + assertTrue(test.isEmpty()); + assertFalse(test.isRegexTestClassPattern()); + assertTrue(test.isRegexTestMethodPattern()); + test = new ResolvedTest(ResolvedTest.Type.METHOD, " \n ", false); + assertNull(test.getTestClassPattern()); + assertNull(test.getTestMethodPattern()); + assertFalse(test.hasTestClassPattern()); + assertFalse(test.hasTestMethodPattern()); + assertTrue(test.isEmpty()); + assertFalse(test.isRegexTestClassPattern()); + assertFalse(test.isRegexTestMethodPattern()); + test = new ResolvedTest(" \n \t ", " \n \t ", false); + assertNull(test.getTestClassPattern()); + assertNull(test.getTestMethodPattern()); + assertFalse(test.hasTestClassPattern()); + assertFalse(test.hasTestMethodPattern()); + assertTrue(test.isEmpty()); + assertFalse(test.isRegexTestClassPattern()); + assertFalse(test.isRegexTestMethodPattern()); + } + + @Test + public void testNegativeIllegalRegex() { + try { + new TestListResolver("#%regex[.*.Test.class]"); + } catch (IllegalArgumentException e) { // expected in junit 3.x } } @Test - public void testNegativeIllegalRegex2() - { - try - { - new TestListResolver( "%regex[.*.Test.class]#" ); - } - catch ( IllegalArgumentException e ) - { + public void testNegativeIllegalRegex2() { + try { + new TestListResolver("%regex[.*.Test.class]#"); + } catch (IllegalArgumentException e) { // expected in junit 3.x } } @Test - public void testNegativeEmptyRegex() - { - TestListResolver resolver = new TestListResolver( "%regex[ ]" ); - assertTrue( resolver.getExcludedPatterns().isEmpty() ); - assertTrue( resolver.getIncludedPatterns().isEmpty() ); - assertTrue( resolver.isEmpty() ); - assertEquals( 0, resolver.getPluginParameterTest().length() ); - assertFalse( resolver.hasExcludedMethodPatterns() ); - assertFalse( resolver.hasIncludedMethodPatterns() ); - assertFalse( resolver.hasMethodPatterns() ); + public void testNegativeEmptyRegex() { + TestListResolver resolver = new TestListResolver("%regex[ ]"); + assertTrue(resolver.getExcludedPatterns().isEmpty()); + assertTrue(resolver.getIncludedPatterns().isEmpty()); + assertTrue(resolver.isEmpty()); + assertEquals(0, resolver.getPluginParameterTest().length()); + assertFalse(resolver.hasExcludedMethodPatterns()); + assertFalse(resolver.hasIncludedMethodPatterns()); + assertFalse(resolver.hasMethodPatterns()); } @Test - public void testNegativeEmptyRegexWithHash() - { - TestListResolver resolver = new TestListResolver( "%regex[# ]" ); - assertTrue( resolver.getExcludedPatterns().isEmpty() ); - assertTrue( resolver.getIncludedPatterns().isEmpty() ); - assertTrue( resolver.isEmpty() ); - assertEquals( 0, resolver.getPluginParameterTest().length() ); - assertFalse( resolver.hasExcludedMethodPatterns() ); - assertFalse( resolver.hasIncludedMethodPatterns() ); - assertFalse( resolver.hasMethodPatterns() ); + public void testNegativeEmptyRegexWithHash() { + TestListResolver resolver = new TestListResolver("%regex[# ]"); + assertTrue(resolver.getExcludedPatterns().isEmpty()); + assertTrue(resolver.getIncludedPatterns().isEmpty()); + assertTrue(resolver.isEmpty()); + assertEquals(0, resolver.getPluginParameterTest().length()); + assertFalse(resolver.hasExcludedMethodPatterns()); + assertFalse(resolver.hasIncludedMethodPatterns()); + assertFalse(resolver.hasMethodPatterns()); } @Test - public void testNegativeRegexWithEmptyMethod() - { - TestListResolver resolver = new TestListResolver( "%regex[.*.Test.class# ]" ); - assertFalse( resolver.isEmpty() ); - assertTrue( resolver.getExcludedPatterns().isEmpty() ); - assertFalse( resolver.getIncludedPatterns().isEmpty() ); - assertEquals( 1, resolver.getIncludedPatterns().size() ); - assertEquals( "%regex[.*.Test.class]", resolver.getPluginParameterTest() ); - assertFalse( resolver.hasExcludedMethodPatterns() ); - assertFalse( resolver.hasIncludedMethodPatterns() ); - assertFalse( resolver.hasMethodPatterns() ); + public void testNegativeRegexWithEmptyMethod() { + TestListResolver resolver = new TestListResolver("%regex[.*.Test.class# ]"); + assertFalse(resolver.isEmpty()); + assertTrue(resolver.getExcludedPatterns().isEmpty()); + assertFalse(resolver.getIncludedPatterns().isEmpty()); + assertEquals(1, resolver.getIncludedPatterns().size()); + assertEquals("%regex[.*.Test.class]", resolver.getPluginParameterTest()); + assertFalse(resolver.hasExcludedMethodPatterns()); + assertFalse(resolver.hasIncludedMethodPatterns()); + assertFalse(resolver.hasMethodPatterns()); } @Test - public void testBackwardsCompatibilityNullMethodFilter() - { - Filter filter = createMethodFilter( null ); + public void testBackwardsCompatibilityNullMethodFilter() { + Filter filter = createMethodFilter(null); JUnitCore core = new JUnitCore(); - Result result = core.run( Request.classes( FirstClass.class, SecondClass.class ).filterWith( filter ) ); - assertTrue( result.wasSuccessful() ); - assertEquals( 5, result.getRunCount() ); - assertEquals( 0, result.getFailureCount() ); - assertEquals( 0, result.getIgnoreCount() ); + Result result = + core.run(Request.classes(FirstClass.class, SecondClass.class).filterWith(filter)); + assertTrue(result.wasSuccessful()); + assertEquals(5, result.getRunCount()); + assertEquals(0, result.getFailureCount()); + assertEquals(0, result.getIgnoreCount()); } @Test - public void testBackwardsCompatibilityEmptyMethodFilter() - { - Filter filter = createMethodFilter( "" ); + public void testBackwardsCompatibilityEmptyMethodFilter() { + Filter filter = createMethodFilter(""); JUnitCore core = new JUnitCore(); - Result result = core.run( Request.classes( FirstClass.class, SecondClass.class ).filterWith( filter ) ); - assertTrue( result.wasSuccessful() ); - assertEquals( 5, result.getRunCount() ); - assertEquals( 0, result.getFailureCount() ); - assertEquals( 0, result.getIgnoreCount() ); + Result result = + core.run(Request.classes(FirstClass.class, SecondClass.class).filterWith(filter)); + assertTrue(result.wasSuccessful()); + assertEquals(5, result.getRunCount()); + assertEquals(0, result.getFailureCount()); + assertEquals(0, result.getIgnoreCount()); } @Test - public void testBackwardsCompatibilityBlankMethodFilter() - { - Filter filter = createMethodFilter( " \n" ); + public void testBackwardsCompatibilityBlankMethodFilter() { + Filter filter = createMethodFilter(" \n"); JUnitCore core = new JUnitCore(); - Result result = core.run( Request.classes( FirstClass.class, SecondClass.class ).filterWith( filter ) ); - assertTrue( result.wasSuccessful() ); - assertEquals( 5, result.getRunCount() ); - assertEquals( 0, result.getFailureCount() ); - assertEquals( 0, result.getIgnoreCount() ); + Result result = + core.run(Request.classes(FirstClass.class, SecondClass.class).filterWith(filter)); + assertTrue(result.wasSuccessful()); + assertEquals(5, result.getRunCount()); + assertEquals(0, result.getFailureCount()); + assertEquals(0, result.getIgnoreCount()); } @Test - public void testBackwardsCompatibilityTestParameterClass() - { - Filter filter = createMethodFilter( firstClassName ); + public void testBackwardsCompatibilityTestParameterClass() { + Filter filter = createMethodFilter(firstClassName); JUnitCore core = new JUnitCore(); - Result result = core.run( Request.classes( FirstClass.class, SecondClass.class ).filterWith( filter ) ); - assertTrue( result.wasSuccessful() ); - assertEquals( 3, result.getRunCount() ); - assertEquals( 0, result.getFailureCount() ); - assertEquals( 0, result.getIgnoreCount() ); + Result result = + core.run(Request.classes(FirstClass.class, SecondClass.class).filterWith(filter)); + assertTrue(result.wasSuccessful()); + assertEquals(3, result.getRunCount()); + assertEquals(0, result.getFailureCount()); + assertEquals(0, result.getIgnoreCount()); } @Test - public void testBackwardsCompatibilityTestParameterJavaClass() - { - Filter filter = createMethodFilter( firstClassName + ".java" ); + public void testBackwardsCompatibilityTestParameterJavaClass() { + Filter filter = createMethodFilter(firstClassName + ".java"); JUnitCore core = new JUnitCore(); - Result result = core.run( Request.classes( FirstClass.class, SecondClass.class ).filterWith( filter ) ); - assertTrue( result.wasSuccessful() ); - assertEquals( 3, result.getRunCount() ); - assertEquals( 0, result.getFailureCount() ); - assertEquals( 0, result.getIgnoreCount() ); + Result result = + core.run(Request.classes(FirstClass.class, SecondClass.class).filterWith(filter)); + assertTrue(result.wasSuccessful()); + assertEquals(3, result.getRunCount()); + assertEquals(0, result.getFailureCount()); + assertEquals(0, result.getIgnoreCount()); } @Test - public void testBackwardsCompatibilityTestParameterMethod1() - { - Filter filter = createMethodFilter( firstClassName + ".java#testMethod" ); + public void testBackwardsCompatibilityTestParameterMethod1() { + Filter filter = createMethodFilter(firstClassName + ".java#testMethod"); JUnitCore core = new JUnitCore(); - Result result = core.run( Request.classes( FirstClass.class, SecondClass.class ).filterWith( filter ) ); - assertTrue( result.wasSuccessful() ); - assertEquals( 1, result.getRunCount() ); - assertEquals( 0, result.getFailureCount() ); - assertEquals( 0, result.getIgnoreCount() ); + Result result = + core.run(Request.classes(FirstClass.class, SecondClass.class).filterWith(filter)); + assertTrue(result.wasSuccessful()); + assertEquals(1, result.getRunCount()); + assertEquals(0, result.getFailureCount()); + assertEquals(0, result.getIgnoreCount()); } @Test - public void testBackwardsCompatibilityTestParameterMethod2() - { - Filter filter = createMethodFilter( firstClassName + "#testMethod" ); + public void testBackwardsCompatibilityTestParameterMethod2() { + Filter filter = createMethodFilter(firstClassName + "#testMethod"); JUnitCore core = new JUnitCore(); - Result result = core.run( Request.classes( FirstClass.class, SecondClass.class ).filterWith( filter ) ); - assertTrue( result.wasSuccessful() ); - assertEquals( 1, result.getRunCount() ); - assertEquals( 0, result.getFailureCount() ); - assertEquals( 0, result.getIgnoreCount() ); + Result result = + core.run(Request.classes(FirstClass.class, SecondClass.class).filterWith(filter)); + assertTrue(result.wasSuccessful()); + assertEquals(1, result.getRunCount()); + assertEquals(0, result.getFailureCount()); + assertEquals(0, result.getIgnoreCount()); } @Test - public void testBackwardsCompatibilityTestParameterMethod3() - { - Filter filter = createMethodFilter( firstClassName + "#testMethod" ); + public void testBackwardsCompatibilityTestParameterMethod3() { + Filter filter = createMethodFilter(firstClassName + "#testMethod"); JUnitCore core = new JUnitCore(); - Result result = core.run( Request.classes( FirstClass.class, SecondClass.class ).filterWith( filter ) ); - assertTrue( result.wasSuccessful() ); - assertEquals( 1, result.getRunCount() ); - assertEquals( 0, result.getFailureCount() ); - assertEquals( 0, result.getIgnoreCount() ); + Result result = + core.run(Request.classes(FirstClass.class, SecondClass.class).filterWith(filter)); + assertTrue(result.wasSuccessful()); + assertEquals(1, result.getRunCount()); + assertEquals(0, result.getFailureCount()); + assertEquals(0, result.getIgnoreCount()); } @Test - public void testRegexWithWildcard() - { - Filter filter = - createMethodFilter( "%regex[" + firstClassRegex + ".*]" ); + public void testRegexWithWildcard() { + Filter filter = createMethodFilter("%regex[" + firstClassRegex + ".*]"); JUnitCore core = new JUnitCore(); - Result result = core.run( Request.classes( FirstClass.class, SecondClass.class ).filterWith( filter ) ); - assertTrue( result.wasSuccessful() ); - assertEquals( 3, result.getRunCount() ); - assertEquals( 0, result.getFailureCount() ); - assertEquals( 0, result.getIgnoreCount() ); + Result result = + core.run(Request.classes(FirstClass.class, SecondClass.class).filterWith(filter)); + assertTrue(result.wasSuccessful()); + assertEquals(3, result.getRunCount()); + assertEquals(0, result.getFailureCount()); + assertEquals(0, result.getIgnoreCount()); } @Test - public void testRegexWithWildcardClass() - { - Filter filter = - createMethodFilter( "%regex[" + firstClassRegex + ".*.class]" ); + public void testRegexWithWildcardClass() { + Filter filter = createMethodFilter("%regex[" + firstClassRegex + ".*.class]"); JUnitCore core = new JUnitCore(); - Result result = core.run( Request.classes( FirstClass.class, SecondClass.class ).filterWith( filter ) ); - assertTrue( result.wasSuccessful() ); - assertEquals( 3, result.getRunCount() ); - assertEquals( 0, result.getFailureCount() ); - assertEquals( 0, result.getIgnoreCount() ); + Result result = + core.run(Request.classes(FirstClass.class, SecondClass.class).filterWith(filter)); + assertTrue(result.wasSuccessful()); + assertEquals(3, result.getRunCount()); + assertEquals(0, result.getFailureCount()); + assertEquals(0, result.getIgnoreCount()); } @Test - public void testRegexWithExactClass() - { - Filter filter = createMethodFilter( "%regex[" + firstClassRegex + ".class]" ); + public void testRegexWithExactClass() { + Filter filter = createMethodFilter("%regex[" + firstClassRegex + ".class]"); JUnitCore core = new JUnitCore(); - Result result = core.run( Request.classes( FirstClass.class, SecondClass.class ).filterWith( filter ) ); - assertTrue( result.wasSuccessful() ); - assertEquals( 3, result.getRunCount() ); - assertEquals( 0, result.getFailureCount() ); - assertEquals( 0, result.getIgnoreCount() ); + Result result = + core.run(Request.classes(FirstClass.class, SecondClass.class).filterWith(filter)); + assertTrue(result.wasSuccessful()); + assertEquals(3, result.getRunCount()); + assertEquals(0, result.getFailureCount()); + assertEquals(0, result.getIgnoreCount()); } @Test - public void testRegexWithWildcardJavaClassNegativeTest() - { - Filter filter = createMethodFilter( "%regex[" + firstClassRegex + ".*.class]" ); + public void testRegexWithWildcardJavaClassNegativeTest() { + Filter filter = createMethodFilter("%regex[" + firstClassRegex + ".*.class]"); JUnitCore core = new JUnitCore(); - Result result = core.run( Request.classes( FirstClass.class, SecondClass.class ).filterWith( filter ) ); - assertTrue( result.wasSuccessful() ); - assertEquals( 3, result.getRunCount() ); - assertEquals( 0, result.getFailureCount() ); - assertEquals( 0, result.getIgnoreCount() ); + Result result = + core.run(Request.classes(FirstClass.class, SecondClass.class).filterWith(filter)); + assertTrue(result.wasSuccessful()); + assertEquals(3, result.getRunCount()); + assertEquals(0, result.getFailureCount()); + assertEquals(0, result.getIgnoreCount()); } @Test - public void testRegexWithTwoClasses() - { - Filter filter = createMethodFilter( "%regex[" + firstClassRegex + ".*|" + secondClassRegex + ".*]" ); + public void testRegexWithTwoClasses() { + Filter filter = createMethodFilter("%regex[" + firstClassRegex + ".*|" + secondClassRegex + ".*]"); JUnitCore core = new JUnitCore(); - Result result = core.run( Request.classes( FirstClass.class, SecondClass.class, ThirdClass.class ) - .filterWith( filter ) ); - assertTrue( result.wasSuccessful() ); - assertEquals( 5, result.getRunCount() ); - assertEquals( 0, result.getFailureCount() ); - assertEquals( 0, result.getIgnoreCount() ); + Result result = core.run(Request.classes(FirstClass.class, SecondClass.class, ThirdClass.class) + .filterWith(filter)); + assertTrue(result.wasSuccessful()); + assertEquals(5, result.getRunCount()); + assertEquals(0, result.getFailureCount()); + assertEquals(0, result.getIgnoreCount()); } @Test - public void testRegexWithTwoClassesComplement() - { - Filter filter = createMethodFilter( "!%regex[" + firstClassRegex + ".*|" + secondClassRegex + ".*]" ); + public void testRegexWithTwoClassesComplement() { + Filter filter = createMethodFilter("!%regex[" + firstClassRegex + ".*|" + secondClassRegex + ".*]"); JUnitCore core = new JUnitCore(); - Result result = core.run( Request.classes( FirstClass.class, SecondClass.class, ThirdClass.class ) - .filterWith( filter ) ); - assertTrue( result.wasSuccessful() ); - assertEquals( 2, result.getRunCount() ); - assertEquals( 0, result.getFailureCount() ); - assertEquals( 0, result.getIgnoreCount() ); + Result result = core.run(Request.classes(FirstClass.class, SecondClass.class, ThirdClass.class) + .filterWith(filter)); + assertTrue(result.wasSuccessful()); + assertEquals(2, result.getRunCount()); + assertEquals(0, result.getFailureCount()); + assertEquals(0, result.getIgnoreCount()); } @Test - public void testRegexWithTwoClassesAndOneMethod() - { + public void testRegexWithTwoClassesAndOneMethod() { Filter filter = - createMethodFilter( "%regex[" + firstClassRegex + ".*|" + secondClassRegex + ".* # otherMethod]" ); + createMethodFilter("%regex[" + firstClassRegex + ".*|" + secondClassRegex + ".* # otherMethod]"); JUnitCore core = new JUnitCore(); - Result result = core.run( Request.classes( FirstClass.class, SecondClass.class, ThirdClass.class ) - .filterWith( filter ) ); - assertTrue( result.wasSuccessful() ); - assertEquals( 1, result.getRunCount() ); - assertEquals( 0, result.getFailureCount() ); - assertEquals( 0, result.getIgnoreCount() ); + Result result = core.run(Request.classes(FirstClass.class, SecondClass.class, ThirdClass.class) + .filterWith(filter)); + assertTrue(result.wasSuccessful()); + assertEquals(1, result.getRunCount()); + assertEquals(0, result.getFailureCount()); + assertEquals(0, result.getIgnoreCount()); } @Test - public void testRegexWithTwoClassesAndOneMethodComplement() - { + public void testRegexWithTwoClassesAndOneMethodComplement() { Filter filter = - createMethodFilter( "!%regex[" + firstClassRegex + ".*|" + secondClassRegex + ".*# otherMethod]" ); + createMethodFilter("!%regex[" + firstClassRegex + ".*|" + secondClassRegex + ".*# otherMethod]"); JUnitCore core = new JUnitCore(); - Result result = core.run( Request.classes( FirstClass.class, SecondClass.class, ThirdClass.class ) - .filterWith( filter ) ); - assertTrue( result.wasSuccessful() ); - assertEquals( 6, result.getRunCount() ); - assertEquals( 0, result.getFailureCount() ); - assertEquals( 0, result.getIgnoreCount() ); + Result result = core.run(Request.classes(FirstClass.class, SecondClass.class, ThirdClass.class) + .filterWith(filter)); + assertTrue(result.wasSuccessful()); + assertEquals(6, result.getRunCount()); + assertEquals(0, result.getFailureCount()); + assertEquals(0, result.getIgnoreCount()); } @Test - public void testRegexWithTwoClassesAndWildcardMethod() - { - Filter filter = createMethodFilter( "%regex[" + firstClassRegex + ".*|" + secondClassRegex + ".*#test.* ]" ); + public void testRegexWithTwoClassesAndWildcardMethod() { + Filter filter = createMethodFilter("%regex[" + firstClassRegex + ".*|" + secondClassRegex + ".*#test.* ]"); JUnitCore core = new JUnitCore(); - Result result = core.run( Request.classes( FirstClass.class, SecondClass.class, ThirdClass.class ) - .filterWith( filter ) ); - assertTrue( result.wasSuccessful() ); - assertEquals( 2, result.getRunCount() ); - assertEquals( 0, result.getFailureCount() ); - assertEquals( 0, result.getIgnoreCount() ); + Result result = core.run(Request.classes(FirstClass.class, SecondClass.class, ThirdClass.class) + .filterWith(filter)); + assertTrue(result.wasSuccessful()); + assertEquals(2, result.getRunCount()); + assertEquals(0, result.getFailureCount()); + assertEquals(0, result.getIgnoreCount()); } @Test - public void testRegexWithTwoClassesAndRegexMethodComplement() - { - Filter filter = createMethodFilter( "!%regex[" + firstClassRegex + ".*|" + secondClassRegex + ".*#test.*]" ); + public void testRegexWithTwoClassesAndRegexMethodComplement() { + Filter filter = createMethodFilter("!%regex[" + firstClassRegex + ".*|" + secondClassRegex + ".*#test.*]"); JUnitCore core = new JUnitCore(); - Result result = core.run( Request.classes( FirstClass.class, SecondClass.class, ThirdClass.class ) - .filterWith( filter ) ); - assertTrue( result.wasSuccessful() ); - assertEquals( 5, result.getRunCount() ); - assertEquals( 0, result.getFailureCount() ); - assertEquals( 0, result.getIgnoreCount() ); + Result result = core.run(Request.classes(FirstClass.class, SecondClass.class, ThirdClass.class) + .filterWith(filter)); + assertTrue(result.wasSuccessful()); + assertEquals(5, result.getRunCount()); + assertEquals(0, result.getFailureCount()); + assertEquals(0, result.getIgnoreCount()); } @Test - public void testRegexWithTwoClassesAndRegexMethods() - { + public void testRegexWithTwoClassesAndRegexMethods() { Filter filter = - createMethodFilter( "%regex[ " + firstClassRegex + ".*|" + secondClassRegex + ".* # test.*|other.* ]" ); + createMethodFilter("%regex[ " + firstClassRegex + ".*|" + secondClassRegex + ".* # test.*|other.* ]"); JUnitCore core = new JUnitCore(); - Result result = core.run( Request.classes( FirstClass.class, SecondClass.class, ThirdClass.class ) - .filterWith( filter ) ); - assertTrue( result.wasSuccessful() ); - assertEquals( 3, result.getRunCount() ); - assertEquals( 0, result.getFailureCount() ); - assertEquals( 0, result.getIgnoreCount() ); + Result result = core.run(Request.classes(FirstClass.class, SecondClass.class, ThirdClass.class) + .filterWith(filter)); + assertTrue(result.wasSuccessful()); + assertEquals(3, result.getRunCount()); + assertEquals(0, result.getFailureCount()); + assertEquals(0, result.getIgnoreCount()); } @Test - public void testRegexWithTwoClassesAndRegexMethodsComplement() - { + public void testRegexWithTwoClassesAndRegexMethodsComplement() { Filter filter = - createMethodFilter( "!%regex[" + firstClassRegex + ".*|" + secondClassRegex + ".* # test.*|other.* ]" ); + createMethodFilter("!%regex[" + firstClassRegex + ".*|" + secondClassRegex + ".* # test.*|other.* ]"); JUnitCore core = new JUnitCore(); - Result result = core.run( Request.classes( FirstClass.class, SecondClass.class, ThirdClass.class ) - .filterWith( filter ) ); - assertTrue( result.wasSuccessful() ); - assertEquals( 4, result.getRunCount() ); - assertEquals( 0, result.getFailureCount() ); - assertEquals( 0, result.getIgnoreCount() ); + Result result = core.run(Request.classes(FirstClass.class, SecondClass.class, ThirdClass.class) + .filterWith(filter)); + assertTrue(result.wasSuccessful()); + assertEquals(4, result.getRunCount()); + assertEquals(0, result.getFailureCount()); + assertEquals(0, result.getIgnoreCount()); } @Test - public void testMultipleRegexClasses() - { - Filter filter = - createMethodFilter( "%regex[" + firstClassRegex + ".*], %regex[" + secondClassRegex + ".*]" ); + public void testMultipleRegexClasses() { + Filter filter = createMethodFilter("%regex[" + firstClassRegex + ".*], %regex[" + secondClassRegex + ".*]"); JUnitCore core = new JUnitCore(); - Result result = core.run( Request.classes( FirstClass.class, SecondClass.class, ThirdClass.class ) - .filterWith( filter ) ); - assertTrue( result.wasSuccessful() ); - assertEquals( 5, result.getRunCount() ); - assertEquals( 0, result.getFailureCount() ); - assertEquals( 0, result.getIgnoreCount() ); + Result result = core.run(Request.classes(FirstClass.class, SecondClass.class, ThirdClass.class) + .filterWith(filter)); + assertTrue(result.wasSuccessful()); + assertEquals(5, result.getRunCount()); + assertEquals(0, result.getFailureCount()); + assertEquals(0, result.getIgnoreCount()); } @Test - public void testMultipleRegexClassesComplement() - { - Filter filter = - createMethodFilter( "!%regex[" + firstClassRegex + ".*] , !%regex[" + secondClassRegex + ".*]" ); + public void testMultipleRegexClassesComplement() { + Filter filter = createMethodFilter("!%regex[" + firstClassRegex + ".*] , !%regex[" + secondClassRegex + ".*]"); JUnitCore core = new JUnitCore(); - Result result = core.run( Request.classes( FirstClass.class, SecondClass.class, ThirdClass.class ) - .filterWith( filter ) ); - assertTrue( result.wasSuccessful() ); - assertEquals( 2, result.getRunCount() ); - assertEquals( 0, result.getFailureCount() ); - assertEquals( 0, result.getIgnoreCount() ); + Result result = core.run(Request.classes(FirstClass.class, SecondClass.class, ThirdClass.class) + .filterWith(filter)); + assertTrue(result.wasSuccessful()); + assertEquals(2, result.getRunCount()); + assertEquals(0, result.getFailureCount()); + assertEquals(0, result.getIgnoreCount()); } @Test - public void testMultipleClasses() - { - Filter filter = createMethodFilter( firstClassName + "," + secondClassName ); + public void testMultipleClasses() { + Filter filter = createMethodFilter(firstClassName + "," + secondClassName); JUnitCore core = new JUnitCore(); - Result result = core.run( Request.classes( FirstClass.class, SecondClass.class, ThirdClass.class ) - .filterWith( filter ) ); - assertTrue( result.wasSuccessful() ); - assertEquals( 5, result.getRunCount() ); - assertEquals( 0, result.getFailureCount() ); - assertEquals( 0, result.getIgnoreCount() ); + Result result = core.run(Request.classes(FirstClass.class, SecondClass.class, ThirdClass.class) + .filterWith(filter)); + assertTrue(result.wasSuccessful()); + assertEquals(5, result.getRunCount()); + assertEquals(0, result.getFailureCount()); + assertEquals(0, result.getIgnoreCount()); } @Test - public void testMultipleClassesMethods() - { - Filter filter = createMethodFilter( firstClassName + "#other*," + secondClassName + "#*TestMethod" ); + public void testMultipleClassesMethods() { + Filter filter = createMethodFilter(firstClassName + "#other*," + secondClassName + "#*TestMethod"); JUnitCore core = new JUnitCore(); - Result result = core.run( Request.classes( FirstClass.class, SecondClass.class, ThirdClass.class ) - .filterWith( filter ) ); - assertTrue( result.wasSuccessful() ); - assertEquals( 2, result.getRunCount() ); - assertEquals( 0, result.getFailureCount() ); - assertEquals( 0, result.getIgnoreCount() ); + Result result = core.run(Request.classes(FirstClass.class, SecondClass.class, ThirdClass.class) + .filterWith(filter)); + assertTrue(result.wasSuccessful()); + assertEquals(2, result.getRunCount()); + assertEquals(0, result.getFailureCount()); + assertEquals(0, result.getIgnoreCount()); } @Test - public void testMultipleClassesAndMultipleMethodsWithWildcards() - { - Filter filter = createMethodFilter( firstClassName + "#other*+second*Method," - + secondClassName + "#*TestMethod" ); + public void testMultipleClassesAndMultipleMethodsWithWildcards() { + Filter filter = + createMethodFilter(firstClassName + "#other*+second*Method," + secondClassName + "#*TestMethod"); JUnitCore core = new JUnitCore(); - Result result = core.run( Request.classes( FirstClass.class, SecondClass.class, ThirdClass.class ) - .filterWith( filter ) ); - assertTrue( result.wasSuccessful() ); - assertEquals( 3, result.getRunCount() ); - assertEquals( 0, result.getFailureCount() ); - assertEquals( 0, result.getIgnoreCount() ); + Result result = core.run(Request.classes(FirstClass.class, SecondClass.class, ThirdClass.class) + .filterWith(filter)); + assertTrue(result.wasSuccessful()); + assertEquals(3, result.getRunCount()); + assertEquals(0, result.getFailureCount()); + assertEquals(0, result.getIgnoreCount()); } @Test - public void testMultipleClassesAndMultipleMethodsWithRegex() - { - Filter filter = createMethodFilter( "%regex[" + firstClassRegex + ".class#other.*|second.*Method]," - + "%regex[" + secondClassRegex + ".class#.*TestMethod]" ); + public void testMultipleClassesAndMultipleMethodsWithRegex() { + Filter filter = createMethodFilter("%regex[" + firstClassRegex + ".class#other.*|second.*Method]," + "%regex[" + + secondClassRegex + ".class#.*TestMethod]"); JUnitCore core = new JUnitCore(); - Result result = core.run( Request.classes( FirstClass.class, SecondClass.class, ThirdClass.class ) - .filterWith( filter ) ); - assertTrue( result.wasSuccessful() ); - assertEquals( 3, result.getRunCount() ); - assertEquals( 0, result.getFailureCount() ); - assertEquals( 0, result.getIgnoreCount() ); + Result result = core.run(Request.classes(FirstClass.class, SecondClass.class, ThirdClass.class) + .filterWith(filter)); + assertTrue(result.wasSuccessful()); + assertEquals(3, result.getRunCount()); + assertEquals(0, result.getFailureCount()); + assertEquals(0, result.getIgnoreCount()); } @Test - public void testMultipleClassesAndMultipleMethodsMix() - { - Filter filter = createMethodFilter( "%regex[" + firstClassRegex + ".class # other.*|second.*Method]," - + secondClassName + "#*TestMethod" ); + public void testMultipleClassesAndMultipleMethodsMix() { + Filter filter = createMethodFilter( + "%regex[" + firstClassRegex + ".class # other.*|second.*Method]," + secondClassName + "#*TestMethod"); JUnitCore core = new JUnitCore(); - Result result = core.run( Request.classes( FirstClass.class, SecondClass.class, ThirdClass.class ) - .filterWith( filter ) ); - assertTrue( result.wasSuccessful() ); - assertEquals( 3, result.getRunCount() ); - assertEquals( 0, result.getFailureCount() ); - assertEquals( 0, result.getIgnoreCount() ); + Result result = core.run(Request.classes(FirstClass.class, SecondClass.class, ThirdClass.class) + .filterWith(filter)); + assertTrue(result.wasSuccessful()); + assertEquals(3, result.getRunCount()); + assertEquals(0, result.getFailureCount()); + assertEquals(0, result.getIgnoreCount()); } @Test - public void testMultipleClassesAndMultipleMethods() - { - Filter filter = createMethodFilter( firstClassName + "#other*+secondTestMethod," - + secondClassName + "#*TestMethod" ); + public void testMultipleClassesAndMultipleMethods() { + Filter filter = + createMethodFilter(firstClassName + "#other*+secondTestMethod," + secondClassName + "#*TestMethod"); JUnitCore core = new JUnitCore(); - Result result = core.run( Request.classes( FirstClass.class, SecondClass.class, ThirdClass.class ) - .filterWith( filter ) ); - assertTrue( result.wasSuccessful() ); - assertEquals( 3, result.getRunCount() ); - assertEquals( 0, result.getFailureCount() ); - assertEquals( 0, result.getIgnoreCount() ); + Result result = core.run(Request.classes(FirstClass.class, SecondClass.class, ThirdClass.class) + .filterWith(filter)); + assertTrue(result.wasSuccessful()); + assertEquals(3, result.getRunCount()); + assertEquals(0, result.getFailureCount()); + assertEquals(0, result.getIgnoreCount()); } @Test - public void testMultipleClassesComplement() - { - Filter filter = createMethodFilter( "!" + firstClassName + ",!" + secondClassName ); + public void testMultipleClassesComplement() { + Filter filter = createMethodFilter("!" + firstClassName + ",!" + secondClassName); JUnitCore core = new JUnitCore(); - Result result = core.run( Request.classes( FirstClass.class, SecondClass.class, ThirdClass.class ) - .filterWith( filter ) ); - assertTrue( result.wasSuccessful() ); - assertEquals( 2, result.getRunCount() ); - assertEquals( 0, result.getFailureCount() ); - assertEquals( 0, result.getIgnoreCount() ); + Result result = core.run(Request.classes(FirstClass.class, SecondClass.class, ThirdClass.class) + .filterWith(filter)); + assertTrue(result.wasSuccessful()); + assertEquals(2, result.getRunCount()); + assertEquals(0, result.getFailureCount()); + assertEquals(0, result.getIgnoreCount()); } @Test - public void testMultipleRegexClassesMethods() - { - Filter filter = - createMethodFilter( "%regex[" + firstClassRegex + ".* # test.*|other.*]," - + "%regex[" + secondClassRegex + ".*#second.*]" ); + public void testMultipleRegexClassesMethods() { + Filter filter = createMethodFilter( + "%regex[" + firstClassRegex + ".* # test.*|other.*]," + "%regex[" + secondClassRegex + ".*#second.*]"); JUnitCore core = new JUnitCore(); - Result result = core.run( Request.classes( FirstClass.class, SecondClass.class, ThirdClass.class ) - .filterWith( filter ) ); - assertTrue( result.wasSuccessful() ); - assertEquals( 3, result.getRunCount() ); - assertEquals( 0, result.getFailureCount() ); - assertEquals( 0, result.getIgnoreCount() ); + Result result = core.run(Request.classes(FirstClass.class, SecondClass.class, ThirdClass.class) + .filterWith(filter)); + assertTrue(result.wasSuccessful()); + assertEquals(3, result.getRunCount()); + assertEquals(0, result.getFailureCount()); + assertEquals(0, result.getIgnoreCount()); } @Test - public void testMultipleRegexClassesMethodsComplement() - { - Filter filter = - createMethodFilter( "!%regex[" + firstClassRegex + ".* # test.*|other.*]," - + "!%regex[" + secondClassRegex + ".*#second.*]" ); + public void testMultipleRegexClassesMethodsComplement() { + Filter filter = createMethodFilter("!%regex[" + firstClassRegex + ".* # test.*|other.*]," + "!%regex[" + + secondClassRegex + ".*#second.*]"); JUnitCore core = new JUnitCore(); - Result result = core.run( Request.classes( FirstClass.class, SecondClass.class, ThirdClass.class ) - .filterWith( filter ) ); - assertTrue( result.wasSuccessful() ); - assertEquals( 4, result.getRunCount() ); - assertEquals( 0, result.getFailureCount() ); - assertEquals( 0, result.getIgnoreCount() ); + Result result = core.run(Request.classes(FirstClass.class, SecondClass.class, ThirdClass.class) + .filterWith(filter)); + assertTrue(result.wasSuccessful()); + assertEquals(4, result.getRunCount()); + assertEquals(0, result.getFailureCount()); + assertEquals(0, result.getIgnoreCount()); } @Test - public void testShouldMatchExactMethodName() - { - Filter exactFilter = createMethodFilter( "#testMethod" ); - assertTrue( "exact match on name should run", exactFilter.shouldRun( testMethod ) ); + public void testShouldMatchExactMethodName() { + Filter exactFilter = createMethodFilter("#testMethod"); + assertTrue("exact match on name should run", exactFilter.shouldRun(testMethod)); } @Test - public void testShouldMatchExactMethodNameComplement() - { - Filter exactFilter = createMethodFilter( "!#testMethod" ); - assertFalse( "should not run testMethod", exactFilter.shouldRun( testMethod ) ); - assertTrue( "should run other than testMethod", exactFilter.shouldRun( secondTestMethod ) ); - assertFalse( "should not run testMethod", exactFilter.shouldRun( testMethodInSecondClass ) ); - assertTrue( "should run other than testMethod", exactFilter.shouldRun( secondTestMethodInSecondClass ) ); + public void testShouldMatchExactMethodNameComplement() { + Filter exactFilter = createMethodFilter("!#testMethod"); + assertFalse("should not run testMethod", exactFilter.shouldRun(testMethod)); + assertTrue("should run other than testMethod", exactFilter.shouldRun(secondTestMethod)); + assertFalse("should not run testMethod", exactFilter.shouldRun(testMethodInSecondClass)); + assertTrue("should run other than testMethod", exactFilter.shouldRun(secondTestMethodInSecondClass)); - exactFilter = createMethodFilter( "!FilterFactoryTest$FirstClass#testMethod" ); - assertFalse( "should not run testMethod", exactFilter.shouldRun( testMethod ) ); - assertTrue( "should run other than testMethod", exactFilter.shouldRun( secondTestMethod ) ); - assertTrue( "should not run testMethod", exactFilter.shouldRun( testMethodInSecondClass ) ); - assertTrue( "should run other than testMethod", exactFilter.shouldRun( secondTestMethodInSecondClass ) ); + exactFilter = createMethodFilter("!FilterFactoryTest$FirstClass#testMethod"); + assertFalse("should not run testMethod", exactFilter.shouldRun(testMethod)); + assertTrue("should run other than testMethod", exactFilter.shouldRun(secondTestMethod)); + assertTrue("should not run testMethod", exactFilter.shouldRun(testMethodInSecondClass)); + assertTrue("should run other than testMethod", exactFilter.shouldRun(secondTestMethodInSecondClass)); - exactFilter = - createMethodFilter( "!FilterFactoryTest$FirstClass#testMethod, !FilterFactoryTest$SecondClass#testMethod" ); - assertFalse( "should not run testMethod", exactFilter.shouldRun( testMethod ) ); - assertTrue( "should run other than testMethod", exactFilter.shouldRun( secondTestMethod ) ); - assertFalse( "should not run testMethod", exactFilter.shouldRun( testMethodInSecondClass ) ); - assertTrue( "should run other than testMethod", exactFilter.shouldRun( secondTestMethodInSecondClass ) ); + exactFilter = createMethodFilter( + "!FilterFactoryTest$FirstClass#testMethod, !FilterFactoryTest$SecondClass#testMethod"); + assertFalse("should not run testMethod", exactFilter.shouldRun(testMethod)); + assertTrue("should run other than testMethod", exactFilter.shouldRun(secondTestMethod)); + assertFalse("should not run testMethod", exactFilter.shouldRun(testMethodInSecondClass)); + assertTrue("should run other than testMethod", exactFilter.shouldRun(secondTestMethodInSecondClass)); } @Test - public void testShouldMatchExactMethodNameWithHash() - { - final Filter exactFilter = createMethodFilter( "#testMethod" ); - assertTrue( "exact match on name should run", exactFilter.shouldRun( testMethod ) ); + public void testShouldMatchExactMethodNameWithHash() { + final Filter exactFilter = createMethodFilter("#testMethod"); + assertTrue("exact match on name should run", exactFilter.shouldRun(testMethod)); } @Test - public void testShouldRunSuiteWithIncludedMethod() - { + public void testShouldRunSuiteWithIncludedMethod() { String sourceFile = "pkg" + File.separator + "XMyTest.class"; - assertTrue( new TestListResolver( "#testMethod" ).shouldRun( sourceFile, null ) ); + assertTrue(new TestListResolver("#testMethod").shouldRun(sourceFile, null)); } @Test - public void testShouldNotRunDifferentMethods() - { - final Filter exactFilter = createMethodFilter( "#testMethod" ); - Description testCase = createSuiteDescription( FirstClass.class ); - testCase.addChild( otherMethod ); - assertFalse( "exact match test case", exactFilter.shouldRun( testCase ) ); + public void testShouldNotRunDifferentMethods() { + final Filter exactFilter = createMethodFilter("#testMethod"); + Description testCase = createSuiteDescription(FirstClass.class); + testCase.addChild(otherMethod); + assertFalse("exact match test case", exactFilter.shouldRun(testCase)); } @Test - public void testShouldNotRunExactMethodWithoutClass() - { - Filter exactFilter = createMethodFilter( "#testMethod" ); - assertFalse( "should run containing matching method", exactFilter.shouldRun( secondTestMethod ) ); + public void testShouldNotRunExactMethodWithoutClass() { + Filter exactFilter = createMethodFilter("#testMethod"); + assertFalse("should run containing matching method", exactFilter.shouldRun(secondTestMethod)); } @Test - public void testShouldNotMatchExactOnOtherMethod() - { - Filter exactFilter = createMethodFilter( "#testMethod" ); - assertFalse( "should not run other methods", exactFilter.shouldRun( otherMethod ) ); + public void testShouldNotMatchExactOnOtherMethod() { + Filter exactFilter = createMethodFilter("#testMethod"); + assertFalse("should not run other methods", exactFilter.shouldRun(otherMethod)); } @Test - public void testShouldMatchWildCardsInMethodName() - { - Filter starAtEnd = createMethodFilter( "#test*" ); - assertTrue( "match ending with star should run", starAtEnd.shouldRun( testMethod ) ); + public void testShouldMatchWildCardsInMethodName() { + Filter starAtEnd = createMethodFilter("#test*"); + assertTrue("match ending with star should run", starAtEnd.shouldRun(testMethod)); - Filter starAtBeginning = createMethodFilter( "#*Method" ); - assertTrue( "match starting with star should run", starAtBeginning.shouldRun( testMethod ) ); + Filter starAtBeginning = createMethodFilter("#*Method"); + assertTrue("match starting with star should run", starAtBeginning.shouldRun(testMethod)); - Filter starInMiddle = createMethodFilter( "#test*thod" ); - assertTrue( "match containing star should run", starInMiddle.shouldRun( testMethod ) ); + Filter starInMiddle = createMethodFilter("#test*thod"); + assertTrue("match containing star should run", starInMiddle.shouldRun(testMethod)); - Filter questionAtEnd = createMethodFilter( "#testMetho?" ); - assertTrue( "match ending with question mark should run", questionAtEnd.shouldRun( testMethod ) ); + Filter questionAtEnd = createMethodFilter("#testMetho?"); + assertTrue("match ending with question mark should run", questionAtEnd.shouldRun(testMethod)); - Filter questionAtBeginning = createMethodFilter( "#????Method" ); - assertTrue( "match starting with question mark should run", questionAtBeginning.shouldRun( testMethod ) ); + Filter questionAtBeginning = createMethodFilter("#????Method"); + assertTrue("match starting with question mark should run", questionAtBeginning.shouldRun(testMethod)); - Filter questionInMiddle = createMethodFilter( "#testM?thod" ); - assertTrue( "match containing question mark should run", questionInMiddle.shouldRun( testMethod ) ); + Filter questionInMiddle = createMethodFilter("#testM?thod"); + assertTrue("match containing question mark should run", questionInMiddle.shouldRun(testMethod)); - Filter starAndQuestion = createMethodFilter( "#t?st*thod" ); - assertTrue( "match containing star and question mark should run", starAndQuestion.shouldRun( testMethod ) ); + Filter starAndQuestion = createMethodFilter("#t?st*thod"); + assertTrue("match containing star and question mark should run", starAndQuestion.shouldRun(testMethod)); } @Test - public void testShouldMatchExactClassAndMethod() - { - Filter exactFilter = createMethodFilter( firstClassName + "#testMethod" ); - assertTrue( "exact match on name should run", exactFilter.shouldRun( testMethod ) ); + public void testShouldMatchExactClassAndMethod() { + Filter exactFilter = createMethodFilter(firstClassName + "#testMethod"); + assertTrue("exact match on name should run", exactFilter.shouldRun(testMethod)); } @Test - public void testShouldMatchSimpleClassNameWithMethod() - { - Filter exactFilter = createMethodFilter( "FilterFactoryTest$FirstClass#testMethod" ); - assertTrue( "exact match on name should run", exactFilter.shouldRun( testMethod ) ); - assertFalse( "other method should not match", exactFilter.shouldRun( otherMethod ) ); + public void testShouldMatchSimpleClassNameWithMethod() { + Filter exactFilter = createMethodFilter("FilterFactoryTest$FirstClass#testMethod"); + assertTrue("exact match on name should run", exactFilter.shouldRun(testMethod)); + assertFalse("other method should not match", exactFilter.shouldRun(otherMethod)); } @Test - public void testShouldMatchNestedClassAsRegexWithMethod() - { + public void testShouldMatchNestedClassAsRegexWithMethod() { Filter exactFilter = - createMethodFilter( "%regex[.*.common.junit48.FilterFactoryTest\\$FirstClass.class#testMethod]" ); - assertTrue( "exact match on name should run", exactFilter.shouldRun( testMethod ) ); - assertFalse( "other method should not match", exactFilter.shouldRun( otherMethod ) ); + createMethodFilter("%regex[.*.common.junit48.FilterFactoryTest\\$FirstClass.class#testMethod]"); + assertTrue("exact match on name should run", exactFilter.shouldRun(testMethod)); + assertFalse("other method should not match", exactFilter.shouldRun(otherMethod)); } @Test - public void testShouldMatchNestedCanonicalClassAsRegexWithMethod() - { + public void testShouldMatchNestedCanonicalClassAsRegexWithMethod() { Filter exactFilter = - createMethodFilter( "%regex[.*.common.junit48.FilterFactoryTest.FirstClass.class#testMethod]" ); - assertTrue( "exact match on name should run", exactFilter.shouldRun( testMethod ) ); - assertFalse( "other method should not match", exactFilter.shouldRun( otherMethod ) ); + createMethodFilter("%regex[.*.common.junit48.FilterFactoryTest.FirstClass.class#testMethod]"); + assertTrue("exact match on name should run", exactFilter.shouldRun(testMethod)); + assertFalse("other method should not match", exactFilter.shouldRun(otherMethod)); } @Test - public void testShouldMatchClassNameWithWildcardAndMethod() - { - Filter exactFilter = createMethodFilter( "*First*#testMethod" ); - assertTrue( "exact match on name should run", exactFilter.shouldRun( testMethod ) ); - assertFalse( "other method should not match", exactFilter.shouldRun( otherMethod ) ); + public void testShouldMatchClassNameWithWildcardAndMethod() { + Filter exactFilter = createMethodFilter("*First*#testMethod"); + assertTrue("exact match on name should run", exactFilter.shouldRun(testMethod)); + assertFalse("other method should not match", exactFilter.shouldRun(otherMethod)); } @Test - public void testShouldMatchClassNameWithWildcardCompletely() - { - Filter exactFilter = createMethodFilter( "First*#testMethod" ); - assertFalse( "other method should not match", exactFilter.shouldRun( testMethod ) ); - assertFalse( "other method should not match", exactFilter.shouldRun( otherMethod ) ); + public void testShouldMatchClassNameWithWildcardCompletely() { + Filter exactFilter = createMethodFilter("First*#testMethod"); + assertFalse("other method should not match", exactFilter.shouldRun(testMethod)); + assertFalse("other method should not match", exactFilter.shouldRun(otherMethod)); } @Test - public void testShouldMatchMultipleMethodsSeparatedByComma() - { - Filter exactFilter = createMethodFilter( firstClassName + "#testMethod,#secondTestMethod" ); + public void testShouldMatchMultipleMethodsSeparatedByComma() { + Filter exactFilter = createMethodFilter(firstClassName + "#testMethod,#secondTestMethod"); - assertTrue( "exact match on name should run", exactFilter.shouldRun( testMethod ) ); - assertTrue( "exact match on name should run", exactFilter.shouldRun( secondTestMethod ) ); - assertTrue( "exact match on name should run", exactFilter.shouldRun( secondTestMethodInSecondClass ) ); + assertTrue("exact match on name should run", exactFilter.shouldRun(testMethod)); + assertTrue("exact match on name should run", exactFilter.shouldRun(secondTestMethod)); + assertTrue("exact match on name should run", exactFilter.shouldRun(secondTestMethodInSecondClass)); - assertFalse( "other method should not match", exactFilter.shouldRun( otherMethod ) ); + assertFalse("other method should not match", exactFilter.shouldRun(otherMethod)); } @Test - public void testShouldMatchMultipleMethodsInSameClassSeparatedByPlus() - { - Filter exactFilter = createMethodFilter( firstClassName + "#testMethod+secondTestMethod" ); + public void testShouldMatchMultipleMethodsInSameClassSeparatedByPlus() { + Filter exactFilter = createMethodFilter(firstClassName + "#testMethod+secondTestMethod"); - assertTrue( "exact match on name should run", exactFilter.shouldRun( testMethod ) ); - assertTrue( "exact match on name should run", exactFilter.shouldRun( secondTestMethod ) ); + assertTrue("exact match on name should run", exactFilter.shouldRun(testMethod)); + assertTrue("exact match on name should run", exactFilter.shouldRun(secondTestMethod)); - assertFalse( "method in another class should not match", - exactFilter.shouldRun( secondTestMethodInSecondClass ) ); + assertFalse("method in another class should not match", exactFilter.shouldRun(secondTestMethodInSecondClass)); - assertFalse( "other method should not match", exactFilter.shouldRun( otherMethod ) ); + assertFalse("other method should not match", exactFilter.shouldRun(otherMethod)); } @Test - public void testShouldRunCompleteClassWhenSeparatedByCommaWithoutHash() - { - Filter exactFilter = createMethodFilter( firstClassName + "#testMethod," + secondClassName ); + public void testShouldRunCompleteClassWhenSeparatedByCommaWithoutHash() { + Filter exactFilter = createMethodFilter(firstClassName + "#testMethod," + secondClassName); - assertTrue( "exact match on name should run", exactFilter.shouldRun( testMethod ) ); + assertTrue("exact match on name should run", exactFilter.shouldRun(testMethod)); - assertFalse( "other method should not match", exactFilter.shouldRun( secondTestMethod ) ); - assertFalse( "other method should not match", exactFilter.shouldRun( otherMethod ) ); + assertFalse("other method should not match", exactFilter.shouldRun(secondTestMethod)); + assertFalse("other method should not match", exactFilter.shouldRun(otherMethod)); - assertTrue( "should run complete second class", exactFilter.shouldRun( testMethodInSecondClass ) ); - assertTrue( "should run complete second class", exactFilter.shouldRun( secondTestMethodInSecondClass ) ); + assertTrue("should run complete second class", exactFilter.shouldRun(testMethodInSecondClass)); + assertTrue("should run complete second class", exactFilter.shouldRun(secondTestMethodInSecondClass)); } @Test - public void testShouldRunSuitesContainingExactMethodName() - { - Description suite = Description.createSuiteDescription( Suite.class ); - suite.addChild( testMethod ); - suite.addChild( secondTestMethod ); + public void testShouldRunSuitesContainingExactMethodName() { + Description suite = Description.createSuiteDescription(Suite.class); + suite.addChild(testMethod); + suite.addChild(secondTestMethod); - Filter exactFilter = createMethodFilter( "#testMethod" ); - assertTrue( "should run suites containing matching method", exactFilter.shouldRun( suite ) ); + Filter exactFilter = createMethodFilter("#testMethod"); + assertTrue("should run suites containing matching method", exactFilter.shouldRun(suite)); } @Test - public void testShouldSkipSuitesNotContainingExactMethodName() - { - Filter exactFilter = createMethodFilter( "#otherMethod" ); - assertFalse( "should not run method", exactFilter.shouldRun( testMethod ) ); - assertFalse( "should not run method", exactFilter.shouldRun( secondTestMethod ) ); - Description suite = Description.createSuiteDescription( Suite.class ); - suite.addChild( testMethod ); - suite.addChild( secondTestMethod ); - assertFalse( "should not run suites containing no matches", exactFilter.shouldRun( suite ) ); + public void testShouldSkipSuitesNotContainingExactMethodName() { + Filter exactFilter = createMethodFilter("#otherMethod"); + assertFalse("should not run method", exactFilter.shouldRun(testMethod)); + assertFalse("should not run method", exactFilter.shouldRun(secondTestMethod)); + Description suite = Description.createSuiteDescription(Suite.class); + suite.addChild(testMethod); + suite.addChild(secondTestMethod); + assertFalse("should not run suites containing no matches", exactFilter.shouldRun(suite)); } @Test - public void testSingleMethodWithJUnitCoreSuite() - { - Filter filter = createMethodFilter( "#testMethod" ); + public void testSingleMethodWithJUnitCoreSuite() { + Filter filter = createMethodFilter("#testMethod"); JUnitCore core = new JUnitCore(); - Result result = core.run( Request.classes( Suite.class ).filterWith( filter ) ); - assertTrue( result.wasSuccessful() ); - assertEquals( 2, result.getRunCount() ); - assertEquals( 0, result.getFailureCount() ); - assertEquals( 0, result.getIgnoreCount() ); + Result result = core.run(Request.classes(Suite.class).filterWith(filter)); + assertTrue(result.wasSuccessful()); + assertEquals(2, result.getRunCount()); + assertEquals(0, result.getFailureCount()); + assertEquals(0, result.getIgnoreCount()); } @Test - public void testShouldNotRunNonExistingMethodJUnitCoreSuite() - { - Filter filter = createMethodFilter( "#nonExisting" ); + public void testShouldNotRunNonExistingMethodJUnitCoreSuite() { + Filter filter = createMethodFilter("#nonExisting"); JUnitCore core = new JUnitCore(); - Result result = core.run( Request.classes( Suite.class ).filterWith( filter ) ); - assertTrue( result.wasSuccessful() ); - assertEquals( 0, result.getRunCount() ); //running the Suite - assertEquals( 0, result.getFailureCount() ); - assertEquals( 0, result.getIgnoreCount() ); + Result result = core.run(Request.classes(Suite.class).filterWith(filter)); + assertTrue(result.wasSuccessful()); + assertEquals(0, result.getRunCount()); // running the Suite + assertEquals(0, result.getFailureCount()); + assertEquals(0, result.getIgnoreCount()); } @Test - public void testShouldRunNonExistingMethodJUnitCoreSuite() - { - Filter filter = createMethodFilter( "!#nonExisting" ); + public void testShouldRunNonExistingMethodJUnitCoreSuite() { + Filter filter = createMethodFilter("!#nonExisting"); JUnitCore core = new JUnitCore(); - Result result = core.run( Request.classes( Suite.class ).filterWith( filter ) ); - assertTrue( result.wasSuccessful() ); - assertEquals( 5, result.getRunCount() ); - assertEquals( 0, result.getFailureCount() ); - assertEquals( 0, result.getIgnoreCount() ); + Result result = core.run(Request.classes(Suite.class).filterWith(filter)); + assertTrue(result.wasSuccessful()); + assertEquals(5, result.getRunCount()); + assertEquals(0, result.getFailureCount()); + assertEquals(0, result.getIgnoreCount()); } @Test - public void testClassAndMethodJUnitCoreSuite() - { - Filter filter = createMethodFilter( "FilterFactoryTest$FirstClass#testMethod" ); + public void testClassAndMethodJUnitCoreSuite() { + Filter filter = createMethodFilter("FilterFactoryTest$FirstClass#testMethod"); JUnitCore core = new JUnitCore(); - Result result = core.run( Request.classes( Suite.class, FirstClass.class, SecondClass.class ) - .filterWith( filter ) ); - assertTrue( result.wasSuccessful() ); - assertEquals( 2, result.getRunCount() ); - assertEquals( 0, result.getFailureCount() ); - assertEquals( 0, result.getIgnoreCount() ); + Result result = core.run(Request.classes(Suite.class, FirstClass.class, SecondClass.class) + .filterWith(filter)); + assertTrue(result.wasSuccessful()); + assertEquals(2, result.getRunCount()); + assertEquals(0, result.getFailureCount()); + assertEquals(0, result.getIgnoreCount()); } @Test - public void testSingleMethodWithJUnitCoreFirstClass() - { - Filter filter = createMethodFilter( "#testMethod" ); + public void testSingleMethodWithJUnitCoreFirstClass() { + Filter filter = createMethodFilter("#testMethod"); JUnitCore core = new JUnitCore(); - Result result = core.run( Request.classes( FirstClass.class ).filterWith( filter ) ); - assertTrue( result.wasSuccessful() ); - assertEquals( 1, result.getRunCount() ); - assertEquals( 0, result.getFailureCount() ); - assertEquals( 0, result.getIgnoreCount() ); + Result result = core.run(Request.classes(FirstClass.class).filterWith(filter)); + assertTrue(result.wasSuccessful()); + assertEquals(1, result.getRunCount()); + assertEquals(0, result.getFailureCount()); + assertEquals(0, result.getIgnoreCount()); } @Test - public void testWithJUnitCoreFirstClassAndSingleMethod() - { - Filter filter = createMethodFilter( "FilterFactoryTest$FirstClass#testMethod" ); + public void testWithJUnitCoreFirstClassAndSingleMethod() { + Filter filter = createMethodFilter("FilterFactoryTest$FirstClass#testMethod"); JUnitCore core = new JUnitCore(); - Result result = core.run( Request.classes( FirstClass.class ).filterWith( filter ) ); - assertTrue( result.wasSuccessful() ); - assertEquals( 1, result.getRunCount() ); - assertEquals( 0, result.getFailureCount() ); - assertEquals( 0, result.getIgnoreCount() ); + Result result = core.run(Request.classes(FirstClass.class).filterWith(filter)); + assertTrue(result.wasSuccessful()); + assertEquals(1, result.getRunCount()); + assertEquals(0, result.getFailureCount()); + assertEquals(0, result.getIgnoreCount()); } @Test - public void testShouldRunSuite() - { - TestListResolver filter = new TestListResolver( "Su?te" ); - filter = TestListResolver.optionallyWildcardFilter( filter ); + public void testShouldRunSuite() { + TestListResolver filter = new TestListResolver("Su?te"); + filter = TestListResolver.optionallyWildcardFilter(filter); JUnitCore core = new JUnitCore(); - Result result = core.run( Request.classes( Suite.class ).filterWith( new MethodFilter( filter ) ) ); - assertTrue( result.wasSuccessful() ); - assertEquals( 5, result.getRunCount() ); - assertEquals( 0, result.getFailureCount() ); - assertEquals( 0, result.getIgnoreCount() ); - } - - @Test - public void testShouldRunParameterized() - { - TestListResolver filter = - new TestListResolver( "#testAA[?]+testB?[?], " - + "PT#testC*, " - + "!PT.java#testCY[?]," - + "%regex[.*.tests.pt.PT.class#w.*|x.*T.*]" ); - filter = TestListResolver.optionallyWildcardFilter( filter ); + Result result = core.run(Request.classes(Suite.class).filterWith(new MethodFilter(filter))); + assertTrue(result.wasSuccessful()); + assertEquals(5, result.getRunCount()); + assertEquals(0, result.getFailureCount()); + assertEquals(0, result.getIgnoreCount()); + } + + @Test + public void testShouldRunParameterized() { + TestListResolver filter = new TestListResolver("#testAA[?]+testB?[?], " + + "PT#testC*, " + + "!PT.java#testCY[?]," + + "%regex[.*.tests.pt.PT.class#w.*|x.*T.*]"); + filter = TestListResolver.optionallyWildcardFilter(filter); JUnitCore core = new JUnitCore(); - Result result = core.run( Request.classes( PT.class ).filterWith( new MethodFilter( filter ) ) ); - assertTrue( result.wasSuccessful() ); - assertEquals( 12, result.getRunCount() ); - assertEquals( 0, result.getFailureCount() ); - assertEquals( 0, result.getIgnoreCount() ); + Result result = core.run(Request.classes(PT.class).filterWith(new MethodFilter(filter))); + assertTrue(result.wasSuccessful()); + assertEquals(12, result.getRunCount()); + assertEquals(0, result.getFailureCount()); + assertEquals(0, result.getIgnoreCount()); } @Test - public void testShouldRunParameterizedWithPlusDelimiter() - { + public void testShouldRunParameterizedWithPlusDelimiter() { // Running parameterized tests: w12T34, x12T34 and x12T35. // Two parameters "x" and "y" in the test case PT.java change the method descriptions to the following ones: // w12T34[0], w12T34[1] // x12T34[0], x12T34[1] // x12T35[0], x12T35[1] - TestListResolver filter = - new TestListResolver( "%regex[.*.PT.* # w.*|x(\\d+)T(\\d+)\\[(\\d+)\\]]" ); - filter = TestListResolver.optionallyWildcardFilter( filter ); + TestListResolver filter = new TestListResolver("%regex[.*.PT.* # w.*|x(\\d+)T(\\d+)\\[(\\d+)\\]]"); + filter = TestListResolver.optionallyWildcardFilter(filter); JUnitCore core = new JUnitCore(); - Result result = core.run( Request.classes( PT.class ).filterWith( new MethodFilter( filter ) ) ); - assertTrue( result.wasSuccessful() ); - assertEquals( 6, result.getRunCount() ); - assertEquals( 0, result.getFailureCount() ); - assertEquals( 0, result.getIgnoreCount() ); + Result result = core.run(Request.classes(PT.class).filterWith(new MethodFilter(filter))); + assertTrue(result.wasSuccessful()); + assertEquals(6, result.getRunCount()); + assertEquals(0, result.getFailureCount()); + assertEquals(0, result.getIgnoreCount()); } @Test - public void testTestListResolver() - { - assertFalse( new TestListResolver( "b/ATest.java" ).shouldRun( "tests/a/ATest.class", null ) ); - assertFalse( new TestListResolver( "b/Test.java" ).shouldRun( "a/ATest.class", null ) ); - assertTrue( new TestListResolver( "ATest.java" ).shouldRun( "tests/a/ATest.class", null ) ); - assertTrue( new TestListResolver( "a/ATest.java" ).shouldRun( "a/ATest.class", null ) ); - assertTrue( new TestListResolver( "**/ATest.java" ).shouldRun( "a/ATest.class", null ) ); + public void testTestListResolver() { + assertFalse(new TestListResolver("b/ATest.java").shouldRun("tests/a/ATest.class", null)); + assertFalse(new TestListResolver("b/Test.java").shouldRun("a/ATest.class", null)); + assertTrue(new TestListResolver("ATest.java").shouldRun("tests/a/ATest.class", null)); + assertTrue(new TestListResolver("a/ATest.java").shouldRun("a/ATest.class", null)); + assertTrue(new TestListResolver("**/ATest.java").shouldRun("a/ATest.class", null)); Class testsATest = org.apache.maven.surefire.common.junit48.tests.ATest.class; Class aTest = org.apache.maven.surefire.common.junit48.tests.a.ATest.class; - assertFalse( new TestListResolver( "b/ATest.java" ).shouldRun( testsATest, null ) ); - assertFalse( new TestListResolver( "b/ATest.java" ).shouldRun( aTest, null ) ); - assertTrue( new TestListResolver( "ATest.java" ).shouldRun( testsATest, null ) ); - assertTrue( new TestListResolver( "a/ATest.java" ).shouldRun( aTest, null ) ); - assertTrue( new TestListResolver( "**/ATest.java" ).shouldRun( aTest, null ) ); + assertFalse(new TestListResolver("b/ATest.java").shouldRun(testsATest, null)); + assertFalse(new TestListResolver("b/ATest.java").shouldRun(aTest, null)); + assertTrue(new TestListResolver("ATest.java").shouldRun(testsATest, null)); + assertTrue(new TestListResolver("a/ATest.java").shouldRun(aTest, null)); + assertTrue(new TestListResolver("**/ATest.java").shouldRun(aTest, null)); } @Test - public void testShouldRunClassOnly() - { + public void testShouldRunClassOnly() { Class testsATest = org.apache.maven.surefire.common.junit48.tests.ATest.class; - TestListResolver resolver = new TestListResolver( "**/ATest.java#testSuccessTwo" ); - assertTrue( resolver.shouldRun( testsATest, null ) ); - resolver = new TestListResolver( "**/BTest.java#testSuccessTwo" ); - assertFalse( resolver.shouldRun( testsATest, null ) ); + TestListResolver resolver = new TestListResolver("**/ATest.java#testSuccessTwo"); + assertTrue(resolver.shouldRun(testsATest, null)); + resolver = new TestListResolver("**/BTest.java#testSuccessTwo"); + assertFalse(resolver.shouldRun(testsATest, null)); } @Test - public void testMatchPatterns() - { + public void testMatchPatterns() { String sourceFile = "pkg" + File.separator + "MyTest.class"; boolean matchPattern = - MatchPatterns.from( "**" + File.separator + "MyTest.class" ).matches( sourceFile, true ); - assertTrue( matchPattern ); + MatchPatterns.from("**" + File.separator + "MyTest.class").matches(sourceFile, true); + assertTrue(matchPattern); - matchPattern = MatchPatterns.from( "MyTest.class" ).matches( sourceFile, true ); - assertFalse( matchPattern ); + matchPattern = MatchPatterns.from("MyTest.class").matches(sourceFile, true); + assertFalse(matchPattern); - matchPattern = MatchPatterns.from( "MyTest.class" ).matches( "MyTest.class", true ); - assertTrue( matchPattern ); + matchPattern = MatchPatterns.from("MyTest.class").matches("MyTest.class", true); + assertTrue(matchPattern); - matchPattern = MatchPatterns.from( "**" + File.separator + "MyTest.class" ).matches( "MyTest.class", true ); - assertTrue( matchPattern ); + matchPattern = + MatchPatterns.from("**" + File.separator + "MyTest.class").matches("MyTest.class", true); + assertTrue(matchPattern); } @Test - public void testNegativePatternOnPackageLessClass() - { + public void testNegativePatternOnPackageLessClass() { String sourceFile = "pkg" + File.separator + "XMyTest.class"; - assertFalse( new TestListResolver( "**/MyTest.java" ).shouldRun( sourceFile, null ) ); - assertFalse( new TestListResolver( "MyTest.java" ).shouldRun( sourceFile, null ) ); - assertFalse( new TestListResolver( "MyTest.java" ).shouldRun( "XMyTest.class", null ) ); - assertFalse( new TestListResolver( "**/MyTest.java" ).shouldRun( "XMyTest.class", null ) ); + assertFalse(new TestListResolver("**/MyTest.java").shouldRun(sourceFile, null)); + assertFalse(new TestListResolver("MyTest.java").shouldRun(sourceFile, null)); + assertFalse(new TestListResolver("MyTest.java").shouldRun("XMyTest.class", null)); + assertFalse(new TestListResolver("**/MyTest.java").shouldRun("XMyTest.class", null)); } @Test - public void testPatternOnPackageLessClass() - { + public void testPatternOnPackageLessClass() { String sourceFile = "pkg" + File.separator + "MyTest.class"; - assertTrue( new TestListResolver( "**/MyTest.java" ).shouldRun( sourceFile, null ) ); - assertTrue( new TestListResolver( "MyTest.java" ).shouldRun( sourceFile, null ) ); - assertTrue( new TestListResolver( "MyTest.java" ).shouldRun( "MyTest.class", null ) ); - assertTrue( new TestListResolver( "**/MyTest.java" ).shouldRun( "MyTest.class", null ) ); + assertTrue(new TestListResolver("**/MyTest.java").shouldRun(sourceFile, null)); + assertTrue(new TestListResolver("MyTest.java").shouldRun(sourceFile, null)); + assertTrue(new TestListResolver("MyTest.java").shouldRun("MyTest.class", null)); + assertTrue(new TestListResolver("**/MyTest.java").shouldRun("MyTest.class", null)); } @Test - public void testIncludesExcludes() - { - Collection inc = Arrays.asList( "**/NotIncludedByDefault.java", "**/*Test.java" ); - Collection exc = Collections.singletonList( "**/DontRunTest.*" ); - TestListResolver resolver = new TestListResolver( inc, exc ); - assertFalse( resolver.shouldRun( "org/test/DontRunTest.class", null ) ); - assertTrue( resolver.shouldRun( "org/test/DefaultTest.class", null ) ); - assertTrue( resolver.shouldRun( "org/test/NotIncludedByDefault.class", null ) ); + public void testIncludesExcludes() { + Collection inc = Arrays.asList("**/NotIncludedByDefault.java", "**/*Test.java"); + Collection exc = Collections.singletonList("**/DontRunTest.*"); + TestListResolver resolver = new TestListResolver(inc, exc); + assertFalse(resolver.shouldRun("org/test/DontRunTest.class", null)); + assertTrue(resolver.shouldRun("org/test/DefaultTest.class", null)); + assertTrue(resolver.shouldRun("org/test/NotIncludedByDefault.class", null)); } @Test - public void testSimple() - { - TestListResolver resolver = new TestListResolver( "NotIncludedByDefault" ); - assertTrue( resolver.shouldRun( "org/test/NotIncludedByDefault.class", null ) ); + public void testSimple() { + TestListResolver resolver = new TestListResolver("NotIncludedByDefault"); + assertTrue(resolver.shouldRun("org/test/NotIncludedByDefault.class", null)); } @Test - public void testFullyQualifiedClass() - { - TestListResolver resolver = new TestListResolver( "my.package.MyTest" ); - assertFalse( resolver.shouldRun( "my/package/AnotherTest.class", null ) ); - assertTrue( resolver.shouldRun( "my/package/MyTest.class", null ) ); + public void testFullyQualifiedClass() { + TestListResolver resolver = new TestListResolver("my.package.MyTest"); + assertFalse(resolver.shouldRun("my/package/AnotherTest.class", null)); + assertTrue(resolver.shouldRun("my/package/MyTest.class", null)); } } diff --git a/surefire-providers/common-junit48/src/test/java/org/apache/maven/surefire/common/junit48/GroupMatcherCategoryFilterPreJUnit412Test.java b/surefire-providers/common-junit48/src/test/java/org/apache/maven/surefire/common/junit48/GroupMatcherCategoryFilterPreJUnit412Test.java index 543e585340..b2260048fe 100644 --- a/surefire-providers/common-junit48/src/test/java/org/apache/maven/surefire/common/junit48/GroupMatcherCategoryFilterPreJUnit412Test.java +++ b/surefire-providers/common-junit48/src/test/java/org/apache/maven/surefire/common/junit48/GroupMatcherCategoryFilterPreJUnit412Test.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.common.junit48; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.common.junit48; import junit.framework.JUnit4TestAdapter; import junit.framework.TestCase; @@ -39,61 +38,54 @@ /** * Before JUnit 4.12, @Category annotation was not @Inherited. These tests make sure the implied contract is honored. */ -public class GroupMatcherCategoryFilterPreJUnit412Test -{ +public class GroupMatcherCategoryFilterPreJUnit412Test { private GroupMatcherCategoryFilter cut; @BeforeClass - public static void printVersion() - { - System.out.println( Version.id() ); + public static void printVersion() { + System.out.println(Version.id()); } @Test - public void shouldNotMatchIncludedCategoryInParent() - { + public void shouldNotMatchIncludedCategoryInParent() { GroupMatcher included = - new SingleGroupMatcher( "org.apache.maven.surefire.common.junit48.tests.group.marker.CategoryB" ); + new SingleGroupMatcher("org.apache.maven.surefire.common.junit48.tests.group.marker.CategoryB"); GroupMatcher excluded = null; - cut = new GroupMatcherCategoryFilter( included, excluded ); - assertFalse( cut.shouldRun( createSuiteDescription( BCTest.class ) ) ); - assertFalse( cut.shouldRun( createSuiteDescription( ATest.class ) ) ); + cut = new GroupMatcherCategoryFilter(included, excluded); + assertFalse(cut.shouldRun(createSuiteDescription(BCTest.class))); + assertFalse(cut.shouldRun(createSuiteDescription(ATest.class))); } @Test - public void shouldNotMatchIncludedCategoryInHierarchy() - { + public void shouldNotMatchIncludedCategoryInHierarchy() { GroupMatcher included = - new SingleGroupMatcher( "org.apache.maven.surefire.common.junit48.tests.group.marker.CategoryC" ); + new SingleGroupMatcher("org.apache.maven.surefire.common.junit48.tests.group.marker.CategoryC"); GroupMatcher excluded = null; - cut = new GroupMatcherCategoryFilter( included, excluded ); - assertFalse( cut.shouldRun( createSuiteDescription( ABCTest.class ) ) ); - assertFalse( cut.shouldRun( createSuiteDescription( BCTest.class ) ) ); - assertFalse( cut.shouldRun( createSuiteDescription( ATest.class ) ) ); + cut = new GroupMatcherCategoryFilter(included, excluded); + assertFalse(cut.shouldRun(createSuiteDescription(ABCTest.class))); + assertFalse(cut.shouldRun(createSuiteDescription(BCTest.class))); + assertFalse(cut.shouldRun(createSuiteDescription(ATest.class))); } @Test - public void shouldNotMatchIncludedCategoryInParentWhenSelfHasAnother() - { + public void shouldNotMatchIncludedCategoryInParentWhenSelfHasAnother() { GroupMatcher included = - new SingleGroupMatcher( "org.apache.maven.surefire.common.junit48.tests.group.marker.CategoryB" ); + new SingleGroupMatcher("org.apache.maven.surefire.common.junit48.tests.group.marker.CategoryB"); GroupMatcher excluded = null; - cut = new GroupMatcherCategoryFilter( included, excluded ); - assertFalse( cut.shouldRun( createSuiteDescription( ABCTest.class ) ) ); - assertFalse( cut.shouldRun( createTestDescription( ABCTest.class, "abc" ) ) ); - assertFalse( cut.shouldRun( createSuiteDescription( ABCParameterizedTest.class ) ) ); - assertFalse( cut.shouldRun( createTestDescription( ABCParameterizedTest.class, "abc" ) ) ); + cut = new GroupMatcherCategoryFilter(included, excluded); + assertFalse(cut.shouldRun(createSuiteDescription(ABCTest.class))); + assertFalse(cut.shouldRun(createTestDescription(ABCTest.class, "abc"))); + assertFalse(cut.shouldRun(createSuiteDescription(ABCParameterizedTest.class))); + assertFalse(cut.shouldRun(createTestDescription(ABCParameterizedTest.class, "abc"))); } /** * */ - public static class JUnit4SuiteTest extends TestCase - { - public static junit.framework.Test suite() - { + public static class JUnit4SuiteTest extends TestCase { + public static junit.framework.Test suite() { TestSuite suite = new TestSuite(); - suite.addTest( new JUnit4TestAdapter( GroupMatcherCategoryFilterPreJUnit412Test.class ) ); + suite.addTest(new JUnit4TestAdapter(GroupMatcherCategoryFilterPreJUnit412Test.class)); return suite; } } diff --git a/surefire-providers/common-junit48/src/test/java/org/apache/maven/surefire/common/junit48/GroupMatcherCategoryFilterTest.java b/surefire-providers/common-junit48/src/test/java/org/apache/maven/surefire/common/junit48/GroupMatcherCategoryFilterTest.java index 6ddb11a53b..e76ec17d74 100644 --- a/surefire-providers/common-junit48/src/test/java/org/apache/maven/surefire/common/junit48/GroupMatcherCategoryFilterTest.java +++ b/surefire-providers/common-junit48/src/test/java/org/apache/maven/surefire/common/junit48/GroupMatcherCategoryFilterTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.common.junit48; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.common.junit48; import junit.framework.JUnit4TestAdapter; import junit.framework.TestCase; @@ -42,96 +41,86 @@ /** * Tests covering inheritance in @Categories for Test classes. */ -public class GroupMatcherCategoryFilterTest -{ +public class GroupMatcherCategoryFilterTest { private GroupMatcherCategoryFilter cut; @BeforeClass - public static void printVersion() - { - System.out.println( Version.id() ); + public static void printVersion() { + System.out.println(Version.id()); } @Test - public void shouldMatchIncludedCategoryInSelf() - { + public void shouldMatchIncludedCategoryInSelf() { GroupMatcher included = - new SingleGroupMatcher( "org.apache.maven.surefire.common.junit48.tests.group.marker.CategoryB" ); + new SingleGroupMatcher("org.apache.maven.surefire.common.junit48.tests.group.marker.CategoryB"); GroupMatcher excluded = null; - cut = new GroupMatcherCategoryFilter( included, excluded ); - assertTrue( cut.shouldRun( createSuiteDescription( BTest.class ) ) ); + cut = new GroupMatcherCategoryFilter(included, excluded); + assertTrue(cut.shouldRun(createSuiteDescription(BTest.class))); } @Test - public void shouldMatchIncludedCategoryInParent() - { + public void shouldMatchIncludedCategoryInParent() { GroupMatcher included = - new SingleGroupMatcher( "org.apache.maven.surefire.common.junit48.tests.group.marker.CategoryB" ); + new SingleGroupMatcher("org.apache.maven.surefire.common.junit48.tests.group.marker.CategoryB"); GroupMatcher excluded = null; - cut = new GroupMatcherCategoryFilter( included, excluded ); - assertTrue( cut.shouldRun( createSuiteDescription( BCTest.class ) ) ); - assertFalse( cut.shouldRun( createSuiteDescription( ATest.class ) ) ); + cut = new GroupMatcherCategoryFilter(included, excluded); + assertTrue(cut.shouldRun(createSuiteDescription(BCTest.class))); + assertFalse(cut.shouldRun(createSuiteDescription(ATest.class))); } @Test - public void shouldMatchIncludedCategoryInHierarchy() - { + public void shouldMatchIncludedCategoryInHierarchy() { GroupMatcher included = - new SingleGroupMatcher( "org.apache.maven.surefire.common.junit48.tests.group.marker.CategoryC" ); + new SingleGroupMatcher("org.apache.maven.surefire.common.junit48.tests.group.marker.CategoryC"); GroupMatcher excluded = null; - cut = new GroupMatcherCategoryFilter( included, excluded ); - assertTrue( cut.shouldRun( createSuiteDescription( ABCTest.class ) ) ); - assertTrue( cut.shouldRun( createSuiteDescription( BCTest.class ) ) ); - assertFalse( cut.shouldRun( createSuiteDescription( ATest.class ) ) ); + cut = new GroupMatcherCategoryFilter(included, excluded); + assertTrue(cut.shouldRun(createSuiteDescription(ABCTest.class))); + assertTrue(cut.shouldRun(createSuiteDescription(BCTest.class))); + assertFalse(cut.shouldRun(createSuiteDescription(ATest.class))); } @Test - public void shouldMatchIncludedCategoryInParentWhenSelfHasAnother() - { + public void shouldMatchIncludedCategoryInParentWhenSelfHasAnother() { GroupMatcher included = - new SingleGroupMatcher( "org.apache.maven.surefire.common.junit48.tests.group.marker.CategoryB" ); + new SingleGroupMatcher("org.apache.maven.surefire.common.junit48.tests.group.marker.CategoryB"); GroupMatcher excluded = null; - cut = new GroupMatcherCategoryFilter( included, excluded ); - assertTrue( cut.shouldRun( createSuiteDescription( ABCTest.class ) ) ); - assertTrue( cut.shouldRun( createTestDescription( ABCTest.class, "abc" ) ) ); - assertTrue( cut.shouldRun( createSuiteDescription( ABCParameterizedTest.class ) ) ); - assertTrue( cut.shouldRun( createTestDescription( ABCParameterizedTest.class, "abc" ) ) ); + cut = new GroupMatcherCategoryFilter(included, excluded); + assertTrue(cut.shouldRun(createSuiteDescription(ABCTest.class))); + assertTrue(cut.shouldRun(createTestDescription(ABCTest.class, "abc"))); + assertTrue(cut.shouldRun(createSuiteDescription(ABCParameterizedTest.class))); + assertTrue(cut.shouldRun(createTestDescription(ABCParameterizedTest.class, "abc"))); } @Test - public void shouldNotMatchIncludedCategoryInParentWhenSelfHasExcludedCategory() - { + public void shouldNotMatchIncludedCategoryInParentWhenSelfHasExcludedCategory() { GroupMatcher included = - new SingleGroupMatcher( "org.apache.maven.surefire.common.junit48.tests.group.marker.CategoryB" ); + new SingleGroupMatcher("org.apache.maven.surefire.common.junit48.tests.group.marker.CategoryB"); GroupMatcher excluded = - new SingleGroupMatcher( "org.apache.maven.surefire.common.junit48.tests.group.marker.CategoryA" ); - cut = new GroupMatcherCategoryFilter( included, excluded ); - assertFalse( cut.shouldRun( createSuiteDescription( ABCTest.class ) ) ); - assertTrue( cut.shouldRun( createSuiteDescription( BBCTest.class ) ) ); - assertTrue( cut.shouldRun( createSuiteDescription( BTest.class ) ) ); + new SingleGroupMatcher("org.apache.maven.surefire.common.junit48.tests.group.marker.CategoryA"); + cut = new GroupMatcherCategoryFilter(included, excluded); + assertFalse(cut.shouldRun(createSuiteDescription(ABCTest.class))); + assertTrue(cut.shouldRun(createSuiteDescription(BBCTest.class))); + assertTrue(cut.shouldRun(createSuiteDescription(BTest.class))); } @Test - public void shouldMatchExcludedCategoryInSelf() - { + public void shouldMatchExcludedCategoryInSelf() { GroupMatcher included = null; GroupMatcher excluded = - new SingleGroupMatcher( "org.apache.maven.surefire.common.junit48.tests.group.marker.CategoryA" ); - cut = new GroupMatcherCategoryFilter( included, excluded ); - assertFalse( cut.shouldRun( createSuiteDescription( ATest.class ) ) ); - assertTrue( cut.shouldRun( createSuiteDescription( BTest.class ) ) ); - assertTrue( cut.shouldRun( createSuiteDescription( BBCTest.class ) ) ); + new SingleGroupMatcher("org.apache.maven.surefire.common.junit48.tests.group.marker.CategoryA"); + cut = new GroupMatcherCategoryFilter(included, excluded); + assertFalse(cut.shouldRun(createSuiteDescription(ATest.class))); + assertTrue(cut.shouldRun(createSuiteDescription(BTest.class))); + assertTrue(cut.shouldRun(createSuiteDescription(BBCTest.class))); } /** * */ - public static class JUnit4SuiteTest extends TestCase - { - public static junit.framework.Test suite() - { + public static class JUnit4SuiteTest extends TestCase { + public static junit.framework.Test suite() { TestSuite suite = new TestSuite(); - suite.addTest( new JUnit4TestAdapter( GroupMatcherCategoryFilterTest.class ) ); + suite.addTest(new JUnit4TestAdapter(GroupMatcherCategoryFilterTest.class)); return suite; } } diff --git a/surefire-providers/common-junit48/src/test/java/org/apache/maven/surefire/common/junit48/JUnit48ReflectorTest.java b/surefire-providers/common-junit48/src/test/java/org/apache/maven/surefire/common/junit48/JUnit48ReflectorTest.java index 3203202483..3515ff2d28 100644 --- a/surefire-providers/common-junit48/src/test/java/org/apache/maven/surefire/common/junit48/JUnit48ReflectorTest.java +++ b/surefire-providers/common-junit48/src/test/java/org/apache/maven/surefire/common/junit48/JUnit48ReflectorTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.common.junit48; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.common.junit48; import junit.framework.TestCase; import org.junit.experimental.categories.Category; @@ -25,42 +24,25 @@ /** * @author Kristian Rosenvold */ -public class JUnit48ReflectorTest - extends TestCase -{ - public void testIsJUnit48Available() - { - JUnit48Reflector jUnit48Reflector = new JUnit48Reflector( getClass().getClassLoader() ); - assertTrue( jUnit48Reflector.isJUnit48Available() ); +public class JUnit48ReflectorTest extends TestCase { + public void testIsJUnit48Available() { + JUnit48Reflector jUnit48Reflector = new JUnit48Reflector(getClass().getClassLoader()); + assertTrue(jUnit48Reflector.isJUnit48Available()); } - public void testCategoryAnnotation() - { - JUnit48Reflector jUnit48Reflector = new JUnit48Reflector( getClass().getClassLoader() ); - assertTrue( jUnit48Reflector.isCategoryAnnotationPresent( Test1.class ) ); - assertTrue( jUnit48Reflector.isCategoryAnnotationPresent( Test3.class ) ); - assertFalse( jUnit48Reflector.isCategoryAnnotationPresent( Test2.class ) ); + public void testCategoryAnnotation() { + JUnit48Reflector jUnit48Reflector = new JUnit48Reflector(getClass().getClassLoader()); + assertTrue(jUnit48Reflector.isCategoryAnnotationPresent(Test1.class)); + assertTrue(jUnit48Reflector.isCategoryAnnotationPresent(Test3.class)); + assertFalse(jUnit48Reflector.isCategoryAnnotationPresent(Test2.class)); } - interface Foo - { + interface Foo {} - } - - @Category( Foo.class ) - private class Test1 - { + @Category(Foo.class) + private class Test1 {} - } + private class Test2 {} - private class Test2 - { - - } - - private class Test3 - extends Test1 - { - - } + private class Test3 extends Test1 {} } diff --git a/surefire-providers/common-junit48/src/test/java/org/apache/maven/surefire/common/junit48/JUnit48TestCheckerTest.java b/surefire-providers/common-junit48/src/test/java/org/apache/maven/surefire/common/junit48/JUnit48TestCheckerTest.java index 42bbdaabac..d4f9800f0b 100644 --- a/surefire-providers/common-junit48/src/test/java/org/apache/maven/surefire/common/junit48/JUnit48TestCheckerTest.java +++ b/surefire-providers/common-junit48/src/test/java/org/apache/maven/surefire/common/junit48/JUnit48TestCheckerTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.common.junit48; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.common.junit48; import org.junit.Test; import org.junit.experimental.runners.Enclosed; @@ -30,55 +29,44 @@ /** * @author Kristian Rosenvold */ -public class JUnit48TestCheckerTest -{ +public class JUnit48TestCheckerTest { @Test - public void valid48Class() - { - JUnit48TestChecker tc = new JUnit48TestChecker( this.getClass().getClassLoader() ); - assertTrue( tc.accept( BasicTest.class ) ); + public void valid48Class() { + JUnit48TestChecker tc = new JUnit48TestChecker(this.getClass().getClassLoader()); + assertTrue(tc.accept(BasicTest.class)); } @Test - public void notValid48Class() - { - JUnit48TestChecker tc = new JUnit48TestChecker( this.getClass().getClassLoader() ); - assertFalse( tc.accept( BasicTest2.class ) ); + public void notValid48Class() { + JUnit48TestChecker tc = new JUnit48TestChecker(this.getClass().getClassLoader()); + assertFalse(tc.accept(BasicTest2.class)); } /** * */ - @RunWith( Enclosed.class ) - public abstract static class BasicTest - { + @RunWith(Enclosed.class) + public abstract static class BasicTest { /** * */ - public static class InnerTest - { + public static class InnerTest { @Test - public void testSomething() - { - } + public void testSomething() {} } } /** * */ - @RunWith( Parameterized.class ) - public abstract static class BasicTest2 - { + @RunWith(Parameterized.class) + public abstract static class BasicTest2 { /** * */ - public static class InnerTest - { + public static class InnerTest { @Test - public void testSomething() - { - } + public void testSomething() {} } } } diff --git a/surefire-providers/common-junit48/src/test/java/org/apache/maven/surefire/common/junit48/JUnit4SuiteTest.java b/surefire-providers/common-junit48/src/test/java/org/apache/maven/surefire/common/junit48/JUnit4SuiteTest.java index 191e1e8f98..1233d889b6 100644 --- a/surefire-providers/common-junit48/src/test/java/org/apache/maven/surefire/common/junit48/JUnit4SuiteTest.java +++ b/surefire-providers/common-junit48/src/test/java/org/apache/maven/surefire/common/junit48/JUnit4SuiteTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.common.junit48; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.common.junit48; import junit.framework.JUnit4TestAdapter; import junit.framework.Test; @@ -30,14 +29,12 @@ * @author Tibor Digana (tibor17) * @since 2.19 */ -public class JUnit4SuiteTest extends TestCase -{ - public static Test suite() - { +public class JUnit4SuiteTest extends TestCase { + public static Test suite() { TestSuite suite = new TestSuite(); - suite.addTestSuite( JUnit48ReflectorTest.class ); - suite.addTest( new JUnit4TestAdapter( JUnit48TestCheckerTest.class ) ); - suite.addTest( new JUnit4TestAdapter( FilterFactoryTest.class ) ); + suite.addTestSuite(JUnit48ReflectorTest.class); + suite.addTest(new JUnit4TestAdapter(JUnit48TestCheckerTest.class)); + suite.addTest(new JUnit4TestAdapter(FilterFactoryTest.class)); return suite; } } diff --git a/surefire-providers/common-junit48/src/test/java/org/apache/maven/surefire/common/junit48/tests/ATest.java b/surefire-providers/common-junit48/src/test/java/org/apache/maven/surefire/common/junit48/tests/ATest.java index 4a9e17a0f2..c247fb7291 100644 --- a/surefire-providers/common-junit48/src/test/java/org/apache/maven/surefire/common/junit48/tests/ATest.java +++ b/surefire-providers/common-junit48/src/test/java/org/apache/maven/surefire/common/junit48/tests/ATest.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.common.junit48.tests; /* @@ -22,6 +40,4 @@ /** * */ -public class ATest -{ -} +public class ATest {} diff --git a/surefire-providers/common-junit48/src/test/java/org/apache/maven/surefire/common/junit48/tests/a/ATest.java b/surefire-providers/common-junit48/src/test/java/org/apache/maven/surefire/common/junit48/tests/a/ATest.java index 28e6e1cd18..08ca203eef 100644 --- a/surefire-providers/common-junit48/src/test/java/org/apache/maven/surefire/common/junit48/tests/a/ATest.java +++ b/surefire-providers/common-junit48/src/test/java/org/apache/maven/surefire/common/junit48/tests/a/ATest.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.common.junit48.tests.a; /* @@ -22,6 +40,4 @@ /** * */ -public class ATest -{ -} +public class ATest {} diff --git a/surefire-providers/common-junit48/src/test/java/org/apache/maven/surefire/common/junit48/tests/group/ABCParameterizedTest.java b/surefire-providers/common-junit48/src/test/java/org/apache/maven/surefire/common/junit48/tests/group/ABCParameterizedTest.java index a1cd44a04f..235c3418f0 100644 --- a/surefire-providers/common-junit48/src/test/java/org/apache/maven/surefire/common/junit48/tests/group/ABCParameterizedTest.java +++ b/surefire-providers/common-junit48/src/test/java/org/apache/maven/surefire/common/junit48/tests/group/ABCParameterizedTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.common.junit48.tests.group; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,10 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.common.junit48.tests.group; + +import java.util.Arrays; +import java.util.List; import org.apache.maven.surefire.common.junit48.tests.group.marker.CategoryA; import org.junit.Test; @@ -25,39 +27,25 @@ import org.junit.runner.RunWith; import org.junit.runners.Parameterized; -import java.util.Arrays; -import java.util.List; - /** * ABCParameterizedTest. */ -@Category( CategoryA.class ) -@RunWith( Parameterized.class ) -public class ABCParameterizedTest - extends AbstractBCTest -{ +@Category(CategoryA.class) +@RunWith(Parameterized.class) +public class ABCParameterizedTest extends AbstractBCTest { @Parameterized.Parameters - public static List data() - { - return Arrays.asList( - new Object[][] { - { 0 }, - { 1 }, - { 6 } - } ); + public static List data() { + return Arrays.asList(new Object[][] {{0}, {1}, {6}}); } private int number; - public ABCParameterizedTest( int number ) - { + public ABCParameterizedTest(int number) { this.number = number; } @Test - public void abc() - { - System.out.println( "ABCTest#abc(" + number + ")" ); + public void abc() { + System.out.println("ABCTest#abc(" + number + ")"); } - } diff --git a/surefire-providers/common-junit48/src/test/java/org/apache/maven/surefire/common/junit48/tests/group/ABCTest.java b/surefire-providers/common-junit48/src/test/java/org/apache/maven/surefire/common/junit48/tests/group/ABCTest.java index 63749aa10f..780b4c67cf 100644 --- a/surefire-providers/common-junit48/src/test/java/org/apache/maven/surefire/common/junit48/tests/group/ABCTest.java +++ b/surefire-providers/common-junit48/src/test/java/org/apache/maven/surefire/common/junit48/tests/group/ABCTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.common.junit48.tests.group; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.common.junit48.tests.group; import org.apache.maven.surefire.common.junit48.tests.group.marker.CategoryA; import org.junit.Test; @@ -26,15 +25,11 @@ /** * ABCTest. */ -@Category( CategoryA.class ) -public class ABCTest - extends AbstractBCTest -{ +@Category(CategoryA.class) +public class ABCTest extends AbstractBCTest { @Test - public void abc() - { - System.out.println( "ABCTest#abc" ); + public void abc() { + System.out.println("ABCTest#abc"); } - } diff --git a/surefire-providers/common-junit48/src/test/java/org/apache/maven/surefire/common/junit48/tests/group/ABMethodTest.java b/surefire-providers/common-junit48/src/test/java/org/apache/maven/surefire/common/junit48/tests/group/ABMethodTest.java index 5146c55330..a4c693060a 100644 --- a/surefire-providers/common-junit48/src/test/java/org/apache/maven/surefire/common/junit48/tests/group/ABMethodTest.java +++ b/surefire-providers/common-junit48/src/test/java/org/apache/maven/surefire/common/junit48/tests/group/ABMethodTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.common.junit48.tests.group; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.common.junit48.tests.group; import org.apache.maven.surefire.common.junit48.tests.group.marker.CategoryA; import org.apache.maven.surefire.common.junit48.tests.group.marker.CategoryB; @@ -27,21 +26,17 @@ /** * ABMethodTest. */ -@Category( CategoryA.class ) -public class ABMethodTest -{ +@Category(CategoryA.class) +public class ABMethodTest { @Test - public void a() - { - System.out.println( "ATest#a" ); + public void a() { + System.out.println("ATest#a"); } - @Category( CategoryB.class ) + @Category(CategoryB.class) @Test - public void b() - { - System.out.println( "ATest#b" ); + public void b() { + System.out.println("ATest#b"); } - } diff --git a/surefire-providers/common-junit48/src/test/java/org/apache/maven/surefire/common/junit48/tests/group/ATest.java b/surefire-providers/common-junit48/src/test/java/org/apache/maven/surefire/common/junit48/tests/group/ATest.java index 3f2f9d5a83..ce3244b9ad 100644 --- a/surefire-providers/common-junit48/src/test/java/org/apache/maven/surefire/common/junit48/tests/group/ATest.java +++ b/surefire-providers/common-junit48/src/test/java/org/apache/maven/surefire/common/junit48/tests/group/ATest.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.common.junit48.tests.group; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.common.junit48.tests.group; import org.apache.maven.surefire.common.junit48.tests.group.marker.CategoryA; import org.junit.Test; @@ -26,14 +25,11 @@ /** * ATest. */ -@Category( CategoryA.class ) -public class ATest -{ +@Category(CategoryA.class) +public class ATest { @Test - public void a() - { - System.out.println( "ATest#a" ); + public void a() { + System.out.println("ATest#a"); } - } diff --git a/surefire-providers/common-junit48/src/test/java/org/apache/maven/surefire/common/junit48/tests/group/AbstractBCTest.java b/surefire-providers/common-junit48/src/test/java/org/apache/maven/surefire/common/junit48/tests/group/AbstractBCTest.java index 8cef8abdd5..2f01e69032 100644 --- a/surefire-providers/common-junit48/src/test/java/org/apache/maven/surefire/common/junit48/tests/group/AbstractBCTest.java +++ b/surefire-providers/common-junit48/src/test/java/org/apache/maven/surefire/common/junit48/tests/group/AbstractBCTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.common.junit48.tests.group; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.common.junit48.tests.group; import org.apache.maven.surefire.common.junit48.tests.group.marker.CategoryB; import org.junit.Test; @@ -26,15 +25,11 @@ /** * AbstractBCTest. */ -@Category( CategoryB.class ) -public abstract class AbstractBCTest - extends AbstractCTest -{ +@Category(CategoryB.class) +public abstract class AbstractBCTest extends AbstractCTest { @Test - public void pb() - { - System.out.println( "AbstractBCTest#pb" ); + public void pb() { + System.out.println("AbstractBCTest#pb"); } - } diff --git a/surefire-providers/common-junit48/src/test/java/org/apache/maven/surefire/common/junit48/tests/group/AbstractCTest.java b/surefire-providers/common-junit48/src/test/java/org/apache/maven/surefire/common/junit48/tests/group/AbstractCTest.java index 942f9157b4..083dd0b47a 100644 --- a/surefire-providers/common-junit48/src/test/java/org/apache/maven/surefire/common/junit48/tests/group/AbstractCTest.java +++ b/surefire-providers/common-junit48/src/test/java/org/apache/maven/surefire/common/junit48/tests/group/AbstractCTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.common.junit48.tests.group; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.common.junit48.tests.group; import org.apache.maven.surefire.common.junit48.tests.group.marker.CategoryC; import org.junit.Test; @@ -26,14 +25,11 @@ /** * AbstractCTest. */ -@Category( CategoryC.class ) -public abstract class AbstractCTest -{ +@Category(CategoryC.class) +public abstract class AbstractCTest { @Test - public void pc() - { - System.out.println( "AbstractCTest#pc" ); + public void pc() { + System.out.println("AbstractCTest#pc"); } - } diff --git a/surefire-providers/common-junit48/src/test/java/org/apache/maven/surefire/common/junit48/tests/group/BBCTest.java b/surefire-providers/common-junit48/src/test/java/org/apache/maven/surefire/common/junit48/tests/group/BBCTest.java index e48cbec97c..452adc2a86 100644 --- a/surefire-providers/common-junit48/src/test/java/org/apache/maven/surefire/common/junit48/tests/group/BBCTest.java +++ b/surefire-providers/common-junit48/src/test/java/org/apache/maven/surefire/common/junit48/tests/group/BBCTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.common.junit48.tests.group; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.common.junit48.tests.group; import org.apache.maven.surefire.common.junit48.tests.group.marker.CategoryB; import org.junit.Test; @@ -26,15 +25,11 @@ /** * BBCTest. */ -@Category( CategoryB.class ) -public class BBCTest - extends AbstractBCTest -{ +@Category(CategoryB.class) +public class BBCTest extends AbstractBCTest { @Test - public void bbc() - { - System.out.println( "BBCTest#bbc" ); + public void bbc() { + System.out.println("BBCTest#bbc"); } - } diff --git a/surefire-providers/common-junit48/src/test/java/org/apache/maven/surefire/common/junit48/tests/group/BCTest.java b/surefire-providers/common-junit48/src/test/java/org/apache/maven/surefire/common/junit48/tests/group/BCTest.java index 0cd859cde0..ce687e6a6d 100644 --- a/surefire-providers/common-junit48/src/test/java/org/apache/maven/surefire/common/junit48/tests/group/BCTest.java +++ b/surefire-providers/common-junit48/src/test/java/org/apache/maven/surefire/common/junit48/tests/group/BCTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.common.junit48.tests.group; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,20 +16,17 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.common.junit48.tests.group; import org.junit.Test; /** * BCTest. */ -public class BCTest - extends AbstractBCTest -{ +public class BCTest extends AbstractBCTest { @Test - public void bc() - { - System.out.println( "BCTest#bc" ); + public void bc() { + System.out.println("BCTest#bc"); } - } diff --git a/surefire-providers/common-junit48/src/test/java/org/apache/maven/surefire/common/junit48/tests/group/BTest.java b/surefire-providers/common-junit48/src/test/java/org/apache/maven/surefire/common/junit48/tests/group/BTest.java index 126678d0dc..b20f45dab1 100644 --- a/surefire-providers/common-junit48/src/test/java/org/apache/maven/surefire/common/junit48/tests/group/BTest.java +++ b/surefire-providers/common-junit48/src/test/java/org/apache/maven/surefire/common/junit48/tests/group/BTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.common.junit48.tests.group; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.common.junit48.tests.group; import org.apache.maven.surefire.common.junit48.tests.group.marker.CategoryB; import org.junit.Test; @@ -26,14 +25,11 @@ /** * BTest. */ -@Category( CategoryB.class ) -public class BTest -{ +@Category(CategoryB.class) +public class BTest { @Test - public void b() - { - System.out.println( "BTest#b" ); + public void b() { + System.out.println("BTest#b"); } - } diff --git a/surefire-providers/common-junit48/src/test/java/org/apache/maven/surefire/common/junit48/tests/group/UncategorizedTest.java b/surefire-providers/common-junit48/src/test/java/org/apache/maven/surefire/common/junit48/tests/group/UncategorizedTest.java index 92a4a7ac88..f1cdeaf029 100644 --- a/surefire-providers/common-junit48/src/test/java/org/apache/maven/surefire/common/junit48/tests/group/UncategorizedTest.java +++ b/surefire-providers/common-junit48/src/test/java/org/apache/maven/surefire/common/junit48/tests/group/UncategorizedTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.common.junit48.tests.group; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,19 +16,17 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.common.junit48.tests.group; import org.junit.Test; /** * UncategorizedTest. */ -public class UncategorizedTest -{ +public class UncategorizedTest { @Test - public void a() - { - System.out.println( "Uncategorized#a" ); + public void a() { + System.out.println("Uncategorized#a"); } - } diff --git a/surefire-providers/common-junit48/src/test/java/org/apache/maven/surefire/common/junit48/tests/group/marker/CategoryA.java b/surefire-providers/common-junit48/src/test/java/org/apache/maven/surefire/common/junit48/tests/group/marker/CategoryA.java index 5d69a128f4..ea40829b4f 100644 --- a/surefire-providers/common-junit48/src/test/java/org/apache/maven/surefire/common/junit48/tests/group/marker/CategoryA.java +++ b/surefire-providers/common-junit48/src/test/java/org/apache/maven/surefire/common/junit48/tests/group/marker/CategoryA.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.common.junit48.tests.group.marker; /* @@ -22,6 +40,4 @@ /** * CategoryA marker. */ -public interface CategoryA -{ -} +public interface CategoryA {} diff --git a/surefire-providers/common-junit48/src/test/java/org/apache/maven/surefire/common/junit48/tests/group/marker/CategoryB.java b/surefire-providers/common-junit48/src/test/java/org/apache/maven/surefire/common/junit48/tests/group/marker/CategoryB.java index 380b895cc7..95e353e3c1 100644 --- a/surefire-providers/common-junit48/src/test/java/org/apache/maven/surefire/common/junit48/tests/group/marker/CategoryB.java +++ b/surefire-providers/common-junit48/src/test/java/org/apache/maven/surefire/common/junit48/tests/group/marker/CategoryB.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.common.junit48.tests.group.marker; /* @@ -22,6 +40,4 @@ /** * CategoryB marker. */ -public interface CategoryB -{ -} +public interface CategoryB {} diff --git a/surefire-providers/common-junit48/src/test/java/org/apache/maven/surefire/common/junit48/tests/group/marker/CategoryC.java b/surefire-providers/common-junit48/src/test/java/org/apache/maven/surefire/common/junit48/tests/group/marker/CategoryC.java index df16556ae3..6b84717335 100644 --- a/surefire-providers/common-junit48/src/test/java/org/apache/maven/surefire/common/junit48/tests/group/marker/CategoryC.java +++ b/surefire-providers/common-junit48/src/test/java/org/apache/maven/surefire/common/junit48/tests/group/marker/CategoryC.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.common.junit48.tests.group.marker; /* @@ -22,6 +40,4 @@ /** * CategoryC marker. */ -public interface CategoryC -{ -} +public interface CategoryC {} diff --git a/surefire-providers/common-junit48/src/test/java/org/apache/maven/surefire/common/junit48/tests/pt/PT.java b/surefire-providers/common-junit48/src/test/java/org/apache/maven/surefire/common/junit48/tests/pt/PT.java index a6f1df47e6..43a6897bab 100644 --- a/surefire-providers/common-junit48/src/test/java/org/apache/maven/surefire/common/junit48/tests/pt/PT.java +++ b/surefire-providers/common-junit48/src/test/java/org/apache/maven/surefire/common/junit48/tests/pt/PT.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.common.junit48.tests.pt; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,72 +16,51 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.common.junit48.tests.pt; + +import java.util.Arrays; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; -import java.util.Arrays; - /** * */ -@RunWith( Parameterized.class ) -public class PT -{ +@RunWith(Parameterized.class) +public class PT { - public PT( String x ) - { - } + public PT(String x) {} @Parameterized.Parameters - public static Iterable data() - { - return Arrays.asList( new Object[][]{ { "x" }, { "y" } } ); + public static Iterable data() { + return Arrays.asList(new Object[][] {{"x"}, {"y"}}); } @Test - public void testAA() - { - } + public void testAA() {} @Test - public void testB5() - { - } + public void testB5() {} @Test - public void testCX() - { - } + public void testCX() {} @Test - public void testCY() - { - } + public void testCY() {} @Test - public void w12T34() - { - } + public void w12T34() {} @Test - public void x12T34() - { - } + public void x12T34() {} @Test - public void x12T35() - { - } + public void x12T35() {} @Test - public void x12t36() - { - } + public void x12t36() {} @Test - public void y12t34() - { - } + public void y12t34() {} } diff --git a/surefire-providers/pom.xml b/surefire-providers/pom.xml index f67fbde260..4422055d79 100644 --- a/surefire-providers/pom.xml +++ b/surefire-providers/pom.xml @@ -17,7 +17,6 @@ ~ specific language governing permissions and limitations ~ under the License. --> - 4.0.0 @@ -62,11 +61,11 @@ org.apache.maven.surefire surefire-shadefire - 3.0.0-M7 + 3.0.0-M7 + - diff --git a/surefire-providers/surefire-junit-platform/pom.xml b/surefire-providers/surefire-junit-platform/pom.xml index c6197919a5..abb6b6d651 100644 --- a/surefire-providers/surefire-junit-platform/pom.xml +++ b/surefire-providers/surefire-junit-platform/pom.xml @@ -1,3 +1,4 @@ + - - 4.0.0 - - - org.apache.maven.surefire - surefire-providers - 3.0.0-M10-SNAPSHOT - - - surefire-junit-platform + 4.0.0 - SureFire JUnit Platform Runner - SureFire JUnit Platform Runner + + org.apache.maven.surefire + surefire-providers + 3.0.0-M10-SNAPSHOT + - - - Konstantin Lutovich - - Contributed to the original provider implementation - - - - Shintaro Katafuchi - - Contributed to the original provider implementation - - - - Sam Brannen - - Contributed to the original provider implementation - - - - Stefan Bechtold - - Contributed to the original provider implementation - - - - Marc Philipp - - Contributed to the original provider implementation - - - - Matthias Merdes - - Contributed to the original provider implementation - - - - Johannes Link - - Contributed to the original provider implementation - - - + surefire-junit-platform - - - org.apache.maven.surefire - common-java5 - ${project.version} - - - org.junit.platform - junit-platform-launcher - - - org.junit.jupiter - junit-jupiter-engine - test - - - org.junit.jupiter - junit-jupiter-params - test - - - org.mockito - mockito-core - test - - - org.powermock - powermock-reflect - test - - + SureFire JUnit Platform Runner + SureFire JUnit Platform Runner - - - - org.jacoco - jacoco-maven-plugin - - - jacoco-agent - - prepare-agent - - - - - jacoco.agent - - - - maven-surefire-plugin - - ${jvm.args.tests} ${jacoco.agent} - true - - **/JUnit47SuiteTest.java - - - - - + + + Konstantin Lutovich + + Contributed to the original provider implementation + + + + Shintaro Katafuchi + + Contributed to the original provider implementation + + + + Sam Brannen + + Contributed to the original provider implementation + + + + Stefan Bechtold + + Contributed to the original provider implementation + + + + Marc Philipp + + Contributed to the original provider implementation + + + + Matthias Merdes + + Contributed to the original provider implementation + + + + Johannes Link + + Contributed to the original provider implementation + + + surefire-3.0.0-M8 + + + + org.apache.maven.surefire + common-java5 + ${project.version} + + + org.junit.platform + junit-platform-launcher + + + org.junit.jupiter + junit-jupiter-engine + test + + + org.junit.jupiter + junit-jupiter-params + test + + + org.mockito + mockito-core + test + + + org.powermock + powermock-reflect + test + + + + + + + org.jacoco + jacoco-maven-plugin + + jacoco.agent + + + + jacoco-agent + + prepare-agent + + + + + + maven-surefire-plugin + + ${jvm.args.tests} ${jacoco.agent} + true + + **/JUnit47SuiteTest.java + + + + + diff --git a/surefire-providers/surefire-junit-platform/src/main/java/org/apache/maven/surefire/junitplatform/JUnitPlatformProvider.java b/surefire-providers/surefire-junit-platform/src/main/java/org/apache/maven/surefire/junitplatform/JUnitPlatformProvider.java index ad2ec944d2..d401a465cf 100644 --- a/surefire-providers/surefire-junit-platform/src/main/java/org/apache/maven/surefire/junitplatform/JUnitPlatformProvider.java +++ b/surefire-providers/surefire-junit-platform/src/main/java/org/apache/maven/surefire/junitplatform/JUnitPlatformProvider.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.junitplatform; /* @@ -19,26 +37,6 @@ * under the License. */ -import static java.util.Arrays.stream; -import static java.util.Collections.emptyMap; -import static java.util.Optional.empty; -import static java.util.Optional.of; -import static java.util.logging.Level.WARNING; -import static java.util.stream.Collectors.toList; -import static org.apache.maven.surefire.api.booter.ProviderParameterNames.EXCLUDE_JUNIT5_ENGINES_PROP; -import static org.apache.maven.surefire.api.booter.ProviderParameterNames.INCLUDE_JUNIT5_ENGINES_PROP; -import static org.apache.maven.surefire.api.booter.ProviderParameterNames.TESTNG_EXCLUDEDGROUPS_PROP; -import static org.apache.maven.surefire.api.booter.ProviderParameterNames.TESTNG_GROUPS_PROP; -import static org.apache.maven.surefire.api.report.ConsoleOutputCapture.startCapture; -import static org.apache.maven.surefire.api.report.RunMode.NORMAL_RUN; -import static org.apache.maven.surefire.api.report.RunMode.RERUN_TEST_AFTER_FAILURE; -import static org.apache.maven.surefire.api.testset.TestListResolver.optionallyWildcardFilter; -import static org.apache.maven.surefire.api.util.TestsToRun.fromClass; -import static org.apache.maven.surefire.shared.utils.StringUtils.isBlank; -import static org.junit.platform.engine.discovery.DiscoverySelectors.selectClass; -import static org.junit.platform.engine.discovery.DiscoverySelectors.selectUniqueId; -import static org.junit.platform.launcher.core.LauncherDiscoveryRequestBuilder.request; - import java.io.IOException; import java.io.StringReader; import java.io.UncheckedIOException; @@ -70,14 +68,32 @@ import org.junit.platform.launcher.TestIdentifier; import org.junit.platform.launcher.core.LauncherDiscoveryRequestBuilder; +import static java.util.Arrays.stream; +import static java.util.Collections.emptyMap; +import static java.util.Optional.empty; +import static java.util.Optional.of; +import static java.util.logging.Level.WARNING; +import static java.util.stream.Collectors.toList; +import static org.apache.maven.surefire.api.booter.ProviderParameterNames.EXCLUDE_JUNIT5_ENGINES_PROP; +import static org.apache.maven.surefire.api.booter.ProviderParameterNames.INCLUDE_JUNIT5_ENGINES_PROP; +import static org.apache.maven.surefire.api.booter.ProviderParameterNames.TESTNG_EXCLUDEDGROUPS_PROP; +import static org.apache.maven.surefire.api.booter.ProviderParameterNames.TESTNG_GROUPS_PROP; +import static org.apache.maven.surefire.api.report.ConsoleOutputCapture.startCapture; +import static org.apache.maven.surefire.api.report.RunMode.NORMAL_RUN; +import static org.apache.maven.surefire.api.report.RunMode.RERUN_TEST_AFTER_FAILURE; +import static org.apache.maven.surefire.api.testset.TestListResolver.optionallyWildcardFilter; +import static org.apache.maven.surefire.api.util.TestsToRun.fromClass; +import static org.apache.maven.surefire.shared.utils.StringUtils.isBlank; +import static org.junit.platform.engine.discovery.DiscoverySelectors.selectClass; +import static org.junit.platform.engine.discovery.DiscoverySelectors.selectUniqueId; +import static org.junit.platform.launcher.core.LauncherDiscoveryRequestBuilder.request; + /** * JUnit 5 Platform Provider. * * @since 2.22.0 */ -public class JUnitPlatformProvider - extends AbstractProvider -{ +public class JUnitPlatformProvider extends AbstractProvider { static final String CONFIGURATION_PARAMETERS = "configurationParameters"; private final ProviderParameters parameters; @@ -88,13 +104,11 @@ public class JUnitPlatformProvider private final Map configurationParameters; - public JUnitPlatformProvider( ProviderParameters parameters ) - { - this( parameters, new LazyLauncher() ); + public JUnitPlatformProvider(ProviderParameters parameters) { + this(parameters, new LazyLauncher()); } - JUnitPlatformProvider( ProviderParameters parameters, Launcher launcher ) - { + JUnitPlatformProvider(ProviderParameters parameters, Launcher launcher) { this.parameters = parameters; this.launcher = launcher; filters = newFilters(); @@ -102,235 +116,180 @@ public JUnitPlatformProvider( ProviderParameters parameters ) } @Override - public Iterable> getSuites() - { - try - { + public Iterable> getSuites() { + try { return scanClasspath(); - } - finally - { + } finally { closeLauncher(); } } @Override - public RunResult invoke( Object forkTestSet ) - throws TestSetFailedException, ReporterException - { + public RunResult invoke(Object forkTestSet) throws TestSetFailedException, ReporterException { ReporterFactory reporterFactory = parameters.getReporterFactory(); final RunResult runResult; - try - { - RunListenerAdapter adapter = new RunListenerAdapter( reporterFactory.createTestReportListener() ); - adapter.setRunMode( NORMAL_RUN ); - startCapture( adapter ); + try { + RunListenerAdapter adapter = new RunListenerAdapter(reporterFactory.createTestReportListener()); + adapter.setRunMode(NORMAL_RUN); + startCapture(adapter); setupJunitLogger(); - if ( forkTestSet instanceof TestsToRun ) - { - invokeAllTests( (TestsToRun) forkTestSet, adapter ); - } - else if ( forkTestSet instanceof Class ) - { - invokeAllTests( fromClass( ( Class ) forkTestSet ), adapter ); - } - else if ( forkTestSet == null ) - { - invokeAllTests( scanClasspath(), adapter ); + if (forkTestSet instanceof TestsToRun) { + invokeAllTests((TestsToRun) forkTestSet, adapter); + } else if (forkTestSet instanceof Class) { + invokeAllTests(fromClass((Class) forkTestSet), adapter); + } else if (forkTestSet == null) { + invokeAllTests(scanClasspath(), adapter); + } else { + throw new IllegalArgumentException("Unexpected value of forkTestSet: " + forkTestSet); } - else - { - throw new IllegalArgumentException( - "Unexpected value of forkTestSet: " + forkTestSet ); - } - } - finally - { + } finally { runResult = reporterFactory.close(); } return runResult; } - private static void setupJunitLogger() - { - Logger logger = Logger.getLogger( "org.junit" ); - if ( logger.getLevel() == null ) - { - logger.setLevel( WARNING ); + private static void setupJunitLogger() { + Logger logger = Logger.getLogger("org.junit"); + if (logger.getLevel() == null) { + logger.setLevel(WARNING); } } - private TestsToRun scanClasspath() - { - TestPlanScannerFilter filter = new TestPlanScannerFilter( launcher, filters ); + private TestsToRun scanClasspath() { + TestPlanScannerFilter filter = new TestPlanScannerFilter(launcher, filters); ScanResult scanResult = parameters.getScanResult(); - TestsToRun scannedClasses = scanResult.applyFilter( filter, parameters.getTestClassLoader() ); - return parameters.getRunOrderCalculator().orderTestClasses( scannedClasses ); + TestsToRun scannedClasses = scanResult.applyFilter(filter, parameters.getTestClassLoader()); + return parameters.getRunOrderCalculator().orderTestClasses(scannedClasses); } - private void invokeAllTests( TestsToRun testsToRun, RunListenerAdapter adapter ) - { - try - { - execute( testsToRun, adapter ); - } - finally - { + private void invokeAllTests(TestsToRun testsToRun, RunListenerAdapter adapter) { + try { + execute(testsToRun, adapter); + } finally { closeLauncher(); } // Rerun failing tests if requested int count = parameters.getTestRequest().getRerunFailingTestsCount(); - if ( count > 0 && adapter.hasFailingTests() ) - { - adapter.setRunMode( RERUN_TEST_AFTER_FAILURE ); - for ( int i = 0; i < count; i++ ) - { - try - { + if (count > 0 && adapter.hasFailingTests()) { + adapter.setRunMode(RERUN_TEST_AFTER_FAILURE); + for (int i = 0; i < count; i++) { + try { // Replace the "discoveryRequest" so that it only specifies the failing tests - LauncherDiscoveryRequest discoveryRequest = - buildLauncherDiscoveryRequestForRerunFailures( adapter ); + LauncherDiscoveryRequest discoveryRequest = buildLauncherDiscoveryRequestForRerunFailures(adapter); // Reset adapter's recorded failures and invoke the failed tests again adapter.reset(); - launcher.execute( discoveryRequest, adapter ); + launcher.execute(discoveryRequest, adapter); // If no tests fail in the rerun, we're done - if ( !adapter.hasFailingTests() ) - { + if (!adapter.hasFailingTests()) { break; } - } - finally - { + } finally { closeLauncher(); } } } } - private void execute( TestsToRun testsToRun, RunListenerAdapter adapter ) - { - if ( testsToRun.allowEagerReading() ) - { + private void execute(TestsToRun testsToRun, RunListenerAdapter adapter) { + if (testsToRun.allowEagerReading()) { List selectors = new ArrayList<>(); - testsToRun.iterator() - .forEachRemaining( c -> selectors.add( selectClass( c.getName() ) ) ); + testsToRun.iterator().forEachRemaining(c -> selectors.add(selectClass(c.getName()))); LauncherDiscoveryRequestBuilder builder = request() - .filters( filters ) - .configurationParameters( configurationParameters ) - .selectors( selectors ); + .filters(filters) + .configurationParameters(configurationParameters) + .selectors(selectors); - launcher.execute( builder.build(), adapter ); - } - else - { - testsToRun.iterator() - .forEachRemaining( c -> - { - LauncherDiscoveryRequestBuilder builder = request() - .filters( filters ) - .configurationParameters( configurationParameters ) - .selectors( selectClass( c.getName() ) ); - launcher.execute( builder.build(), adapter ); - } ); + launcher.execute(builder.build(), adapter); + } else { + testsToRun.iterator().forEachRemaining(c -> { + LauncherDiscoveryRequestBuilder builder = request() + .filters(filters) + .configurationParameters(configurationParameters) + .selectors(selectClass(c.getName())); + launcher.execute(builder.build(), adapter); + }); } } - - private void closeLauncher() - { - if ( launcher instanceof AutoCloseable ) - { - try - { - ( (AutoCloseable) launcher ).close(); - } - catch ( Exception e ) - { - throw new SurefireReflectionException( e ); + + private void closeLauncher() { + if (launcher instanceof AutoCloseable) { + try { + ((AutoCloseable) launcher).close(); + } catch (Exception e) { + throw new SurefireReflectionException(e); } } } - private LauncherDiscoveryRequest buildLauncherDiscoveryRequestForRerunFailures( RunListenerAdapter adapter ) - { - LauncherDiscoveryRequestBuilder builder = request().filters( filters ).configurationParameters( - configurationParameters ); + private LauncherDiscoveryRequest buildLauncherDiscoveryRequestForRerunFailures(RunListenerAdapter adapter) { + LauncherDiscoveryRequestBuilder builder = + request().filters(filters).configurationParameters(configurationParameters); // Iterate over recorded failures - for ( TestIdentifier identifier : new LinkedHashSet<>( adapter.getFailures().keySet() ) ) - { - builder.selectors( selectUniqueId( identifier.getUniqueId() ) ); + for (TestIdentifier identifier : + new LinkedHashSet<>(adapter.getFailures().keySet())) { + builder.selectors(selectUniqueId(identifier.getUniqueId())); } return builder.build(); } - private Filter[] newFilters() - { + private Filter[] newFilters() { List> filters = new ArrayList<>(); - getPropertiesList( TESTNG_GROUPS_PROP ) - .map( TagFilter::includeTags ) - .ifPresent( filters::add ); + getPropertiesList(TESTNG_GROUPS_PROP).map(TagFilter::includeTags).ifPresent(filters::add); - getPropertiesList( TESTNG_EXCLUDEDGROUPS_PROP ) - .map( TagFilter::excludeTags ) - .ifPresent( filters::add ); + getPropertiesList(TESTNG_EXCLUDEDGROUPS_PROP) + .map(TagFilter::excludeTags) + .ifPresent(filters::add); - of( optionallyWildcardFilter( parameters.getTestRequest().getTestListResolver() ) ) - .filter( f -> !f.isEmpty() ) - .filter( f -> !f.isWildcard() ) - .map( TestMethodFilter::new ) - .ifPresent( filters::add ); + of(optionallyWildcardFilter(parameters.getTestRequest().getTestListResolver())) + .filter(f -> !f.isEmpty()) + .filter(f -> !f.isWildcard()) + .map(TestMethodFilter::new) + .ifPresent(filters::add); - getPropertiesList( INCLUDE_JUNIT5_ENGINES_PROP ) - .map( EngineFilter::includeEngines ) - .ifPresent( filters::add ); + getPropertiesList(INCLUDE_JUNIT5_ENGINES_PROP) + .map(EngineFilter::includeEngines) + .ifPresent(filters::add); - getPropertiesList( EXCLUDE_JUNIT5_ENGINES_PROP ) - .map( EngineFilter::excludeEngines ) - .ifPresent( filters::add ); + getPropertiesList(EXCLUDE_JUNIT5_ENGINES_PROP) + .map(EngineFilter::excludeEngines) + .ifPresent(filters::add); - return filters.toArray( new Filter[ filters.size() ] ); + return filters.toArray(new Filter[filters.size()]); } - Filter[] getFilters() - { + Filter[] getFilters() { return filters; } - private Map newConfigurationParameters() - { - String content = parameters.getProviderProperties().get( CONFIGURATION_PARAMETERS ); - if ( content == null ) - { + private Map newConfigurationParameters() { + String content = parameters.getProviderProperties().get(CONFIGURATION_PARAMETERS); + if (content == null) { return emptyMap(); } - try ( StringReader reader = new StringReader( content ) ) - { + try (StringReader reader = new StringReader(content)) { Map result = new HashMap<>(); Properties props = new Properties(); - props.load( reader ); - props.stringPropertyNames() - .forEach( key -> result.put( key, props.getProperty( key ) ) ); + props.load(reader); + props.stringPropertyNames().forEach(key -> result.put(key, props.getProperty(key))); return result; - } - catch ( IOException e ) - { - throw new UncheckedIOException( "Error reading " + CONFIGURATION_PARAMETERS, e ); + } catch (IOException e) { + throw new UncheckedIOException("Error reading " + CONFIGURATION_PARAMETERS, e); } } - Map getConfigurationParameters() - { + Map getConfigurationParameters() { return configurationParameters; } - private Optional> getPropertiesList( String key ) - { - String property = parameters.getProviderProperties().get( key ); - return isBlank( property ) ? empty() - : of( stream( property.split( "[,]+" ) ) - .filter( StringUtils::isNotBlank ) - .map( String::trim ) - .collect( toList() ) ); + private Optional> getPropertiesList(String key) { + String property = parameters.getProviderProperties().get(key); + return isBlank(property) + ? empty() + : of(stream(property.split("[,]+")) + .filter(StringUtils::isNotBlank) + .map(String::trim) + .collect(toList())); } } diff --git a/surefire-providers/surefire-junit-platform/src/main/java/org/apache/maven/surefire/junitplatform/LazyLauncher.java b/surefire-providers/surefire-junit-platform/src/main/java/org/apache/maven/surefire/junitplatform/LazyLauncher.java index 6a1a3b3b38..441f21faaa 100644 --- a/surefire-providers/surefire-junit-platform/src/main/java/org/apache/maven/surefire/junitplatform/LazyLauncher.java +++ b/surefire-providers/surefire-junit-platform/src/main/java/org/apache/maven/surefire/junitplatform/LazyLauncher.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.junitplatform; /* @@ -30,43 +48,34 @@ * Launcher proxy which delays the most possible the initialization of the real JUnit * Launcher in order to avoid stream/stdout corruption due to early logging. */ -class LazyLauncher implements Launcher, AutoCloseable -{ +class LazyLauncher implements Launcher, AutoCloseable { private AutoCloseable launcherSession; private Launcher launcher; @Override - public void registerTestExecutionListeners( TestExecutionListener... testExecutionListeners ) - { - launcher().registerTestExecutionListeners( testExecutionListeners ); + public void registerTestExecutionListeners(TestExecutionListener... testExecutionListeners) { + launcher().registerTestExecutionListeners(testExecutionListeners); } @Override - public TestPlan discover( LauncherDiscoveryRequest launcherDiscoveryRequest ) - { - return launcher().discover( launcherDiscoveryRequest ); + public TestPlan discover(LauncherDiscoveryRequest launcherDiscoveryRequest) { + return launcher().discover(launcherDiscoveryRequest); } @Override - public void execute( LauncherDiscoveryRequest launcherDiscoveryRequest, - TestExecutionListener... testExecutionListeners ) - { - launcher().execute( launcherDiscoveryRequest, testExecutionListeners ); + public void execute( + LauncherDiscoveryRequest launcherDiscoveryRequest, TestExecutionListener... testExecutionListeners) { + launcher().execute(launcherDiscoveryRequest, testExecutionListeners); } - private Launcher launcher() - { - if ( launcher == null ) - { - try - { - Class sessionClass = Class.forName( "org.junit.platform.launcher.LauncherSession" ); - launcherSession = ReflectionUtils.invokeGetter( LauncherFactory.class, null, "openSession" ); - launcher = ReflectionUtils.invokeGetter( sessionClass, launcherSession, "getLauncher" ); - } - catch ( ClassNotFoundException e ) - { + private Launcher launcher() { + if (launcher == null) { + try { + Class sessionClass = Class.forName("org.junit.platform.launcher.LauncherSession"); + launcherSession = ReflectionUtils.invokeGetter(LauncherFactory.class, null, "openSession"); + launcher = ReflectionUtils.invokeGetter(sessionClass, launcherSession, "getLauncher"); + } catch (ClassNotFoundException e) { launcher = LauncherFactory.create(); } } @@ -74,10 +83,8 @@ private Launcher launcher() } @Override - public void close() throws Exception - { - if ( launcherSession != null ) - { + public void close() throws Exception { + if (launcherSession != null) { launcherSession.close(); launcherSession = null; } diff --git a/surefire-providers/surefire-junit-platform/src/main/java/org/apache/maven/surefire/junitplatform/RunListenerAdapter.java b/surefire-providers/surefire-junit-platform/src/main/java/org/apache/maven/surefire/junitplatform/RunListenerAdapter.java index cafc934d05..c341f1c2cf 100644 --- a/surefire-providers/surefire-junit-platform/src/main/java/org/apache/maven/surefire/junitplatform/RunListenerAdapter.java +++ b/surefire-providers/surefire-junit-platform/src/main/java/org/apache/maven/surefire/junitplatform/RunListenerAdapter.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.junitplatform; /* @@ -19,13 +37,6 @@ * under the License. */ -import static java.util.Collections.emptyMap; -import static java.util.stream.Collectors.joining; -import static java.util.stream.Collectors.toList; -import static org.apache.maven.surefire.api.util.internal.ObjectUtils.systemProps; -import static org.apache.maven.surefire.shared.lang3.StringUtils.isNotBlank; -import static org.junit.platform.engine.TestExecutionResult.Status.FAILED; - import java.util.Collections; import java.util.List; import java.util.Map; @@ -37,15 +48,15 @@ import org.apache.maven.surefire.api.report.OutputReportEntry; import org.apache.maven.surefire.api.report.RunMode; +import org.apache.maven.surefire.api.report.SafeThrowable; +import org.apache.maven.surefire.api.report.SimpleReportEntry; +import org.apache.maven.surefire.api.report.StackTraceWriter; import org.apache.maven.surefire.api.report.TestOutputReceiver; import org.apache.maven.surefire.api.report.TestOutputReportEntry; -import org.apache.maven.surefire.report.ClassMethodIndexer; import org.apache.maven.surefire.api.report.TestReportListener; +import org.apache.maven.surefire.report.ClassMethodIndexer; import org.apache.maven.surefire.report.PojoStackTraceWriter; import org.apache.maven.surefire.report.RunModeSetter; -import org.apache.maven.surefire.api.report.SafeThrowable; -import org.apache.maven.surefire.api.report.SimpleReportEntry; -import org.apache.maven.surefire.api.report.StackTraceWriter; import org.junit.platform.engine.TestExecutionResult; import org.junit.platform.engine.TestSource; import org.junit.platform.engine.support.descriptor.ClassSource; @@ -54,12 +65,17 @@ import org.junit.platform.launcher.TestIdentifier; import org.junit.platform.launcher.TestPlan; +import static java.util.Collections.emptyMap; +import static java.util.stream.Collectors.joining; +import static java.util.stream.Collectors.toList; +import static org.apache.maven.surefire.api.util.internal.ObjectUtils.systemProps; +import static org.apache.maven.surefire.shared.lang3.StringUtils.isNotBlank; +import static org.junit.platform.engine.TestExecutionResult.Status.FAILED; + /** * @since 2.22.0 */ -final class RunListenerAdapter - implements TestExecutionListener, TestOutputReceiver, RunModeSetter -{ +final class RunListenerAdapter implements TestExecutionListener, TestOutputReceiver, RunModeSetter { private final ClassMethodIndexer classMethodIndexer = new ClassMethodIndexer(); private final ConcurrentMap testStartTime = new ConcurrentHashMap<>(); private final ConcurrentMap failures = new ConcurrentHashMap<>(); @@ -68,232 +84,218 @@ final class RunListenerAdapter private volatile TestPlan testPlan; private volatile RunMode runMode; - RunListenerAdapter( TestReportListener runListener ) - { + RunListenerAdapter(TestReportListener runListener) { this.runListener = runListener; } @Override - public void setRunMode( RunMode runMode ) - { + public void setRunMode(RunMode runMode) { this.runMode = runMode; } @Override - public void testPlanExecutionStarted( TestPlan testPlan ) - { + public void testPlanExecutionStarted(TestPlan testPlan) { this.testPlan = testPlan; } @Override - public void testPlanExecutionFinished( TestPlan testPlan ) - { + public void testPlanExecutionFinished(TestPlan testPlan) { this.testPlan = null; testStartTime.clear(); } @Override - public void executionStarted( TestIdentifier testIdentifier ) - { - runningTestIdentifiersByUniqueId.put( testIdentifier.getUniqueId(), testIdentifier ); - - if ( testIdentifier.isContainer() - && testIdentifier.getSource().filter( ClassSource.class::isInstance ).isPresent() ) - { - testStartTime.put( testIdentifier, System.currentTimeMillis() ); - runListener.testSetStarting( createReportEntry( testIdentifier ) ); - } - else if ( testIdentifier.isTest() ) - { - testStartTime.put( testIdentifier, System.currentTimeMillis() ); - runListener.testStarting( createReportEntry( testIdentifier ) ); + public void executionStarted(TestIdentifier testIdentifier) { + runningTestIdentifiersByUniqueId.put(testIdentifier.getUniqueId(), testIdentifier); + + if (testIdentifier.isContainer() + && testIdentifier + .getSource() + .filter(ClassSource.class::isInstance) + .isPresent()) { + testStartTime.put(testIdentifier, System.currentTimeMillis()); + runListener.testSetStarting(createReportEntry(testIdentifier)); + } else if (testIdentifier.isTest()) { + testStartTime.put(testIdentifier, System.currentTimeMillis()); + runListener.testStarting(createReportEntry(testIdentifier)); } } @Override - public void executionFinished( TestIdentifier testIdentifier, TestExecutionResult testExecutionResult ) - { + public void executionFinished(TestIdentifier testIdentifier, TestExecutionResult testExecutionResult) { boolean isClass = testIdentifier.isContainer() - && testIdentifier.getSource().filter( ClassSource.class::isInstance ).isPresent(); + && testIdentifier + .getSource() + .filter(ClassSource.class::isInstance) + .isPresent(); boolean isTest = testIdentifier.isTest(); boolean failed = testExecutionResult.getStatus() == FAILED; - boolean isAssertionError = testExecutionResult.getThrowable() - .filter( AssertionError.class::isInstance ).isPresent(); + boolean isAssertionError = testExecutionResult + .getThrowable() + .filter(AssertionError.class::isInstance) + .isPresent(); - boolean isRootContainer = testIdentifier.isContainer() && !testIdentifier.getParentId().isPresent(); + boolean isRootContainer = + testIdentifier.isContainer() && !testIdentifier.getParentId().isPresent(); - if ( failed || isClass || isTest ) - { - Integer elapsed = computeElapsedTime( testIdentifier ); - switch ( testExecutionResult.getStatus() ) - { + if (failed || isClass || isTest) { + Integer elapsed = computeElapsedTime(testIdentifier); + switch (testExecutionResult.getStatus()) { case ABORTED: - if ( isTest ) - { + if (isTest) { runListener.testAssumptionFailure( - createReportEntry( testIdentifier, testExecutionResult, elapsed ) ); - } - else - { - runListener.testSetCompleted( createReportEntry( testIdentifier, testExecutionResult, - systemProps(), null, elapsed ) ); + createReportEntry(testIdentifier, testExecutionResult, elapsed)); + } else { + runListener.testSetCompleted( + createReportEntry(testIdentifier, testExecutionResult, systemProps(), null, elapsed)); } break; case FAILED: - String reason = safeGetMessage( testExecutionResult.getThrowable().orElse( null ) ); - SimpleReportEntry reportEntry = createReportEntry( testIdentifier, testExecutionResult, - reason, elapsed ); - if ( isAssertionError ) - { - runListener.testFailed( reportEntry ); + String reason = + safeGetMessage(testExecutionResult.getThrowable().orElse(null)); + SimpleReportEntry reportEntry = + createReportEntry(testIdentifier, testExecutionResult, reason, elapsed); + if (isAssertionError) { + runListener.testFailed(reportEntry); + } else { + runListener.testError(reportEntry); } - else - { - runListener.testError( reportEntry ); - } - if ( isClass || isRootContainer ) - { - runListener.testSetCompleted( createReportEntry( testIdentifier, null, - systemProps(), null, elapsed ) ); + if (isClass || isRootContainer) { + runListener.testSetCompleted( + createReportEntry(testIdentifier, null, systemProps(), null, elapsed)); } - failures.put( testIdentifier, testExecutionResult ); + failures.put(testIdentifier, testExecutionResult); break; default: - if ( isTest ) - { - runListener.testSucceeded( createReportEntry( testIdentifier, null, elapsed ) ); - } - else - { + if (isTest) { + runListener.testSucceeded(createReportEntry(testIdentifier, null, elapsed)); + } else { runListener.testSetCompleted( - createReportEntry( testIdentifier, null, systemProps(), null, elapsed ) ); + createReportEntry(testIdentifier, null, systemProps(), null, elapsed)); } } } - runningTestIdentifiersByUniqueId.remove( testIdentifier.getUniqueId() ); + runningTestIdentifiersByUniqueId.remove(testIdentifier.getUniqueId()); } - private Integer computeElapsedTime( TestIdentifier testIdentifier ) - { - Long startTime = testStartTime.remove( testIdentifier ); + private Integer computeElapsedTime(TestIdentifier testIdentifier) { + Long startTime = testStartTime.remove(testIdentifier); long endTime = System.currentTimeMillis(); - return startTime == null ? null : (int) ( endTime - startTime ); + return startTime == null ? null : (int) (endTime - startTime); } - private Stream collectAllTestIdentifiersInHierarchy( TestIdentifier testIdentifier ) - { - return testIdentifier.getParentId() - .map( runningTestIdentifiersByUniqueId::get ) - .map( parentTestIdentifier -> - Stream.concat( Stream.of( parentTestIdentifier ), - collectAllTestIdentifiersInHierarchy( parentTestIdentifier ) ) ) - .orElseGet( Stream::empty ); + private Stream collectAllTestIdentifiersInHierarchy(TestIdentifier testIdentifier) { + return testIdentifier + .getParentId() + .map(runningTestIdentifiersByUniqueId::get) + .map(parentTestIdentifier -> Stream.concat( + Stream.of(parentTestIdentifier), collectAllTestIdentifiersInHierarchy(parentTestIdentifier))) + .orElseGet(Stream::empty); } - private String safeGetMessage( Throwable throwable ) - { - try - { - SafeThrowable t = throwable == null ? null : new SafeThrowable( throwable ); + private String safeGetMessage(Throwable throwable) { + try { + SafeThrowable t = throwable == null ? null : new SafeThrowable(throwable); return t == null ? null : t.getMessage(); - } - catch ( Throwable t ) - { + } catch (Throwable t) { return t.getMessage(); } } @Override - public void executionSkipped( TestIdentifier testIdentifier, String reason ) - { + public void executionSkipped(TestIdentifier testIdentifier, String reason) { boolean isClass = testIdentifier.isContainer() - && testIdentifier.getSource().filter( ClassSource.class::isInstance ).isPresent(); - - testStartTime.remove( testIdentifier ); - - if ( isClass ) - { - SimpleReportEntry report = createReportEntry( testIdentifier ); - runListener.testSetStarting( report ); - for ( TestIdentifier child : testPlan.getChildren( testIdentifier ) ) - { - runListener.testSkipped( createReportEntry( child, null, emptyMap(), reason, null ) ); + && testIdentifier + .getSource() + .filter(ClassSource.class::isInstance) + .isPresent(); + + testStartTime.remove(testIdentifier); + + if (isClass) { + SimpleReportEntry report = createReportEntry(testIdentifier); + runListener.testSetStarting(report); + for (TestIdentifier child : testPlan.getChildren(testIdentifier)) { + runListener.testSkipped(createReportEntry(child, null, emptyMap(), reason, null)); } - runListener.testSetCompleted( report ); - } - else - { - runListener.testSkipped( createReportEntry( testIdentifier, null, emptyMap(), reason, null ) ); + runListener.testSetCompleted(report); + } else { + runListener.testSkipped(createReportEntry(testIdentifier, null, emptyMap(), reason, null)); } } - private SimpleReportEntry createReportEntry( TestIdentifier testIdentifier, - TestExecutionResult testExecutionResult, - Map systemProperties, - String reason, - Integer elapsedTime ) - { - String[] classMethodName = toClassMethodName( testIdentifier ); + private SimpleReportEntry createReportEntry( + TestIdentifier testIdentifier, + TestExecutionResult testExecutionResult, + Map systemProperties, + String reason, + Integer elapsedTime) { + String[] classMethodName = toClassMethodName(testIdentifier); String className = classMethodName[0]; String classText = classMethodName[1]; - if ( Objects.equals( className, classText ) ) - { + if (Objects.equals(className, classText)) { classText = null; } boolean failed = testExecutionResult == null || testExecutionResult.getStatus() == FAILED; String methodName = failed || testIdentifier.isTest() ? classMethodName[2] : null; String methodText = failed || testIdentifier.isTest() ? classMethodName[3] : null; - if ( Objects.equals( methodName, methodText ) ) - { + if (Objects.equals(methodName, methodText)) { methodText = null; } StackTraceWriter stw = - testExecutionResult == null ? null : toStackTraceWriter( className, methodName, testExecutionResult ); - return new SimpleReportEntry( runMode, classMethodIndexer.indexClassMethod( className, methodName ), className, - classText, methodName, methodText, stw, elapsedTime, reason, systemProperties ); + testExecutionResult == null ? null : toStackTraceWriter(className, methodName, testExecutionResult); + return new SimpleReportEntry( + runMode, + classMethodIndexer.indexClassMethod(className, methodName), + className, + classText, + methodName, + methodText, + stw, + elapsedTime, + reason, + systemProperties); } - private SimpleReportEntry createReportEntry( TestIdentifier testIdentifier ) - { - return createReportEntry( testIdentifier, null, null ); + private SimpleReportEntry createReportEntry(TestIdentifier testIdentifier) { + return createReportEntry(testIdentifier, null, null); } - private SimpleReportEntry createReportEntry( TestIdentifier testIdentifier, - TestExecutionResult testExecutionResult, Integer elapsedTime ) - { - return createReportEntry( testIdentifier, testExecutionResult, emptyMap(), null, elapsedTime ); + private SimpleReportEntry createReportEntry( + TestIdentifier testIdentifier, TestExecutionResult testExecutionResult, Integer elapsedTime) { + return createReportEntry(testIdentifier, testExecutionResult, emptyMap(), null, elapsedTime); } - private SimpleReportEntry createReportEntry( TestIdentifier testIdentifier, - TestExecutionResult testExecutionResult, String reason, Integer elapsedTime ) - { - return createReportEntry( testIdentifier, testExecutionResult, emptyMap(), reason, elapsedTime ); + private SimpleReportEntry createReportEntry( + TestIdentifier testIdentifier, + TestExecutionResult testExecutionResult, + String reason, + Integer elapsedTime) { + return createReportEntry(testIdentifier, testExecutionResult, emptyMap(), reason, elapsedTime); } - private StackTraceWriter toStackTraceWriter( String realClassName, String realMethodName, - TestExecutionResult testExecutionResult ) - { - switch ( testExecutionResult.getStatus() ) - { + private StackTraceWriter toStackTraceWriter( + String realClassName, String realMethodName, TestExecutionResult testExecutionResult) { + switch (testExecutionResult.getStatus()) { case ABORTED: case FAILED: // Failed tests must have a StackTraceWriter, otherwise Surefire will fail - Throwable exception = testExecutionResult.getThrowable().orElse( null ); - return toStackTraceWriter( realClassName, realMethodName, exception ); + Throwable exception = testExecutionResult.getThrowable().orElse(null); + return toStackTraceWriter(realClassName, realMethodName, exception); default: - return testExecutionResult.getThrowable() - .map( t -> toStackTraceWriter( realClassName, realMethodName, t ) ) - .orElse( null ); + return testExecutionResult + .getThrowable() + .map(t -> toStackTraceWriter(realClassName, realMethodName, t)) + .orElse(null); } } - private StackTraceWriter toStackTraceWriter( String realClassName, String realMethodName, Throwable throwable ) - { - return new PojoStackTraceWriter( realClassName, realMethodName, throwable ); + private StackTraceWriter toStackTraceWriter(String realClassName, String realMethodName, Throwable throwable) { + return new PojoStackTraceWriter(realClassName, realMethodName, throwable); } /** @@ -307,43 +309,43 @@ private StackTraceWriter toStackTraceWriter( String realClassName, String realMe * @param testIdentifier a class or method * @return 4 elements string array */ - private String[] toClassMethodName( TestIdentifier testIdentifier ) - { + private String[] toClassMethodName(TestIdentifier testIdentifier) { Optional testSource = testIdentifier.getSource(); String display = testIdentifier.getDisplayName(); - if ( testSource.filter( MethodSource.class::isInstance ).isPresent() ) - { - MethodSource methodSource = testSource.map( MethodSource.class::cast ).get(); + if (testSource.filter(MethodSource.class::isInstance).isPresent()) { + MethodSource methodSource = testSource.map(MethodSource.class::cast).get(); String realClassName = methodSource.getClassName(); - String[] source = collectAllTestIdentifiersInHierarchy( testIdentifier ) - .filter( i -> i.getSource().map( ClassSource.class::isInstance ).orElse( false ) ) + String[] source = collectAllTestIdentifiersInHierarchy(testIdentifier) + .filter(i -> + i.getSource().map(ClassSource.class::isInstance).orElse(false)) .findFirst() - .map( this::toClassMethodName ) - .map( s -> new String[] { s[0], s[1] } ) - .orElse( new String[] { realClassName, realClassName } ); - - String parentDisplay = - collectAllTestIdentifiersInHierarchy( testIdentifier ) - .filter( identifier -> identifier.getSource().filter( MethodSource.class::isInstance ).isPresent() ) - .map( TestIdentifier::getDisplayName ) - .collect( joining( " " ) ); - - boolean needsSpaceSeparator = isNotBlank( parentDisplay ) && !display.startsWith( "[" ); - String methodDisplay = parentDisplay + ( needsSpaceSeparator ? " " : "" ) + display; - - boolean hasParameterizedParent = - collectAllTestIdentifiersInHierarchy( testIdentifier ) - .filter( identifier -> !identifier.getSource().isPresent() ) - .map( TestIdentifier::getLegacyReportingName ) - .anyMatch( legacyReportingName -> legacyReportingName.matches( "^\\[.+]$" ) ); - - boolean parameterized = isNotBlank( methodSource.getMethodParameterTypes() ) || hasParameterizedParent; + .map(this::toClassMethodName) + .map(s -> new String[] {s[0], s[1]}) + .orElse(new String[] {realClassName, realClassName}); + + String parentDisplay = collectAllTestIdentifiersInHierarchy(testIdentifier) + .filter(identifier -> identifier + .getSource() + .filter(MethodSource.class::isInstance) + .isPresent()) + .map(TestIdentifier::getDisplayName) + .collect(joining(" ")); + + boolean needsSpaceSeparator = isNotBlank(parentDisplay) && !display.startsWith("["); + String methodDisplay = parentDisplay + (needsSpaceSeparator ? " " : "") + display; + + boolean hasParameterizedParent = collectAllTestIdentifiersInHierarchy(testIdentifier) + .filter(identifier -> !identifier.getSource().isPresent()) + .map(TestIdentifier::getLegacyReportingName) + .anyMatch(legacyReportingName -> legacyReportingName.matches("^\\[.+]$")); + + boolean parameterized = isNotBlank(methodSource.getMethodParameterTypes()) || hasParameterizedParent; String methodName = methodSource.getMethodName(); String description = testIdentifier.getLegacyReportingName(); - boolean equalDescriptions = methodDisplay.equals( description ); - boolean hasLegacyDescription = description.startsWith( methodName + '(' ); + boolean equalDescriptions = methodDisplay.equals(description); + boolean hasLegacyDescription = description.startsWith(methodName + '('); boolean hasDisplayName = !equalDescriptions || !hasLegacyDescription; String methodDesc = parameterized ? description : methodName; String methodDisp = hasDisplayName ? methodDisplay : methodDesc; @@ -363,29 +365,28 @@ private String[] toClassMethodName( TestIdentifier testIdentifier ) // param+displ || m()[1] | displ return new String[] {source[0], source[1], methodDesc, methodDisp}; - } - else if ( testSource.filter( ClassSource.class::isInstance ).isPresent() ) - { - List parentClassDisplays = - collectAllTestIdentifiersInHierarchy( testIdentifier ) - .filter( identifier -> identifier.getSource().filter( ClassSource.class::isInstance ).isPresent() ) - .map( TestIdentifier::getDisplayName ) - .collect( toList() ); - - Collections.reverse( parentClassDisplays ); - String classDisplay = Stream.concat( parentClassDisplays.stream(), Stream.of( display ) ) - .collect( joining( " " ) ); - - ClassSource classSource = testSource.map( ClassSource.class::cast ).get(); + } else if (testSource.filter(ClassSource.class::isInstance).isPresent()) { + List parentClassDisplays = collectAllTestIdentifiersInHierarchy(testIdentifier) + .filter(identifier -> identifier + .getSource() + .filter(ClassSource.class::isInstance) + .isPresent()) + .map(TestIdentifier::getDisplayName) + .collect(toList()); + + Collections.reverse(parentClassDisplays); + String classDisplay = Stream.concat(parentClassDisplays.stream(), Stream.of(display)) + .collect(joining(" ")); + + ClassSource classSource = testSource.map(ClassSource.class::cast).get(); String className = classSource.getClassName(); - String simpleClassName = className.substring( 1 + className.lastIndexOf( '.' ) ); - String source = classDisplay.replace( ' ', '$' ).equals( simpleClassName ) ? className : classDisplay; + String simpleClassName = className.substring(1 + className.lastIndexOf('.')); + String source = classDisplay.replace(' ', '$').equals(simpleClassName) ? className : classDisplay; return new String[] {className, source, null, null}; - } - else - { - String source = testPlan.getParent( testIdentifier ) - .map( TestIdentifier::getDisplayName ).orElse( display ); + } else { + String source = testPlan.getParent(testIdentifier) + .map(TestIdentifier::getDisplayName) + .orElse(display); return new String[] {source, source, display, display}; } } @@ -393,26 +394,22 @@ else if ( testSource.filter( ClassSource.class::isInstance ).isPresent() ) /** * @return Map of tests that failed. */ - Map getFailures() - { + Map getFailures() { return failures; } - boolean hasFailingTests() - { + boolean hasFailingTests() { return !getFailures().isEmpty(); } - void reset() - { + void reset() { getFailures().clear(); testPlan = null; } @Override - public void writeTestOutput( OutputReportEntry reportEntry ) - { + public void writeTestOutput(OutputReportEntry reportEntry) { Long testRunId = classMethodIndexer.getLocalIndex(); - runListener.writeTestOutput( new TestOutputReportEntry( reportEntry, runMode, testRunId ) ); + runListener.writeTestOutput(new TestOutputReportEntry(reportEntry, runMode, testRunId)); } } diff --git a/surefire-providers/surefire-junit-platform/src/main/java/org/apache/maven/surefire/junitplatform/TestMethodFilter.java b/surefire-providers/surefire-junit-platform/src/main/java/org/apache/maven/surefire/junitplatform/TestMethodFilter.java index d766ffdd27..fa67b764eb 100644 --- a/surefire-providers/surefire-junit-platform/src/main/java/org/apache/maven/surefire/junitplatform/TestMethodFilter.java +++ b/surefire-providers/surefire-junit-platform/src/main/java/org/apache/maven/surefire/junitplatform/TestMethodFilter.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.junitplatform; /* @@ -28,33 +46,29 @@ /** * @since 2.22.0 */ -class TestMethodFilter - implements PostDiscoveryFilter -{ +class TestMethodFilter implements PostDiscoveryFilter { private final TestListResolver testListResolver; - TestMethodFilter( TestListResolver testListResolver ) - { + TestMethodFilter(TestListResolver testListResolver) { this.testListResolver = testListResolver; } @Override - public FilterResult apply( TestDescriptor descriptor ) - { - boolean shouldRun = descriptor.getSource() - .filter( MethodSource.class::isInstance ) - .map( MethodSource.class::cast ) - .map( this::shouldRun ) - .orElse( true ); - - return FilterResult.includedIf( shouldRun ); + public FilterResult apply(TestDescriptor descriptor) { + boolean shouldRun = descriptor + .getSource() + .filter(MethodSource.class::isInstance) + .map(MethodSource.class::cast) + .map(this::shouldRun) + .orElse(true); + + return FilterResult.includedIf(shouldRun); } - private boolean shouldRun( MethodSource source ) - { - String testClass = TestListResolver.toClassFileName( source.getClassName() ); + private boolean shouldRun(MethodSource source) { + String testClass = TestListResolver.toClassFileName(source.getClassName()); String testMethod = source.getMethodName(); - return this.testListResolver.shouldRun( testClass, testMethod ); + return this.testListResolver.shouldRun(testClass, testMethod); } } diff --git a/surefire-providers/surefire-junit-platform/src/main/java/org/apache/maven/surefire/junitplatform/TestPlanScannerFilter.java b/surefire-providers/surefire-junit-platform/src/main/java/org/apache/maven/surefire/junitplatform/TestPlanScannerFilter.java index 90b52368d2..ec058c9690 100644 --- a/surefire-providers/surefire-junit-platform/src/main/java/org/apache/maven/surefire/junitplatform/TestPlanScannerFilter.java +++ b/surefire-providers/surefire-junit-platform/src/main/java/org/apache/maven/surefire/junitplatform/TestPlanScannerFilter.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.junitplatform; /* @@ -19,41 +37,38 @@ * under the License. */ -import static org.junit.platform.engine.discovery.DiscoverySelectors.selectClass; -import static org.junit.platform.launcher.core.LauncherDiscoveryRequestBuilder.request; - import org.apache.maven.surefire.api.util.ScannerFilter; import org.junit.platform.engine.Filter; import org.junit.platform.launcher.Launcher; import org.junit.platform.launcher.LauncherDiscoveryRequest; import org.junit.platform.launcher.TestPlan; +import static org.junit.platform.engine.discovery.DiscoverySelectors.selectClass; +import static org.junit.platform.launcher.core.LauncherDiscoveryRequestBuilder.request; + /** * @since 2.22.0 */ -final class TestPlanScannerFilter - implements ScannerFilter -{ +final class TestPlanScannerFilter implements ScannerFilter { private final Launcher launcher; private final Filter[] includeAndExcludeFilters; - TestPlanScannerFilter( Launcher launcher, Filter[] includeAndExcludeFilters ) - { + TestPlanScannerFilter(Launcher launcher, Filter[] includeAndExcludeFilters) { this.launcher = launcher; this.includeAndExcludeFilters = includeAndExcludeFilters; } @Override - @SuppressWarnings( "rawtypes" ) - public boolean accept( Class testClass ) - { + @SuppressWarnings("rawtypes") + public boolean accept(Class testClass) { LauncherDiscoveryRequest discoveryRequest = request() - .selectors( selectClass( testClass.getName() ) ) - .filters( includeAndExcludeFilters ).build(); + .selectors(selectClass(testClass.getName())) + .filters(includeAndExcludeFilters) + .build(); - TestPlan testPlan = launcher.discover( discoveryRequest ); + TestPlan testPlan = launcher.discover(discoveryRequest); return testPlan.containsTests(); } diff --git a/surefire-providers/surefire-junit-platform/src/test/java/org/apache/maven/surefire/junitplatform/JUnit47SuiteTest.java b/surefire-providers/surefire-junit-platform/src/test/java/org/apache/maven/surefire/junitplatform/JUnit47SuiteTest.java index 7db25c9b20..f37ecd48dd 100644 --- a/surefire-providers/surefire-junit-platform/src/test/java/org/apache/maven/surefire/junitplatform/JUnit47SuiteTest.java +++ b/surefire-providers/surefire-junit-platform/src/test/java/org/apache/maven/surefire/junitplatform/JUnit47SuiteTest.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.junitplatform; /* @@ -29,15 +47,13 @@ * * @since 3.0.0-M4 */ -public class JUnit47SuiteTest extends TestCase -{ - public static Test suite() - { +public class JUnit47SuiteTest extends TestCase { + public static Test suite() { TestSuite suite = new TestSuite(); - suite.addTest( new JUnit4TestAdapter( JUnitPlatformProviderTest.class ) ); - suite.addTest( new JUnit4TestAdapter( RunListenerAdapterTest.class ) ); - suite.addTest( new JUnit4TestAdapter( TestMethodFilterTest.class ) ); - suite.addTest( new JUnit4TestAdapter( TestPlanScannerFilterTest.class ) ); + suite.addTest(new JUnit4TestAdapter(JUnitPlatformProviderTest.class)); + suite.addTest(new JUnit4TestAdapter(RunListenerAdapterTest.class)); + suite.addTest(new JUnit4TestAdapter(TestMethodFilterTest.class)); + suite.addTest(new JUnit4TestAdapter(TestPlanScannerFilterTest.class)); return suite; } } diff --git a/surefire-providers/surefire-junit-platform/src/test/java/org/apache/maven/surefire/junitplatform/JUnitPlatformProviderTest.java b/surefire-providers/surefire-junit-platform/src/test/java/org/apache/maven/surefire/junitplatform/JUnitPlatformProviderTest.java index b909b2c43a..09abd160a8 100644 --- a/surefire-providers/surefire-junit-platform/src/test/java/org/apache/maven/surefire/junitplatform/JUnitPlatformProviderTest.java +++ b/surefire-providers/surefire-junit-platform/src/test/java/org/apache/maven/surefire/junitplatform/JUnitPlatformProviderTest.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.junitplatform; /* @@ -19,33 +37,6 @@ * under the License. */ -import static java.util.Collections.emptyMap; -import static java.util.Collections.singletonMap; -import static java.util.stream.Collectors.toSet; -import static org.apache.maven.surefire.api.booter.ProviderParameterNames.TESTNG_GROUPS_PROP; -import static org.apache.maven.surefire.api.booter.ProviderParameterNames.TESTNG_EXCLUDEDGROUPS_PROP; -import static org.apache.maven.surefire.api.booter.ProviderParameterNames.INCLUDE_JUNIT5_ENGINES_PROP; -import static org.apache.maven.surefire.api.booter.ProviderParameterNames.EXCLUDE_JUNIT5_ENGINES_PROP; -import static org.apache.maven.surefire.api.report.RunMode.NORMAL_RUN; -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assertions.fail; -import static org.junit.jupiter.api.Assumptions.assumeFalse; -import static org.junit.jupiter.api.Assumptions.assumeTrue; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.inOrder; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; -import static org.mockito.Mockito.withSettings; -import static org.powermock.reflect.Whitebox.getInternalState; - import java.io.PrintStream; import java.util.ArrayList; import java.util.Arrays; @@ -57,11 +48,11 @@ import java.util.Set; import org.apache.maven.surefire.api.provider.ProviderParameters; -import org.apache.maven.surefire.api.report.TestOutputReceiver; import org.apache.maven.surefire.api.report.ReportEntry; import org.apache.maven.surefire.api.report.ReporterFactory; import org.apache.maven.surefire.api.report.RunListener; import org.apache.maven.surefire.api.report.SimpleReportEntry; +import org.apache.maven.surefire.api.report.TestOutputReceiver; import org.apache.maven.surefire.api.report.TestOutputReportEntry; import org.apache.maven.surefire.api.report.TestReportListener; import org.apache.maven.surefire.api.report.TestSetReportEntry; @@ -87,1140 +78,1055 @@ import org.mockito.ArgumentCaptor; import org.mockito.InOrder; +import static java.util.Collections.emptyMap; +import static java.util.Collections.singletonMap; +import static java.util.stream.Collectors.toSet; +import static org.apache.maven.surefire.api.booter.ProviderParameterNames.EXCLUDE_JUNIT5_ENGINES_PROP; +import static org.apache.maven.surefire.api.booter.ProviderParameterNames.INCLUDE_JUNIT5_ENGINES_PROP; +import static org.apache.maven.surefire.api.booter.ProviderParameterNames.TESTNG_EXCLUDEDGROUPS_PROP; +import static org.apache.maven.surefire.api.booter.ProviderParameterNames.TESTNG_GROUPS_PROP; +import static org.apache.maven.surefire.api.report.RunMode.NORMAL_RUN; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; +import static org.junit.jupiter.api.Assumptions.assumeFalse; +import static org.junit.jupiter.api.Assumptions.assumeTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.mockito.Mockito.withSettings; +import static org.powermock.reflect.Whitebox.getInternalState; + /** * Unit tests for {@link JUnitPlatformProvider}. * * @since 2.22.0 */ -public class JUnitPlatformProviderTest -{ +public class JUnitPlatformProviderTest { @Test - public void shouldFailClassOnBeforeAll() - throws Exception - { + public void shouldFailClassOnBeforeAll() throws Exception { Launcher launcher = LauncherFactory.create(); - JUnitPlatformProvider provider = new JUnitPlatformProvider( providerParametersMock(), launcher ); - TestReportListener listener = mock( TestReportListener.class ); + JUnitPlatformProvider provider = new JUnitPlatformProvider(providerParametersMock(), launcher); + TestReportListener listener = mock(TestReportListener.class); - ArgumentCaptor testCaptor = ArgumentCaptor.forClass( ReportEntry.class ); - ArgumentCaptor testSetCaptor = ArgumentCaptor.forClass( TestSetReportEntry.class ); + ArgumentCaptor testCaptor = ArgumentCaptor.forClass(ReportEntry.class); + ArgumentCaptor testSetCaptor = ArgumentCaptor.forClass(TestSetReportEntry.class); - RunListenerAdapter adapter = new RunListenerAdapter( listener ); - adapter.setRunMode( NORMAL_RUN ); - launcher.registerTestExecutionListeners( adapter ); + RunListenerAdapter adapter = new RunListenerAdapter(listener); + adapter.setRunMode(NORMAL_RUN); + launcher.registerTestExecutionListeners(adapter); - TestsToRun testsToRun = newTestsToRun( FailingBeforeAllJupiterTest.class ); - invokeProvider( provider, testsToRun ); - InOrder inOrder = inOrder( listener ); - inOrder.verify( listener, times( 1 ) ).testSetStarting( testSetCaptor.capture() ); - inOrder.verify( listener, never() ).testStarting( any( ReportEntry.class ) ); - inOrder.verify( listener, times( 1 ) ).testFailed( testCaptor.capture() ); - inOrder.verify( listener, times( 1 ) ).testSetCompleted( testSetCaptor.capture() ); + TestsToRun testsToRun = newTestsToRun(FailingBeforeAllJupiterTest.class); + invokeProvider(provider, testsToRun); + InOrder inOrder = inOrder(listener); + inOrder.verify(listener, times(1)).testSetStarting(testSetCaptor.capture()); + inOrder.verify(listener, never()).testStarting(any(ReportEntry.class)); + inOrder.verify(listener, times(1)).testFailed(testCaptor.capture()); + inOrder.verify(listener, times(1)).testSetCompleted(testSetCaptor.capture()); - assertThat( testSetCaptor.getAllValues() ) - .hasSize( 2 ); + assertThat(testSetCaptor.getAllValues()).hasSize(2); - assertThat( testSetCaptor.getAllValues().get( 0 ).getSourceName() ) - .isEqualTo( FailingBeforeAllJupiterTest.class.getName() ); + assertThat(testSetCaptor.getAllValues().get(0).getSourceName()) + .isEqualTo(FailingBeforeAllJupiterTest.class.getName()); - assertThat( testSetCaptor.getAllValues().get( 0 ).getName() ) - .isNull(); + assertThat(testSetCaptor.getAllValues().get(0).getName()).isNull(); - assertThat( testCaptor.getAllValues() ) - .hasSize( 1 ); + assertThat(testCaptor.getAllValues()).hasSize(1); - assertThat( testCaptor.getValue().getSourceName() ) - .isEqualTo( FailingBeforeAllJupiterTest.class.getName() ); + assertThat(testCaptor.getValue().getSourceName()).isEqualTo(FailingBeforeAllJupiterTest.class.getName()); - assertThat( testCaptor.getValue().getName() ) - .isNull(); + assertThat(testCaptor.getValue().getName()).isNull(); - assertThat( testSetCaptor.getAllValues().get( 1 ).getSourceName() ) - .isEqualTo( FailingBeforeAllJupiterTest.class.getName() ); + assertThat(testSetCaptor.getAllValues().get(1).getSourceName()) + .isEqualTo(FailingBeforeAllJupiterTest.class.getName()); - assertThat( testSetCaptor.getAllValues().get( 1 ).getName() ) - .isNull(); + assertThat(testSetCaptor.getAllValues().get(1).getName()).isNull(); } @Test - public void shouldErrorClassOnBeforeAll() - throws Exception - { + public void shouldErrorClassOnBeforeAll() throws Exception { Launcher launcher = LauncherFactory.create(); - JUnitPlatformProvider provider = new JUnitPlatformProvider( providerParametersMock(), launcher ); - TestReportListener listener = mock( TestReportListener.class ); + JUnitPlatformProvider provider = new JUnitPlatformProvider(providerParametersMock(), launcher); + TestReportListener listener = mock(TestReportListener.class); - ArgumentCaptor testCaptor = ArgumentCaptor.forClass( ReportEntry.class ); - ArgumentCaptor testSetCaptor = ArgumentCaptor.forClass( TestSetReportEntry.class ); + ArgumentCaptor testCaptor = ArgumentCaptor.forClass(ReportEntry.class); + ArgumentCaptor testSetCaptor = ArgumentCaptor.forClass(TestSetReportEntry.class); - RunListenerAdapter adapter = new RunListenerAdapter( listener ); - adapter.setRunMode( NORMAL_RUN ); - launcher.registerTestExecutionListeners( adapter ); + RunListenerAdapter adapter = new RunListenerAdapter(listener); + adapter.setRunMode(NORMAL_RUN); + launcher.registerTestExecutionListeners(adapter); - TestsToRun testsToRun = newTestsToRun( FailingWithErrorBeforeAllJupiterTest.class ); - invokeProvider( provider, testsToRun ); - InOrder inOrder = inOrder( listener ); - inOrder.verify( listener, times( 1 ) ).testSetStarting( testSetCaptor.capture() ); - inOrder.verify( listener, never() ).testStarting( any( ReportEntry.class ) ); - inOrder.verify( listener, times( 1 ) ).testError( testCaptor.capture() ); - inOrder.verify( listener, times( 1 ) ).testSetCompleted( testSetCaptor.capture() ); + TestsToRun testsToRun = newTestsToRun(FailingWithErrorBeforeAllJupiterTest.class); + invokeProvider(provider, testsToRun); + InOrder inOrder = inOrder(listener); + inOrder.verify(listener, times(1)).testSetStarting(testSetCaptor.capture()); + inOrder.verify(listener, never()).testStarting(any(ReportEntry.class)); + inOrder.verify(listener, times(1)).testError(testCaptor.capture()); + inOrder.verify(listener, times(1)).testSetCompleted(testSetCaptor.capture()); - assertThat( testSetCaptor.getAllValues() ) - .hasSize( 2 ); + assertThat(testSetCaptor.getAllValues()).hasSize(2); - assertThat( testSetCaptor.getAllValues().get( 0 ).getSourceName() ) - .isEqualTo( FailingWithErrorBeforeAllJupiterTest.class.getName() ); + assertThat(testSetCaptor.getAllValues().get(0).getSourceName()) + .isEqualTo(FailingWithErrorBeforeAllJupiterTest.class.getName()); - assertThat( testSetCaptor.getAllValues().get( 0 ).getName() ) - .isNull(); + assertThat(testSetCaptor.getAllValues().get(0).getName()).isNull(); - assertThat( testCaptor.getAllValues() ) - .hasSize( 1 ); + assertThat(testCaptor.getAllValues()).hasSize(1); - assertThat( testCaptor.getValue().getSourceName() ) - .isEqualTo( FailingWithErrorBeforeAllJupiterTest.class.getName() ); + assertThat(testCaptor.getValue().getSourceName()) + .isEqualTo(FailingWithErrorBeforeAllJupiterTest.class.getName()); - assertThat( testCaptor.getValue().getName() ) - .isNull(); + assertThat(testCaptor.getValue().getName()).isNull(); - assertThat( testSetCaptor.getAllValues().get( 1 ).getSourceName() ) - .isEqualTo( FailingWithErrorBeforeAllJupiterTest.class.getName() ); + assertThat(testSetCaptor.getAllValues().get(1).getSourceName()) + .isEqualTo(FailingWithErrorBeforeAllJupiterTest.class.getName()); - assertThat( testSetCaptor.getAllValues().get( 1 ).getName() ) - .isNull(); + assertThat(testSetCaptor.getAllValues().get(1).getName()).isNull(); } @Test - public void getSuitesReturnsScannedClasses() - { - ProviderParameters providerParameters = providerParametersMock( TestClass1.class, TestClass2.class ); - JUnitPlatformProvider provider = new JUnitPlatformProvider( providerParameters ); - assertThat( provider.getSuites() ) - .containsOnly( TestClass1.class, TestClass2.class ); + public void getSuitesReturnsScannedClasses() { + ProviderParameters providerParameters = providerParametersMock(TestClass1.class, TestClass2.class); + JUnitPlatformProvider provider = new JUnitPlatformProvider(providerParameters); + assertThat(provider.getSuites()).containsOnly(TestClass1.class, TestClass2.class); } @Test - public void invokeThrowsForWrongForkTestSet() - { - ProviderParameters providerParameters = providerParametersMock( Integer.class ); - JUnitPlatformProvider provider = new JUnitPlatformProvider( providerParameters ); + public void invokeThrowsForWrongForkTestSet() { + ProviderParameters providerParameters = providerParametersMock(Integer.class); + JUnitPlatformProvider provider = new JUnitPlatformProvider(providerParameters); - assertThrows( IllegalArgumentException.class, () -> invokeProvider( provider, "wrong forkTestSet" ) ); + assertThrows(IllegalArgumentException.class, () -> invokeProvider(provider, "wrong forkTestSet")); } @Test - public void allGivenTestsToRunAreInvoked() - throws Exception - { + public void allGivenTestsToRunAreInvoked() throws Exception { Launcher launcher = LauncherFactory.create(); - JUnitPlatformProvider provider = new JUnitPlatformProvider( providerParametersMock(), launcher ); + JUnitPlatformProvider provider = new JUnitPlatformProvider(providerParametersMock(), launcher); TestPlanSummaryListener executionListener = new TestPlanSummaryListener(); - launcher.registerTestExecutionListeners( executionListener ); + launcher.registerTestExecutionListeners(executionListener); - TestsToRun testsToRun = newTestsToRun( TestClass1.class, TestClass2.class ); - invokeProvider( provider, testsToRun ); + TestsToRun testsToRun = newTestsToRun(TestClass1.class, TestClass2.class); + invokeProvider(provider, testsToRun); - assertThat( executionListener.summaries ).hasSize( 1 ); - TestExecutionSummary summary = executionListener.summaries.get( 0 ); - assertEquals( TestClass1.TESTS_FOUND + TestClass2.TESTS_FOUND, summary.getTestsFoundCount() ); - assertEquals( - TestClass1.TESTS_STARTED + TestClass2.TESTS_STARTED, summary.getTestsStartedCount() ); - assertEquals( - TestClass1.TESTS_SKIPPED + TestClass2.TESTS_SKIPPED, summary.getTestsSkippedCount() ); - assertEquals( - TestClass1.TESTS_SUCCEEDED + TestClass2.TESTS_SUCCEEDED, summary.getTestsSucceededCount() ); - assertEquals( - TestClass1.TESTS_ABORTED + TestClass2.TESTS_ABORTED, summary.getTestsAbortedCount() ); - assertEquals( TestClass1.TESTS_FAILED + TestClass2.TESTS_FAILED, summary.getTestsFailedCount() ); + assertThat(executionListener.summaries).hasSize(1); + TestExecutionSummary summary = executionListener.summaries.get(0); + assertEquals(TestClass1.TESTS_FOUND + TestClass2.TESTS_FOUND, summary.getTestsFoundCount()); + assertEquals(TestClass1.TESTS_STARTED + TestClass2.TESTS_STARTED, summary.getTestsStartedCount()); + assertEquals(TestClass1.TESTS_SKIPPED + TestClass2.TESTS_SKIPPED, summary.getTestsSkippedCount()); + assertEquals(TestClass1.TESTS_SUCCEEDED + TestClass2.TESTS_SUCCEEDED, summary.getTestsSucceededCount()); + assertEquals(TestClass1.TESTS_ABORTED + TestClass2.TESTS_ABORTED, summary.getTestsAbortedCount()); + assertEquals(TestClass1.TESTS_FAILED + TestClass2.TESTS_FAILED, summary.getTestsFailedCount()); } @Test - public void singleTestClassIsInvoked() - throws Exception - { + public void singleTestClassIsInvoked() throws Exception { Launcher launcher = LauncherFactory.create(); - JUnitPlatformProvider provider = new JUnitPlatformProvider( providerParametersMock(), launcher ); + JUnitPlatformProvider provider = new JUnitPlatformProvider(providerParametersMock(), launcher); TestPlanSummaryListener executionListener = new TestPlanSummaryListener(); - launcher.registerTestExecutionListeners( executionListener ); + launcher.registerTestExecutionListeners(executionListener); - invokeProvider( provider, TestClass1.class ); + invokeProvider(provider, TestClass1.class); - assertThat( executionListener.summaries ).hasSize( 1 ); - TestExecutionSummary summary = executionListener.summaries.get( 0 ); - assertEquals( TestClass1.TESTS_FOUND, summary.getTestsFoundCount() ); - assertEquals( TestClass1.TESTS_STARTED, summary.getTestsStartedCount() ); - assertEquals( TestClass1.TESTS_SKIPPED, summary.getTestsSkippedCount() ); - assertEquals( TestClass1.TESTS_SUCCEEDED, summary.getTestsSucceededCount() ); - assertEquals( TestClass1.TESTS_ABORTED, summary.getTestsAbortedCount() ); - assertEquals( TestClass1.TESTS_FAILED, summary.getTestsFailedCount() ); + assertThat(executionListener.summaries).hasSize(1); + TestExecutionSummary summary = executionListener.summaries.get(0); + assertEquals(TestClass1.TESTS_FOUND, summary.getTestsFoundCount()); + assertEquals(TestClass1.TESTS_STARTED, summary.getTestsStartedCount()); + assertEquals(TestClass1.TESTS_SKIPPED, summary.getTestsSkippedCount()); + assertEquals(TestClass1.TESTS_SUCCEEDED, summary.getTestsSucceededCount()); + assertEquals(TestClass1.TESTS_ABORTED, summary.getTestsAbortedCount()); + assertEquals(TestClass1.TESTS_FAILED, summary.getTestsFailedCount()); } @Test - public void singleTestClassIsInvokedLazily() - throws Exception - { + public void singleTestClassIsInvokedLazily() throws Exception { Launcher launcher = LauncherFactory.create(); - JUnitPlatformProvider provider = new JUnitPlatformProvider( providerParametersMock(), launcher ); + JUnitPlatformProvider provider = new JUnitPlatformProvider(providerParametersMock(), launcher); TestPlanSummaryListener executionListener = new TestPlanSummaryListener(); - launcher.registerTestExecutionListeners( executionListener ); + launcher.registerTestExecutionListeners(executionListener); - invokeProvider( provider, newTestsToRunLazily( TestClass1.class ) ); + invokeProvider(provider, newTestsToRunLazily(TestClass1.class)); - assertThat( executionListener.summaries ).hasSize( 1 ); - TestExecutionSummary summary = executionListener.summaries.get( 0 ); - assertEquals( TestClass1.TESTS_FOUND, summary.getTestsFoundCount() ); - assertEquals( TestClass1.TESTS_STARTED, summary.getTestsStartedCount() ); - assertEquals( TestClass1.TESTS_SKIPPED, summary.getTestsSkippedCount() ); - assertEquals( TestClass1.TESTS_SUCCEEDED, summary.getTestsSucceededCount() ); - assertEquals( TestClass1.TESTS_ABORTED, summary.getTestsAbortedCount() ); - assertEquals( TestClass1.TESTS_FAILED, summary.getTestsFailedCount() ); + assertThat(executionListener.summaries).hasSize(1); + TestExecutionSummary summary = executionListener.summaries.get(0); + assertEquals(TestClass1.TESTS_FOUND, summary.getTestsFoundCount()); + assertEquals(TestClass1.TESTS_STARTED, summary.getTestsStartedCount()); + assertEquals(TestClass1.TESTS_SKIPPED, summary.getTestsSkippedCount()); + assertEquals(TestClass1.TESTS_SUCCEEDED, summary.getTestsSucceededCount()); + assertEquals(TestClass1.TESTS_ABORTED, summary.getTestsAbortedCount()); + assertEquals(TestClass1.TESTS_FAILED, summary.getTestsFailedCount()); } @Test - public void failingTestCaseAfterRerun() - throws Exception - { + public void failingTestCaseAfterRerun() throws Exception { Launcher launcher = LauncherFactory.create(); ProviderParameters parameters = providerParametersMock(); // Mock the rerun variable - when( parameters.getTestRequest().getRerunFailingTestsCount() ).thenReturn( 1 ); + when(parameters.getTestRequest().getRerunFailingTestsCount()).thenReturn(1); - JUnitPlatformProvider provider = new JUnitPlatformProvider( parameters, launcher ); + JUnitPlatformProvider provider = new JUnitPlatformProvider(parameters, launcher); TestPlanSummaryListener executionListener = new TestPlanSummaryListener(); - launcher.registerTestExecutionListeners( executionListener ); + launcher.registerTestExecutionListeners(executionListener); - invokeProvider( provider, TestClass2.class ); + invokeProvider(provider, TestClass2.class); - assertThat( executionListener.summaries ).hasSize( 2 ); - TestExecutionSummary summary = executionListener.summaries.get( 0 ); - assertEquals( TestClass2.TESTS_FOUND, summary.getTestsFoundCount() ); - assertEquals( TestClass2.TESTS_STARTED, summary.getTestsStartedCount() ); - assertEquals( TestClass2.TESTS_SKIPPED, summary.getTestsSkippedCount() ); - assertEquals( TestClass2.TESTS_SUCCEEDED, summary.getTestsSucceededCount() ); - assertEquals( TestClass2.TESTS_ABORTED, summary.getTestsAbortedCount() ); - assertEquals( TestClass2.TESTS_FAILED, summary.getTestsFailedCount() ); + assertThat(executionListener.summaries).hasSize(2); + TestExecutionSummary summary = executionListener.summaries.get(0); + assertEquals(TestClass2.TESTS_FOUND, summary.getTestsFoundCount()); + assertEquals(TestClass2.TESTS_STARTED, summary.getTestsStartedCount()); + assertEquals(TestClass2.TESTS_SKIPPED, summary.getTestsSkippedCount()); + assertEquals(TestClass2.TESTS_SUCCEEDED, summary.getTestsSucceededCount()); + assertEquals(TestClass2.TESTS_ABORTED, summary.getTestsAbortedCount()); + assertEquals(TestClass2.TESTS_FAILED, summary.getTestsFailedCount()); // Should only be re-running one unit test // - And it should only fail - summary = executionListener.summaries.get( 1 ); - assertEquals( 1, summary.getTestsFoundCount() ); - assertEquals( 1, summary.getTestsStartedCount() ); - assertEquals( 0, summary.getTestsSkippedCount() ); - assertEquals( 0, summary.getTestsSucceededCount() ); - assertEquals( 0, summary.getTestsAbortedCount() ); - assertEquals( 1, summary.getTestsFailedCount() ); + summary = executionListener.summaries.get(1); + assertEquals(1, summary.getTestsFoundCount()); + assertEquals(1, summary.getTestsStartedCount()); + assertEquals(0, summary.getTestsSkippedCount()); + assertEquals(0, summary.getTestsSucceededCount()); + assertEquals(0, summary.getTestsAbortedCount()); + assertEquals(1, summary.getTestsFailedCount()); } @Test - public void rerunStillFailing() - throws Exception - { + public void rerunStillFailing() throws Exception { Launcher launcher = LauncherFactory.create(); ProviderParameters parameters = providerParametersMock(); // Mock the rerun variable - when( parameters.getTestRequest().getRerunFailingTestsCount() ).thenReturn( 2 ); + when(parameters.getTestRequest().getRerunFailingTestsCount()).thenReturn(2); - JUnitPlatformProvider provider = new JUnitPlatformProvider( parameters, launcher ); + JUnitPlatformProvider provider = new JUnitPlatformProvider(parameters, launcher); TestPlanSummaryListener executionListener = new TestPlanSummaryListener(); - launcher.registerTestExecutionListeners( executionListener ); + launcher.registerTestExecutionListeners(executionListener); // 3 unit tests: // - fail always // - fail twice (pass on 2nd rerun) // - pass always - invokeProvider( provider, TestClass4.class ); - - assertThat( executionListener.summaries ).hasSize( 3 ); - TestExecutionSummary summary = executionListener.summaries.get( 0 ); - assertEquals( 6, summary.getTestsFoundCount() ); - assertEquals( 5, summary.getTestsStartedCount() ); - assertEquals( 1, summary.getTestsSkippedCount() ); - assertEquals( 1, summary.getTestsSucceededCount() ); - assertEquals( 1, summary.getTestsAbortedCount() ); - assertEquals( 3, summary.getTestsFailedCount() ); + invokeProvider(provider, TestClass4.class); + + assertThat(executionListener.summaries).hasSize(3); + TestExecutionSummary summary = executionListener.summaries.get(0); + assertEquals(6, summary.getTestsFoundCount()); + assertEquals(5, summary.getTestsStartedCount()); + assertEquals(1, summary.getTestsSkippedCount()); + assertEquals(1, summary.getTestsSucceededCount()); + assertEquals(1, summary.getTestsAbortedCount()); + assertEquals(3, summary.getTestsFailedCount()); Set failDisplays = new HashSet<>(); - for ( TestExecutionSummary.Failure failure : summary.getFailures() ) - { - failDisplays.add( failure.getTestIdentifier().getDisplayName() ); + for (TestExecutionSummary.Failure failure : summary.getFailures()) { + failDisplays.add(failure.getTestIdentifier().getDisplayName()); } - assertEquals( 3, failDisplays.size() ); - assertTrue( failDisplays.contains( "Fails twice" ) ); - assertTrue( failDisplays.contains( "testAlwaysFail()" ) ); - assertTrue( failDisplays.contains( "testAlwaysError()" ) ); + assertEquals(3, failDisplays.size()); + assertTrue(failDisplays.contains("Fails twice")); + assertTrue(failDisplays.contains("testAlwaysFail()")); + assertTrue(failDisplays.contains("testAlwaysError()")); // Should rerun both of the failures - summary = executionListener.summaries.get( 1 ); - assertEquals( 3, summary.getTestsFoundCount() ); - assertEquals( 3, summary.getTestsStartedCount() ); - assertEquals( 0, summary.getTestsSkippedCount() ); - assertEquals( 0, summary.getTestsSucceededCount() ); - assertEquals( 0, summary.getTestsAbortedCount() ); - assertEquals( 3, summary.getTestsFailedCount() ); + summary = executionListener.summaries.get(1); + assertEquals(3, summary.getTestsFoundCount()); + assertEquals(3, summary.getTestsStartedCount()); + assertEquals(0, summary.getTestsSkippedCount()); + assertEquals(0, summary.getTestsSucceededCount()); + assertEquals(0, summary.getTestsAbortedCount()); + assertEquals(3, summary.getTestsFailedCount()); failDisplays.clear(); - for ( TestExecutionSummary.Failure failure : summary.getFailures() ) - { - failDisplays.add( failure.getTestIdentifier().getDisplayName() ); + for (TestExecutionSummary.Failure failure : summary.getFailures()) { + failDisplays.add(failure.getTestIdentifier().getDisplayName()); } - assertEquals( 3, failDisplays.size() ); - assertTrue( failDisplays.contains( "Fails twice" ) ); - assertTrue( failDisplays.contains( "testAlwaysFail()" ) ); - assertTrue( failDisplays.contains( "testAlwaysError()" ) ); + assertEquals(3, failDisplays.size()); + assertTrue(failDisplays.contains("Fails twice")); + assertTrue(failDisplays.contains("testAlwaysFail()")); + assertTrue(failDisplays.contains("testAlwaysError()")); // now only one failure should remain - summary = executionListener.summaries.get( 2 ); - assertEquals( 3, summary.getTestsFoundCount() ); - assertEquals( 3, summary.getTestsStartedCount() ); - assertEquals( 0, summary.getTestsSkippedCount() ); - assertEquals( 1, summary.getTestsSucceededCount() ); - assertEquals( 0, summary.getTestsAbortedCount() ); - assertEquals( 2, summary.getTestsFailedCount() ); + summary = executionListener.summaries.get(2); + assertEquals(3, summary.getTestsFoundCount()); + assertEquals(3, summary.getTestsStartedCount()); + assertEquals(0, summary.getTestsSkippedCount()); + assertEquals(1, summary.getTestsSucceededCount()); + assertEquals(0, summary.getTestsAbortedCount()); + assertEquals(2, summary.getTestsFailedCount()); failDisplays.clear(); - for ( TestExecutionSummary.Failure failure : summary.getFailures() ) - { - failDisplays.add( failure.getTestIdentifier().getDisplayName() ); + for (TestExecutionSummary.Failure failure : summary.getFailures()) { + failDisplays.add(failure.getTestIdentifier().getDisplayName()); } - assertEquals( 2, failDisplays.size() ); - assertTrue( failDisplays.contains( "testAlwaysFail()" ) ); - assertTrue( failDisplays.contains( "testAlwaysError()" ) ); + assertEquals(2, failDisplays.size()); + assertTrue(failDisplays.contains("testAlwaysFail()")); + assertTrue(failDisplays.contains("testAlwaysError()")); } @Test - public void rerunWithSuccess() - throws Exception - { + public void rerunWithSuccess() throws Exception { Launcher launcher = LauncherFactory.create(); ProviderParameters parameters = providerParametersMock(); // Mock the rerun variable - when( parameters.getTestRequest().getRerunFailingTestsCount() ).thenReturn( 2 ); - when( parameters.getProviderProperties() ) - .thenReturn( singletonMap( JUnitPlatformProvider.CONFIGURATION_PARAMETERS, - "forkCount = 1\nreuseForks = true" ) ); + when(parameters.getTestRequest().getRerunFailingTestsCount()).thenReturn(2); + when(parameters.getProviderProperties()) + .thenReturn(singletonMap( + JUnitPlatformProvider.CONFIGURATION_PARAMETERS, "forkCount = 1\nreuseForks = true")); - JUnitPlatformProvider provider = new JUnitPlatformProvider( parameters, launcher ); + JUnitPlatformProvider provider = new JUnitPlatformProvider(parameters, launcher); TestPlanSummaryListener executionListener = new TestPlanSummaryListener(); - launcher.registerTestExecutionListeners( executionListener ); + launcher.registerTestExecutionListeners(executionListener); - invokeProvider( provider, TestClass5.class ); + invokeProvider(provider, TestClass5.class); - assertThat( executionListener.summaries ).hasSize( 3 ); - TestExecutionSummary summary = executionListener.summaries.get( 0 ); - assertEquals( 1, summary.getTestsFoundCount() ); - assertEquals( 1, summary.getTestsStartedCount() ); - assertEquals( 0, summary.getTestsSucceededCount() ); - assertEquals( 1, summary.getTestsFailedCount() ); + assertThat(executionListener.summaries).hasSize(3); + TestExecutionSummary summary = executionListener.summaries.get(0); + assertEquals(1, summary.getTestsFoundCount()); + assertEquals(1, summary.getTestsStartedCount()); + assertEquals(0, summary.getTestsSucceededCount()); + assertEquals(1, summary.getTestsFailedCount()); - summary = executionListener.summaries.get( 1 ); - assertEquals( 1, summary.getTestsFoundCount() ); - assertEquals( 1, summary.getTestsStartedCount() ); - assertEquals( 0, summary.getTestsSucceededCount() ); - assertEquals( 1, summary.getTestsFailedCount() ); + summary = executionListener.summaries.get(1); + assertEquals(1, summary.getTestsFoundCount()); + assertEquals(1, summary.getTestsStartedCount()); + assertEquals(0, summary.getTestsSucceededCount()); + assertEquals(1, summary.getTestsFailedCount()); - summary = executionListener.summaries.get( 2 ); - assertEquals( 1, summary.getTestsFoundCount() ); - assertEquals( 1, summary.getTestsStartedCount() ); - assertEquals( 1, summary.getTestsSucceededCount() ); - assertEquals( 0, summary.getTestsFailedCount() ); + summary = executionListener.summaries.get(2); + assertEquals(1, summary.getTestsFoundCount()); + assertEquals(1, summary.getTestsStartedCount()); + assertEquals(1, summary.getTestsSucceededCount()); + assertEquals(0, summary.getTestsFailedCount()); } @Test - public void runDisplayNameTest() throws Exception - { + public void runDisplayNameTest() throws Exception { Launcher launcher = LauncherFactory.create(); ProviderParameters parameters = providerParametersMock(); - JUnitPlatformProvider provider = new JUnitPlatformProvider( parameters, launcher ); + JUnitPlatformProvider provider = new JUnitPlatformProvider(parameters, launcher); - TestReportListener listener = mock( TestReportListener.class ); - ArgumentCaptor entryCaptor = ArgumentCaptor.forClass( ReportEntry.class ); - RunListenerAdapter adapter = new RunListenerAdapter( listener ); - adapter.setRunMode( NORMAL_RUN ); + TestReportListener listener = mock(TestReportListener.class); + ArgumentCaptor entryCaptor = ArgumentCaptor.forClass(ReportEntry.class); + RunListenerAdapter adapter = new RunListenerAdapter(listener); + adapter.setRunMode(NORMAL_RUN); - launcher.registerTestExecutionListeners( adapter ); + launcher.registerTestExecutionListeners(adapter); - invokeProvider( provider, DisplayNameTest.class ); + invokeProvider(provider, DisplayNameTest.class); - verify( listener, times( 1 ) ).testStarting( entryCaptor.capture() ); + verify(listener, times(1)).testStarting(entryCaptor.capture()); List reportEntries = entryCaptor.getAllValues(); - assertEquals( 1, reportEntries.size() ); + assertEquals(1, reportEntries.size()); - assertEquals( DisplayNameTest.class.getName(), reportEntries.get( 0 ).getSourceName() ); - assertEquals( "<< ✨ >>", reportEntries.get( 0 ).getSourceText() ); - assertEquals( "test1", reportEntries.get( 0 ).getName() ); - assertEquals( "73$71 ✔", reportEntries.get( 0 ).getNameText() ); + assertEquals(DisplayNameTest.class.getName(), reportEntries.get(0).getSourceName()); + assertEquals("<< ✨ >>", reportEntries.get(0).getSourceText()); + assertEquals("test1", reportEntries.get(0).getName()); + assertEquals("73$71 ✔", reportEntries.get(0).getNameText()); } @Test - public void runNestingTest() throws Exception - { + public void runNestingTest() throws Exception { Launcher launcher = LauncherFactory.create(); ProviderParameters parameters = providerParametersMock(); - JUnitPlatformProvider provider = new JUnitPlatformProvider( parameters, launcher ); + JUnitPlatformProvider provider = new JUnitPlatformProvider(parameters, launcher); - TestReportListener listener = mock( TestReportListener.class ); - ArgumentCaptor entryCaptor = ArgumentCaptor.forClass( ReportEntry.class ); - RunListenerAdapter adapter = new RunListenerAdapter( listener ); - adapter.setRunMode( NORMAL_RUN ); + TestReportListener listener = mock(TestReportListener.class); + ArgumentCaptor entryCaptor = ArgumentCaptor.forClass(ReportEntry.class); + RunListenerAdapter adapter = new RunListenerAdapter(listener); + adapter.setRunMode(NORMAL_RUN); - launcher.registerTestExecutionListeners( adapter ); + launcher.registerTestExecutionListeners(adapter); - invokeProvider( provider, NestingTest.class ); + invokeProvider(provider, NestingTest.class); - verify( listener, times( 2 ) ).testStarting( entryCaptor.capture() ); + verify(listener, times(2)).testStarting(entryCaptor.capture()); List reportEntries = entryCaptor.getAllValues(); - assertEquals( 2, reportEntries.size() ); + assertEquals(2, reportEntries.size()); - assertEquals( NestingTest.Level1NestedTest.class.getName(), - reportEntries.get( 0 ).getSourceName() ); - assertNull( reportEntries.get( 0 ).getSourceText() ); - assertEquals( "level1test", reportEntries.get( 0 ).getName() ); - assertNull( reportEntries.get( 0 ).getNameText() ); + assertEquals( + NestingTest.Level1NestedTest.class.getName(), + reportEntries.get(0).getSourceName()); + assertNull(reportEntries.get(0).getSourceText()); + assertEquals("level1test", reportEntries.get(0).getName()); + assertNull(reportEntries.get(0).getNameText()); - assertEquals( NestingTest.Level1NestedTest.Level2NestedTest.class.getName(), - reportEntries.get( 1 ).getSourceName() ); - assertNull( reportEntries.get( 1 ).getSourceText() ); - assertEquals( "level2test", reportEntries.get( 1 ).getName() ); - assertNull( reportEntries.get( 1 ).getNameText() ); + assertEquals( + NestingTest.Level1NestedTest.Level2NestedTest.class.getName(), + reportEntries.get(1).getSourceName()); + assertNull(reportEntries.get(1).getSourceText()); + assertEquals("level2test", reportEntries.get(1).getName()); + assertNull(reportEntries.get(1).getNameText()); } @Test - public void detectSkippedParameterized() throws Exception - { + public void detectSkippedParameterized() throws Exception { Launcher launcher = LauncherFactory.create(); ProviderParameters parameters = providerParametersMock(); - JUnitPlatformProvider provider = new JUnitPlatformProvider( parameters, launcher ); + JUnitPlatformProvider provider = new JUnitPlatformProvider(parameters, launcher); TestPlanSummaryListener executionListener = new TestPlanSummaryListener(); - TestReportListener listener = mock( TestReportListener.class ); - ArgumentCaptor entryCaptor = ArgumentCaptor.forClass( ReportEntry.class ); - RunListenerAdapter adapter = new RunListenerAdapter( listener ); - adapter.setRunMode( NORMAL_RUN ); + TestReportListener listener = mock(TestReportListener.class); + ArgumentCaptor entryCaptor = ArgumentCaptor.forClass(ReportEntry.class); + RunListenerAdapter adapter = new RunListenerAdapter(listener); + adapter.setRunMode(NORMAL_RUN); - launcher.registerTestExecutionListeners( executionListener, adapter ); + launcher.registerTestExecutionListeners(executionListener, adapter); - invokeProvider( provider, DisabledParameterizedTest.class ); + invokeProvider(provider, DisabledParameterizedTest.class); - assertThat( executionListener.summaries ).hasSize( 1 ); + assertThat(executionListener.summaries).hasSize(1); - verify( listener, times( 1 ) ).testSetCompleted( any() ); - verify( listener, times( 1 ) ).testSkipped( entryCaptor.capture() ); + verify(listener, times(1)).testSetCompleted(any()); + verify(listener, times(1)).testSkipped(entryCaptor.capture()); List reportEntries = entryCaptor.getAllValues(); - assertEquals( DisabledParameterizedTest.class.getName(), reportEntries.get( 0 ).getSourceName() ); - assertNull( reportEntries.get( 0 ).getSourceText() ); - assertEquals( "disabledParameterized(String)", reportEntries.get( 0 ).getName() ); - assertNull( reportEntries.get( 0 ).getNameText() ); - - TestExecutionSummary summary = executionListener.summaries.get( 0 ); - assertEquals( 0, summary.getTestsFoundCount() ); - assertEquals( 0, summary.getTestsStartedCount() ); - assertEquals( 0, summary.getTestsSucceededCount() ); - assertEquals( 0, summary.getTestsFailedCount() ); - assertEquals( 0, summary.getTestsSkippedCount() ); - assertEquals( 3, summary.getContainersFoundCount() ); - assertEquals( 2, summary.getContainersStartedCount() ); - assertEquals( 2, summary.getContainersSucceededCount() ); - assertEquals( 0, summary.getContainersFailedCount() ); - assertEquals( 1, summary.getContainersSkippedCount() ); + assertEquals( + DisabledParameterizedTest.class.getName(), reportEntries.get(0).getSourceName()); + assertNull(reportEntries.get(0).getSourceText()); + assertEquals("disabledParameterized(String)", reportEntries.get(0).getName()); + assertNull(reportEntries.get(0).getNameText()); + + TestExecutionSummary summary = executionListener.summaries.get(0); + assertEquals(0, summary.getTestsFoundCount()); + assertEquals(0, summary.getTestsStartedCount()); + assertEquals(0, summary.getTestsSucceededCount()); + assertEquals(0, summary.getTestsFailedCount()); + assertEquals(0, summary.getTestsSkippedCount()); + assertEquals(3, summary.getContainersFoundCount()); + assertEquals(2, summary.getContainersStartedCount()); + assertEquals(2, summary.getContainersSucceededCount()); + assertEquals(0, summary.getContainersFailedCount()); + assertEquals(1, summary.getContainersSkippedCount()); } @Test - public void detectErroredParameterized() - throws Exception - { + public void detectErroredParameterized() throws Exception { Launcher launcher = LauncherFactory.create(); ProviderParameters parameters = providerParametersMock(); - JUnitPlatformProvider provider = new JUnitPlatformProvider( parameters, launcher ); + JUnitPlatformProvider provider = new JUnitPlatformProvider(parameters, launcher); TestPlanSummaryListener executionListener = new TestPlanSummaryListener(); - TestReportListener listener = mock( TestReportListener.class ); - ArgumentCaptor entryCaptor = ArgumentCaptor.forClass( ReportEntry.class ); - RunListenerAdapter adapter = new RunListenerAdapter( listener ); - adapter.setRunMode( NORMAL_RUN ); + TestReportListener listener = mock(TestReportListener.class); + ArgumentCaptor entryCaptor = ArgumentCaptor.forClass(ReportEntry.class); + RunListenerAdapter adapter = new RunListenerAdapter(listener); + adapter.setRunMode(NORMAL_RUN); - launcher.registerTestExecutionListeners( executionListener, adapter ); + launcher.registerTestExecutionListeners(executionListener, adapter); - invokeProvider( provider, TestClass8.class ); + invokeProvider(provider, TestClass8.class); - assertThat( executionListener.summaries ).hasSize( 1 ); + assertThat(executionListener.summaries).hasSize(1); - verify( listener, times( 1 ) ).testSetCompleted( any() ); - verify( listener, times( 1 ) ).testError( entryCaptor.capture() ); + verify(listener, times(1)).testSetCompleted(any()); + verify(listener, times(1)).testError(entryCaptor.capture()); List reportEntries = entryCaptor.getAllValues(); - assertEquals( TestClass8.class.getName(), reportEntries.get( 0 ).getSourceName() ); - assertNull( reportEntries.get( 0 ).getSourceText() ); - assertEquals( "testParameterizedTestCases", reportEntries.get( 0 ).getName() ); - assertNull( reportEntries.get( 0 ).getNameText() ); + assertEquals(TestClass8.class.getName(), reportEntries.get(0).getSourceName()); + assertNull(reportEntries.get(0).getSourceText()); + assertEquals("testParameterizedTestCases", reportEntries.get(0).getName()); + assertNull(reportEntries.get(0).getNameText()); - TestExecutionSummary summary = executionListener.summaries.get( 0 ); - assertEquals( 0, summary.getTestsFoundCount() ); - assertEquals( 1, summary.getContainersFailedCount() ); - assertEquals( 0, summary.getTestsStartedCount() ); - assertEquals( 0, summary.getTestsSucceededCount() ); - assertEquals( 0, summary.getTestsFailedCount() ); + TestExecutionSummary summary = executionListener.summaries.get(0); + assertEquals(0, summary.getTestsFoundCount()); + assertEquals(1, summary.getContainersFailedCount()); + assertEquals(0, summary.getTestsStartedCount()); + assertEquals(0, summary.getTestsSucceededCount()); + assertEquals(0, summary.getTestsFailedCount()); } @Test - public void detectFailedParameterized() - throws Exception - { + public void detectFailedParameterized() throws Exception { Launcher launcher = LauncherFactory.create(); ProviderParameters parameters = providerParametersMock(); - JUnitPlatformProvider provider = new JUnitPlatformProvider( parameters, launcher ); + JUnitPlatformProvider provider = new JUnitPlatformProvider(parameters, launcher); TestPlanSummaryListener executionListener = new TestPlanSummaryListener(); - TestReportListener listener = mock( TestReportListener.class ); - ArgumentCaptor entryCaptor = ArgumentCaptor.forClass( ReportEntry.class ); - RunListenerAdapter adapter = new RunListenerAdapter( listener ); - adapter.setRunMode( NORMAL_RUN ); + TestReportListener listener = mock(TestReportListener.class); + ArgumentCaptor entryCaptor = ArgumentCaptor.forClass(ReportEntry.class); + RunListenerAdapter adapter = new RunListenerAdapter(listener); + adapter.setRunMode(NORMAL_RUN); - launcher.registerTestExecutionListeners( executionListener, adapter ); + launcher.registerTestExecutionListeners(executionListener, adapter); - invokeProvider( provider, TestClass9.class ); + invokeProvider(provider, TestClass9.class); - assertThat( executionListener.summaries ).hasSize( 1 ); + assertThat(executionListener.summaries).hasSize(1); - verify( listener, times( 1 ) ).testSetCompleted( any() ); - verify( listener, times( 1 ) ).testFailed( entryCaptor.capture() ); + verify(listener, times(1)).testSetCompleted(any()); + verify(listener, times(1)).testFailed(entryCaptor.capture()); List reportEntries = entryCaptor.getAllValues(); - assertEquals( TestClass9.class.getName(), reportEntries.get( 0 ).getSourceName() ); - assertNull( reportEntries.get( 0 ).getSourceText() ); - assertEquals( "testParameterizedTestCases", reportEntries.get( 0 ).getName() ); - assertNull( reportEntries.get( 0 ).getNameText() ); + assertEquals(TestClass9.class.getName(), reportEntries.get(0).getSourceName()); + assertNull(reportEntries.get(0).getSourceText()); + assertEquals("testParameterizedTestCases", reportEntries.get(0).getName()); + assertNull(reportEntries.get(0).getNameText()); - TestExecutionSummary summary = executionListener.summaries.get( 0 ); - assertEquals( 0, summary.getTestsFoundCount() ); - assertEquals( 1, summary.getContainersFailedCount() ); - assertEquals( 0, summary.getTestsStartedCount() ); - assertEquals( 0, summary.getTestsSucceededCount() ); - assertEquals( 0, summary.getTestsFailedCount() ); + TestExecutionSummary summary = executionListener.summaries.get(0); + assertEquals(0, summary.getTestsFoundCount()); + assertEquals(1, summary.getContainersFailedCount()); + assertEquals(0, summary.getTestsStartedCount()); + assertEquals(0, summary.getTestsSucceededCount()); + assertEquals(0, summary.getTestsFailedCount()); } @Test - public void rerunParameterized() - throws Exception - { + public void rerunParameterized() throws Exception { Launcher launcher = LauncherFactory.create(); ProviderParameters parameters = providerParametersMock(); // Mock the rerun variable - when( parameters.getTestRequest().getRerunFailingTestsCount() ).thenReturn( 2 ); - when( parameters.getProviderProperties() ) - .thenReturn( singletonMap( JUnitPlatformProvider.CONFIGURATION_PARAMETERS, - "forkCount = 1\nreuseForks = true" ) ); + when(parameters.getTestRequest().getRerunFailingTestsCount()).thenReturn(2); + when(parameters.getProviderProperties()) + .thenReturn(singletonMap( + JUnitPlatformProvider.CONFIGURATION_PARAMETERS, "forkCount = 1\nreuseForks = true")); - JUnitPlatformProvider provider = new JUnitPlatformProvider( parameters, launcher ); + JUnitPlatformProvider provider = new JUnitPlatformProvider(parameters, launcher); TestPlanSummaryListener executionListener = new TestPlanSummaryListener(); - TestReportListener listener = mock( TestReportListener.class ); - ArgumentCaptor entryCaptor = ArgumentCaptor.forClass( ReportEntry.class ); - RunListenerAdapter adapter = new RunListenerAdapter( listener ); - adapter.setRunMode( NORMAL_RUN ); + TestReportListener listener = mock(TestReportListener.class); + ArgumentCaptor entryCaptor = ArgumentCaptor.forClass(ReportEntry.class); + RunListenerAdapter adapter = new RunListenerAdapter(listener); + adapter.setRunMode(NORMAL_RUN); - launcher.registerTestExecutionListeners( executionListener, adapter ); + launcher.registerTestExecutionListeners(executionListener, adapter); - invokeProvider( provider, TestClass7.class ); + invokeProvider(provider, TestClass7.class); - assertThat( executionListener.summaries ).hasSize( 3 ); + assertThat(executionListener.summaries).hasSize(3); - verify( listener, times( 4 ) ).testStarting( entryCaptor.capture() ); + verify(listener, times(4)).testStarting(entryCaptor.capture()); List reportEntries = entryCaptor.getAllValues(); - assertEquals( TestClass7.class.getName(), reportEntries.get( 0 ).getSourceName() ); - assertNull( reportEntries.get( 0 ).getSourceText() ); - assertEquals( "testParameterizedTestCases(String, boolean)[1]", reportEntries.get( 0 ).getName() ); - assertEquals( "testParameterizedTestCases(String, boolean)[1] Always pass, true", - reportEntries.get( 0 ).getNameText() ); - - assertEquals( TestClass7.class.getName(), reportEntries.get( 1 ).getSourceName() ); - assertNull( reportEntries.get( 1 ).getSourceText() ); - assertEquals( "testParameterizedTestCases(String, boolean)[2]", reportEntries.get( 1 ).getName() ); - assertEquals( "testParameterizedTestCases(String, boolean)[2] Always fail, false", - reportEntries.get( 1 ).getNameText() ); - - assertEquals( TestClass7.class.getName(), reportEntries.get( 2 ).getSourceName() ); - assertNull( reportEntries.get( 2 ).getSourceText() ); - assertEquals( "testParameterizedTestCases(String, boolean)[2]", reportEntries.get( 2 ).getName() ); - assertEquals( "testParameterizedTestCases(String, boolean)[2] Always fail, false", - reportEntries.get( 2 ).getNameText() ); - - assertEquals( TestClass7.class.getName(), reportEntries.get( 3 ).getSourceName() ); - assertNull( reportEntries.get( 3 ).getSourceText() ); - assertEquals( "testParameterizedTestCases(String, boolean)[2]", reportEntries.get( 3 ).getName() ); - assertEquals( "testParameterizedTestCases(String, boolean)[2] Always fail, false", - reportEntries.get( 3 ).getNameText() ); - - TestExecutionSummary summary = executionListener.summaries.get( 0 ); - assertEquals( 2, summary.getTestsFoundCount() ); - assertEquals( 2, summary.getTestsStartedCount() ); - assertEquals( 1, summary.getTestsSucceededCount() ); - assertEquals( 1, summary.getTestsFailedCount() ); - - summary = executionListener.summaries.get( 1 ); - assertEquals( 1, summary.getTestsFoundCount() ); - assertEquals( 1, summary.getTestsStartedCount() ); - assertEquals( 0, summary.getTestsSucceededCount() ); - assertEquals( 1, summary.getTestsFailedCount() ); - - summary = executionListener.summaries.get( 2 ); - assertEquals( 1, summary.getTestsFoundCount() ); - assertEquals( 1, summary.getTestsStartedCount() ); - assertEquals( 0, summary.getTestsSucceededCount() ); - assertEquals( 1, summary.getTestsFailedCount() ); + assertEquals(TestClass7.class.getName(), reportEntries.get(0).getSourceName()); + assertNull(reportEntries.get(0).getSourceText()); + assertEquals( + "testParameterizedTestCases(String, boolean)[1]", + reportEntries.get(0).getName()); + assertEquals( + "testParameterizedTestCases(String, boolean)[1] Always pass, true", + reportEntries.get(0).getNameText()); + + assertEquals(TestClass7.class.getName(), reportEntries.get(1).getSourceName()); + assertNull(reportEntries.get(1).getSourceText()); + assertEquals( + "testParameterizedTestCases(String, boolean)[2]", + reportEntries.get(1).getName()); + assertEquals( + "testParameterizedTestCases(String, boolean)[2] Always fail, false", + reportEntries.get(1).getNameText()); + + assertEquals(TestClass7.class.getName(), reportEntries.get(2).getSourceName()); + assertNull(reportEntries.get(2).getSourceText()); + assertEquals( + "testParameterizedTestCases(String, boolean)[2]", + reportEntries.get(2).getName()); + assertEquals( + "testParameterizedTestCases(String, boolean)[2] Always fail, false", + reportEntries.get(2).getNameText()); + + assertEquals(TestClass7.class.getName(), reportEntries.get(3).getSourceName()); + assertNull(reportEntries.get(3).getSourceText()); + assertEquals( + "testParameterizedTestCases(String, boolean)[2]", + reportEntries.get(3).getName()); + assertEquals( + "testParameterizedTestCases(String, boolean)[2] Always fail, false", + reportEntries.get(3).getNameText()); + + TestExecutionSummary summary = executionListener.summaries.get(0); + assertEquals(2, summary.getTestsFoundCount()); + assertEquals(2, summary.getTestsStartedCount()); + assertEquals(1, summary.getTestsSucceededCount()); + assertEquals(1, summary.getTestsFailedCount()); + + summary = executionListener.summaries.get(1); + assertEquals(1, summary.getTestsFoundCount()); + assertEquals(1, summary.getTestsStartedCount()); + assertEquals(0, summary.getTestsSucceededCount()); + assertEquals(1, summary.getTestsFailedCount()); + + summary = executionListener.summaries.get(2); + assertEquals(1, summary.getTestsFoundCount()); + assertEquals(1, summary.getTestsStartedCount()); + assertEquals(0, summary.getTestsSucceededCount()); + assertEquals(1, summary.getTestsFailedCount()); } @Test - public void allDiscoveredTestsAreInvokedForNullArgument() - throws Exception - { + public void allDiscoveredTestsAreInvokedForNullArgument() throws Exception { TestReportListener runListener = runListenerMock(); - ProviderParameters providerParameters = - providerParametersMock( runListener, TestClass1.class, TestClass2.class ); + ProviderParameters providerParameters = providerParametersMock(runListener, TestClass1.class, TestClass2.class); Launcher launcher = LauncherFactory.create(); - JUnitPlatformProvider provider = new JUnitPlatformProvider( providerParameters, launcher ); + JUnitPlatformProvider provider = new JUnitPlatformProvider(providerParameters, launcher); TestPlanSummaryListener executionListener = new TestPlanSummaryListener(); - launcher.registerTestExecutionListeners( executionListener ); - - invokeProvider( provider, null ); - - InOrder inOrder = inOrder( runListener ); - - ArgumentCaptor report = ArgumentCaptor.forClass( SimpleReportEntry.class ); - inOrder.verify( runListener ) - .testSetStarting( report.capture() ); - assertThat( report.getValue().getSourceName() ) - .isEqualTo( TestClass1.class.getName() ); - assertThat( report.getValue().getName() ) - .isNull(); - - report = ArgumentCaptor.forClass( SimpleReportEntry.class ); - inOrder.verify( runListener ) - .testSetCompleted( report.capture() ); - assertThat( report.getValue().getSourceName() ) - .isEqualTo( TestClass1.class.getName() ); - assertThat( report.getValue().getName() ) - .isNull(); - - report = ArgumentCaptor.forClass( SimpleReportEntry.class ); - inOrder.verify( runListener ) - .testSetStarting( report.capture() ); - assertThat( report.getValue().getSourceName() ) - .isEqualTo( TestClass2.class.getName() ); - assertThat( report.getValue().getName() ) - .isNull(); - - report = ArgumentCaptor.forClass( SimpleReportEntry.class ); - inOrder.verify( runListener ) - .testSetCompleted( report.capture() ); - assertThat( report.getValue().getSourceName() ) - .isEqualTo( TestClass2.class.getName() ); - assertThat( report.getValue().getName() ) - .isNull(); - - assertThat( executionListener.summaries ).hasSize( 1 ); - TestExecutionSummary summary = executionListener.summaries.get( 0 ); - assertEquals( TestClass1.TESTS_FOUND + TestClass2.TESTS_FOUND, summary.getTestsFoundCount() ); - assertEquals( - TestClass1.TESTS_STARTED + TestClass2.TESTS_STARTED, summary.getTestsStartedCount() ); - assertEquals( - TestClass1.TESTS_SKIPPED + TestClass2.TESTS_SKIPPED, summary.getTestsSkippedCount() ); - assertEquals( - TestClass1.TESTS_SUCCEEDED + TestClass2.TESTS_SUCCEEDED, summary.getTestsSucceededCount() ); - assertEquals( - TestClass1.TESTS_ABORTED + TestClass2.TESTS_ABORTED, summary.getTestsAbortedCount() ); - assertEquals( TestClass1.TESTS_FAILED + TestClass2.TESTS_FAILED, summary.getTestsFailedCount() ); + launcher.registerTestExecutionListeners(executionListener); + + invokeProvider(provider, null); + + InOrder inOrder = inOrder(runListener); + + ArgumentCaptor report = ArgumentCaptor.forClass(SimpleReportEntry.class); + inOrder.verify(runListener).testSetStarting(report.capture()); + assertThat(report.getValue().getSourceName()).isEqualTo(TestClass1.class.getName()); + assertThat(report.getValue().getName()).isNull(); + + report = ArgumentCaptor.forClass(SimpleReportEntry.class); + inOrder.verify(runListener).testSetCompleted(report.capture()); + assertThat(report.getValue().getSourceName()).isEqualTo(TestClass1.class.getName()); + assertThat(report.getValue().getName()).isNull(); + + report = ArgumentCaptor.forClass(SimpleReportEntry.class); + inOrder.verify(runListener).testSetStarting(report.capture()); + assertThat(report.getValue().getSourceName()).isEqualTo(TestClass2.class.getName()); + assertThat(report.getValue().getName()).isNull(); + + report = ArgumentCaptor.forClass(SimpleReportEntry.class); + inOrder.verify(runListener).testSetCompleted(report.capture()); + assertThat(report.getValue().getSourceName()).isEqualTo(TestClass2.class.getName()); + assertThat(report.getValue().getName()).isNull(); + + assertThat(executionListener.summaries).hasSize(1); + TestExecutionSummary summary = executionListener.summaries.get(0); + assertEquals(TestClass1.TESTS_FOUND + TestClass2.TESTS_FOUND, summary.getTestsFoundCount()); + assertEquals(TestClass1.TESTS_STARTED + TestClass2.TESTS_STARTED, summary.getTestsStartedCount()); + assertEquals(TestClass1.TESTS_SKIPPED + TestClass2.TESTS_SKIPPED, summary.getTestsSkippedCount()); + assertEquals(TestClass1.TESTS_SUCCEEDED + TestClass2.TESTS_SUCCEEDED, summary.getTestsSucceededCount()); + assertEquals(TestClass1.TESTS_ABORTED + TestClass2.TESTS_ABORTED, summary.getTestsAbortedCount()); + assertEquals(TestClass1.TESTS_FAILED + TestClass2.TESTS_FAILED, summary.getTestsFailedCount()); } @Test - public void outputIsCaptured() - throws Exception - { + public void outputIsCaptured() throws Exception { Launcher launcher = LauncherFactory.create(); TestReportListener runListener = runListenerMock(); - JUnitPlatformProvider provider = new JUnitPlatformProvider( providerParametersMock( runListener ), launcher ); + JUnitPlatformProvider provider = new JUnitPlatformProvider(providerParametersMock(runListener), launcher); - invokeProvider( provider, VerboseTestClass.class ); + invokeProvider(provider, VerboseTestClass.class); - ArgumentCaptor captor = ArgumentCaptor.forClass( TestOutputReportEntry.class ); - verify( runListener, times( 2 ) ) - .writeTestOutput( captor.capture() ); - assertThat( captor.getAllValues().get( 0 ).getLog() ) - .isEqualTo( "stdout" ); - assertThat( captor.getAllValues().get( 1 ).getLog() ) - .isEqualTo( "stderr" ); + ArgumentCaptor captor = ArgumentCaptor.forClass(TestOutputReportEntry.class); + verify(runListener, times(2)).writeTestOutput(captor.capture()); + assertThat(captor.getAllValues().get(0).getLog()).isEqualTo("stdout"); + assertThat(captor.getAllValues().get(1).getLog()).isEqualTo("stderr"); } @Test - public void onlyGroupsIsDeclared() - { - Map properties = singletonMap( TESTNG_GROUPS_PROP, "groupOne, groupTwo" ); + public void onlyGroupsIsDeclared() { + Map properties = singletonMap(TESTNG_GROUPS_PROP, "groupOne, groupTwo"); - ProviderParameters providerParameters = providerParametersMock( TestClass1.class ); - when( providerParameters.getProviderProperties() ).thenReturn( properties ); + ProviderParameters providerParameters = providerParametersMock(TestClass1.class); + when(providerParameters.getProviderProperties()).thenReturn(properties); - JUnitPlatformProvider provider = new JUnitPlatformProvider( providerParameters ); + JUnitPlatformProvider provider = new JUnitPlatformProvider(providerParameters); - assertEquals( 1, provider.getFilters().length ); + assertEquals(1, provider.getFilters().length); } @Test - public void onlyExcludeTagsIsDeclared() - { - Map properties = singletonMap( TESTNG_EXCLUDEDGROUPS_PROP, "tagOne, tagTwo" ); + public void onlyExcludeTagsIsDeclared() { + Map properties = singletonMap(TESTNG_EXCLUDEDGROUPS_PROP, "tagOne, tagTwo"); - ProviderParameters providerParameters = providerParametersMock( TestClass1.class ); - when( providerParameters.getProviderProperties() ).thenReturn( properties ); + ProviderParameters providerParameters = providerParametersMock(TestClass1.class); + when(providerParameters.getProviderProperties()).thenReturn(properties); - JUnitPlatformProvider provider = new JUnitPlatformProvider( providerParameters ); + JUnitPlatformProvider provider = new JUnitPlatformProvider(providerParameters); - assertEquals( 1, provider.getFilters().length ); + assertEquals(1, provider.getFilters().length); } @Test - public void noFiltersAreCreatedIfTagsAreEmpty() - { - Map properties = singletonMap( TESTNG_GROUPS_PROP, "" ); + public void noFiltersAreCreatedIfTagsAreEmpty() { + Map properties = singletonMap(TESTNG_GROUPS_PROP, ""); - ProviderParameters providerParameters = providerParametersMock( TestClass1.class ); - when( providerParameters.getProviderProperties() ).thenReturn( properties ); + ProviderParameters providerParameters = providerParametersMock(TestClass1.class); + when(providerParameters.getProviderProperties()).thenReturn(properties); - JUnitPlatformProvider provider = new JUnitPlatformProvider( providerParameters ); - assertEquals( 0, provider.getFilters().length ); + JUnitPlatformProvider provider = new JUnitPlatformProvider(providerParameters); + assertEquals(0, provider.getFilters().length); } @Test - public void filtersWithEmptyTagsAreNotRegistered() - { + public void filtersWithEmptyTagsAreNotRegistered() { // Here only tagOne is registered as a valid tag and other tags are ignored as they are empty - Map properties = singletonMap( TESTNG_EXCLUDEDGROUPS_PROP, "tagOne," ); + Map properties = singletonMap(TESTNG_EXCLUDEDGROUPS_PROP, "tagOne,"); - ProviderParameters providerParameters = providerParametersMock( TestClass1.class ); - when( providerParameters.getProviderProperties() ).thenReturn( properties ); + ProviderParameters providerParameters = providerParametersMock(TestClass1.class); + when(providerParameters.getProviderProperties()).thenReturn(properties); - JUnitPlatformProvider provider = new JUnitPlatformProvider( providerParameters ); - assertEquals( 1, provider.getFilters().length ); + JUnitPlatformProvider provider = new JUnitPlatformProvider(providerParameters); + assertEquals(1, provider.getFilters().length); } @Test - public void bothIncludeAndExcludeAreAllowed() - { + public void bothIncludeAndExcludeAreAllowed() { Map properties = new HashMap<>(); - properties.put( TESTNG_GROUPS_PROP, "tagOne, tagTwo" ); - properties.put( TESTNG_EXCLUDEDGROUPS_PROP, "tagThree, tagFour" ); + properties.put(TESTNG_GROUPS_PROP, "tagOne, tagTwo"); + properties.put(TESTNG_EXCLUDEDGROUPS_PROP, "tagThree, tagFour"); - ProviderParameters providerParameters = providerParametersMock( TestClass1.class ); - when( providerParameters.getProviderProperties() ).thenReturn( properties ); + ProviderParameters providerParameters = providerParametersMock(TestClass1.class); + when(providerParameters.getProviderProperties()).thenReturn(properties); - JUnitPlatformProvider provider = new JUnitPlatformProvider( providerParameters ); + JUnitPlatformProvider provider = new JUnitPlatformProvider(providerParameters); - assertEquals( 2, provider.getFilters().length ); + assertEquals(2, provider.getFilters().length); } @Test - public void tagExpressionsAreSupportedForIncludeTagsContainingVerticalBar() - { + public void tagExpressionsAreSupportedForIncludeTagsContainingVerticalBar() { Map properties = new HashMap<>(); - properties.put( TESTNG_GROUPS_PROP, "tagOne | tagTwo" ); - properties.put( TESTNG_EXCLUDEDGROUPS_PROP, "tagThree | tagFour" ); + properties.put(TESTNG_GROUPS_PROP, "tagOne | tagTwo"); + properties.put(TESTNG_EXCLUDEDGROUPS_PROP, "tagThree | tagFour"); - ProviderParameters providerParameters = providerParametersMock( TestClass1.class ); - when( providerParameters.getProviderProperties() ).thenReturn( properties ); + ProviderParameters providerParameters = providerParametersMock(TestClass1.class); + when(providerParameters.getProviderProperties()).thenReturn(properties); - JUnitPlatformProvider provider = new JUnitPlatformProvider( providerParameters ); + JUnitPlatformProvider provider = new JUnitPlatformProvider(providerParameters); - assertEquals( 2, provider.getFilters().length ); + assertEquals(2, provider.getFilters().length); } @Test - public void tagExpressionsAreSupportedForIncludeTagsContainingAmpersand() - { + public void tagExpressionsAreSupportedForIncludeTagsContainingAmpersand() { Map properties = new HashMap<>(); - properties.put( TESTNG_GROUPS_PROP, "tagOne & !tagTwo" ); - properties.put( TESTNG_EXCLUDEDGROUPS_PROP, "tagThree & !tagFour" ); + properties.put(TESTNG_GROUPS_PROP, "tagOne & !tagTwo"); + properties.put(TESTNG_EXCLUDEDGROUPS_PROP, "tagThree & !tagFour"); - ProviderParameters providerParameters = providerParametersMock( TestClass1.class ); - when( providerParameters.getProviderProperties() ).thenReturn( properties ); + ProviderParameters providerParameters = providerParametersMock(TestClass1.class); + when(providerParameters.getProviderProperties()).thenReturn(properties); - JUnitPlatformProvider provider = new JUnitPlatformProvider( providerParameters ); + JUnitPlatformProvider provider = new JUnitPlatformProvider(providerParameters); - assertEquals( 2, provider.getFilters().length ); + assertEquals(2, provider.getFilters().length); } @Test - public void onlyIncludeJunit5EnginesIsDeclared() - { - Map properties = singletonMap( INCLUDE_JUNIT5_ENGINES_PROP, "engine-one, engine-two" ); + public void onlyIncludeJunit5EnginesIsDeclared() { + Map properties = singletonMap(INCLUDE_JUNIT5_ENGINES_PROP, "engine-one, engine-two"); - ProviderParameters providerParameters = providerParametersMock( TestClass1.class ); - when( providerParameters.getProviderProperties() ).thenReturn( properties ); + ProviderParameters providerParameters = providerParametersMock(TestClass1.class); + when(providerParameters.getProviderProperties()).thenReturn(properties); - JUnitPlatformProvider provider = new JUnitPlatformProvider( providerParameters ); + JUnitPlatformProvider provider = new JUnitPlatformProvider(providerParameters); - assertThat( provider.getFilters() ).hasSize( 1 ); - assertThat( provider.getFilters()[0] ).isInstanceOf( EngineFilter.class ); + assertThat(provider.getFilters()).hasSize(1); + assertThat(provider.getFilters()[0]).isInstanceOf(EngineFilter.class); } @Test - public void onlyExcludeJunit5EnginesIsDeclared() - { - Map properties = singletonMap( EXCLUDE_JUNIT5_ENGINES_PROP, "engine-one, engine-two" ); + public void onlyExcludeJunit5EnginesIsDeclared() { + Map properties = singletonMap(EXCLUDE_JUNIT5_ENGINES_PROP, "engine-one, engine-two"); - ProviderParameters providerParameters = providerParametersMock( TestClass1.class ); - when( providerParameters.getProviderProperties() ).thenReturn( properties ); + ProviderParameters providerParameters = providerParametersMock(TestClass1.class); + when(providerParameters.getProviderProperties()).thenReturn(properties); - JUnitPlatformProvider provider = new JUnitPlatformProvider( providerParameters ); + JUnitPlatformProvider provider = new JUnitPlatformProvider(providerParameters); - assertThat( provider.getFilters() ).hasSize( 1 ); - assertThat( provider.getFilters()[0] ).isInstanceOf( EngineFilter.class ); + assertThat(provider.getFilters()).hasSize(1); + assertThat(provider.getFilters()[0]).isInstanceOf(EngineFilter.class); } @Test - public void noFiltersAreCreatedIfIncludeJunit5EnginesIsEmpty() - { - Map properties = singletonMap( INCLUDE_JUNIT5_ENGINES_PROP, "" ); + public void noFiltersAreCreatedIfIncludeJunit5EnginesIsEmpty() { + Map properties = singletonMap(INCLUDE_JUNIT5_ENGINES_PROP, ""); - ProviderParameters providerParameters = providerParametersMock( TestClass1.class ); - when( providerParameters.getProviderProperties() ).thenReturn( properties ); + ProviderParameters providerParameters = providerParametersMock(TestClass1.class); + when(providerParameters.getProviderProperties()).thenReturn(properties); - JUnitPlatformProvider provider = new JUnitPlatformProvider( providerParameters ); - assertEquals( 0, provider.getFilters().length ); + JUnitPlatformProvider provider = new JUnitPlatformProvider(providerParameters); + assertEquals(0, provider.getFilters().length); - assertThat( provider.getFilters() ).hasSize( 0 ); + assertThat(provider.getFilters()).hasSize(0); } @Test - public void filtersWithEmptyJunitEngineAreNotRegistered() - { + public void filtersWithEmptyJunitEngineAreNotRegistered() { // Here only tagOne is registered as a valid tag and other tags are ignored as they are empty - Map properties = singletonMap( EXCLUDE_JUNIT5_ENGINES_PROP, "engine-one," ); + Map properties = singletonMap(EXCLUDE_JUNIT5_ENGINES_PROP, "engine-one,"); - ProviderParameters providerParameters = providerParametersMock( TestClass1.class ); - when( providerParameters.getProviderProperties() ).thenReturn( properties ); + ProviderParameters providerParameters = providerParametersMock(TestClass1.class); + when(providerParameters.getProviderProperties()).thenReturn(properties); - JUnitPlatformProvider provider = new JUnitPlatformProvider( providerParameters ); + JUnitPlatformProvider provider = new JUnitPlatformProvider(providerParameters); - assertThat( provider.getFilters() ).hasSize( 1 ); - assertThat( provider.getFilters()[0] ).isInstanceOf( EngineFilter.class ); + assertThat(provider.getFilters()).hasSize(1); + assertThat(provider.getFilters()[0]).isInstanceOf(EngineFilter.class); } @Test - public void bothIncludeAndExcludeJunit5EnginesAreAllowed() - { + public void bothIncludeAndExcludeJunit5EnginesAreAllowed() { Map properties = new HashMap<>(); - properties.put( INCLUDE_JUNIT5_ENGINES_PROP, "engine-one, engine-two" ); - properties.put( EXCLUDE_JUNIT5_ENGINES_PROP, "engine-three, engine-four" ); + properties.put(INCLUDE_JUNIT5_ENGINES_PROP, "engine-one, engine-two"); + properties.put(EXCLUDE_JUNIT5_ENGINES_PROP, "engine-three, engine-four"); - ProviderParameters providerParameters = providerParametersMock( TestClass1.class ); - when( providerParameters.getProviderProperties() ).thenReturn( properties ); + ProviderParameters providerParameters = providerParametersMock(TestClass1.class); + when(providerParameters.getProviderProperties()).thenReturn(properties); - JUnitPlatformProvider provider = new JUnitPlatformProvider( providerParameters ); + JUnitPlatformProvider provider = new JUnitPlatformProvider(providerParameters); - assertThat( provider.getFilters() ).hasSize( 2 ); - assertThat( provider.getFilters()[0] ).isInstanceOf( EngineFilter.class ); - assertThat( provider.getFilters()[1] ).isInstanceOf( EngineFilter.class ); + assertThat(provider.getFilters()).hasSize(2); + assertThat(provider.getFilters()[0]).isInstanceOf(EngineFilter.class); + assertThat(provider.getFilters()[1]).isInstanceOf(EngineFilter.class); } @Test - public void noFiltersAreCreatedIfNoPropertiesAreDeclared() - { - ProviderParameters providerParameters = providerParametersMock( TestClass1.class ); + public void noFiltersAreCreatedIfNoPropertiesAreDeclared() { + ProviderParameters providerParameters = providerParametersMock(TestClass1.class); - JUnitPlatformProvider provider = new JUnitPlatformProvider( providerParameters ); + JUnitPlatformProvider provider = new JUnitPlatformProvider(providerParameters); - assertEquals( 0, provider.getFilters().length ); + assertEquals(0, provider.getFilters().length); } @Test - public void defaultConfigurationParametersAreEmpty() - { - ProviderParameters providerParameters = providerParametersMock( TestClass1.class ); - when( providerParameters.getProviderProperties() ).thenReturn( emptyMap() ); + public void defaultConfigurationParametersAreEmpty() { + ProviderParameters providerParameters = providerParametersMock(TestClass1.class); + when(providerParameters.getProviderProperties()).thenReturn(emptyMap()); - JUnitPlatformProvider provider = new JUnitPlatformProvider( providerParameters ); + JUnitPlatformProvider provider = new JUnitPlatformProvider(providerParameters); - assertTrue( provider.getConfigurationParameters().isEmpty() ); + assertTrue(provider.getConfigurationParameters().isEmpty()); } @Test - public void parsesConfigurationParameters() - { - ProviderParameters providerParameters = providerParametersMock( TestClass1.class ); - when( providerParameters.getProviderProperties() ) - .thenReturn( singletonMap( JUnitPlatformProvider.CONFIGURATION_PARAMETERS, - "foo = true\nbar 42\rbaz: *\r\nqux: EOF" ) ); + public void parsesConfigurationParameters() { + ProviderParameters providerParameters = providerParametersMock(TestClass1.class); + when(providerParameters.getProviderProperties()) + .thenReturn(singletonMap( + JUnitPlatformProvider.CONFIGURATION_PARAMETERS, "foo = true\nbar 42\rbaz: *\r\nqux: EOF")); - JUnitPlatformProvider provider = new JUnitPlatformProvider( providerParameters ); + JUnitPlatformProvider provider = new JUnitPlatformProvider(providerParameters); - assertEquals( 4, provider.getConfigurationParameters().size() ); - assertEquals( "true", provider.getConfigurationParameters().get( "foo" ) ); - assertEquals( "42", provider.getConfigurationParameters().get( "bar" ) ); - assertEquals( "*", provider.getConfigurationParameters().get( "baz" ) ); - assertEquals( "EOF", provider.getConfigurationParameters().get( "qux" ) ); + assertEquals(4, provider.getConfigurationParameters().size()); + assertEquals("true", provider.getConfigurationParameters().get("foo")); + assertEquals("42", provider.getConfigurationParameters().get("bar")); + assertEquals("*", provider.getConfigurationParameters().get("baz")); + assertEquals("EOF", provider.getConfigurationParameters().get("qux")); } @Test - public void shouldFilterTestMethod() - { + public void shouldFilterTestMethod() { ProviderParameters providerParameters = providerParametersMock(); - TestListResolver testListResolver = new TestListResolver( "**/*Test#test*" ); - assertFalse( testListResolver.isEmpty() ); - assertFalse( testListResolver.isWildcard() ); - TestRequest request = new TestRequest( null, null, testListResolver, 0 ); - when( providerParameters.getTestRequest() ).thenReturn( request ); + TestListResolver testListResolver = new TestListResolver("**/*Test#test*"); + assertFalse(testListResolver.isEmpty()); + assertFalse(testListResolver.isWildcard()); + TestRequest request = new TestRequest(null, null, testListResolver, 0); + when(providerParameters.getTestRequest()).thenReturn(request); - JUnitPlatformProvider provider = new JUnitPlatformProvider( providerParameters ); + JUnitPlatformProvider provider = new JUnitPlatformProvider(providerParameters); - assertThat( provider.getFilters() ) - .hasSize( 1 ); + assertThat(provider.getFilters()).hasSize(1); - assertThat( provider.getFilters()[0] ) - .isInstanceOf( TestMethodFilter.class ); + assertThat(provider.getFilters()[0]).isInstanceOf(TestMethodFilter.class); - Object expectedTestListResolver = getInternalState( provider.getFilters()[0], "testListResolver" ); + Object expectedTestListResolver = getInternalState(provider.getFilters()[0], "testListResolver"); - assertThat( expectedTestListResolver ) - .isInstanceOf( TestListResolver.class ); + assertThat(expectedTestListResolver).isInstanceOf(TestListResolver.class); - assertThat( expectedTestListResolver ) - .isSameAs( testListResolver ); + assertThat(expectedTestListResolver).isSameAs(testListResolver); } @Test - public void shouldNotFilterEmpty() - { + public void shouldNotFilterEmpty() { ProviderParameters providerParameters = providerParametersMock(); - TestListResolver testListResolver = new TestListResolver( "" ); - assertTrue( testListResolver.isEmpty() ); - assertFalse( testListResolver.isWildcard() ); - TestRequest request = new TestRequest( null, null, testListResolver, 0 ); - when( providerParameters.getTestRequest() ).thenReturn( request ); + TestListResolver testListResolver = new TestListResolver(""); + assertTrue(testListResolver.isEmpty()); + assertFalse(testListResolver.isWildcard()); + TestRequest request = new TestRequest(null, null, testListResolver, 0); + when(providerParameters.getTestRequest()).thenReturn(request); - JUnitPlatformProvider provider = new JUnitPlatformProvider( providerParameters ); + JUnitPlatformProvider provider = new JUnitPlatformProvider(providerParameters); - assertThat( provider.getFilters() ) - .isEmpty(); + assertThat(provider.getFilters()).isEmpty(); } @Test - public void shouldNotFilterWildcard() - { + public void shouldNotFilterWildcard() { ProviderParameters providerParameters = providerParametersMock(); - TestListResolver testListResolver = new TestListResolver( "*.java" ); - assertTrue( testListResolver.isWildcard() ); - assertFalse( testListResolver.isEmpty() ); - TestRequest request = new TestRequest( null, null, testListResolver, 0 ); - when( providerParameters.getTestRequest() ).thenReturn( request ); + TestListResolver testListResolver = new TestListResolver("*.java"); + assertTrue(testListResolver.isWildcard()); + assertFalse(testListResolver.isEmpty()); + TestRequest request = new TestRequest(null, null, testListResolver, 0); + when(providerParameters.getTestRequest()).thenReturn(request); - JUnitPlatformProvider provider = new JUnitPlatformProvider( providerParameters ); + JUnitPlatformProvider provider = new JUnitPlatformProvider(providerParameters); - assertThat( provider.getFilters() ) - .isEmpty(); + assertThat(provider.getFilters()).isEmpty(); } @Test - public void executesSingleTestIncludedByName() - throws Exception - { + public void executesSingleTestIncludedByName() throws Exception { // following is equivalent of adding '-Dtest=TestClass3#prefix1Suffix1' // '*' needed because it's a nested class and thus has name prefixed with '$' String pattern = "*TestClass3#prefix1Suffix1"; - testExecutionOfMatchingTestMethods( TestClass3.class, pattern, "prefix1Suffix1()" ); + testExecutionOfMatchingTestMethods(TestClass3.class, pattern, "prefix1Suffix1()"); } @Test - public void executesMultipleTestsIncludedByName() - throws Exception - { + public void executesMultipleTestsIncludedByName() throws Exception { // following is equivalent of adding '-Dtest=TestClass3#prefix1Suffix1+prefix2Suffix1' // '*' needed because it's a nested class and thus has name prefixed with '$' String pattern = "*TestClass3#prefix1Suffix1+prefix2Suffix1"; - testExecutionOfMatchingTestMethods( - TestClass3.class, pattern, "prefix1Suffix1()", "prefix2Suffix1()" ); + testExecutionOfMatchingTestMethods(TestClass3.class, pattern, "prefix1Suffix1()", "prefix2Suffix1()"); } @Test - public void executesMultipleTestsIncludedByNamePattern() - throws Exception - { + public void executesMultipleTestsIncludedByNamePattern() throws Exception { // following is equivalent of adding '-Dtest=TestClass3#prefix1*' // '*' needed because it's a nested class and thus has name prefixed with '$' String pattern = "*TestClass3#prefix1*"; - testExecutionOfMatchingTestMethods( - TestClass3.class, pattern, "prefix1Suffix1()", "prefix1Suffix2()" ); + testExecutionOfMatchingTestMethods(TestClass3.class, pattern, "prefix1Suffix1()", "prefix1Suffix2()"); } @Test - public void executesMultipleTestsIncludedByNamePatternWithQuestionMark() - throws Exception - { + public void executesMultipleTestsIncludedByNamePatternWithQuestionMark() throws Exception { // following is equivalent of adding '-Dtest=TestClass3#prefix?Suffix2' // '*' needed because it's a nested class and thus has name prefixed with '$' String pattern = "*TestClass3#prefix?Suffix2"; - testExecutionOfMatchingTestMethods( - TestClass3.class, pattern, "prefix1Suffix2()", "prefix2Suffix2()" ); + testExecutionOfMatchingTestMethods(TestClass3.class, pattern, "prefix1Suffix2()", "prefix2Suffix2()"); } @Test - public void doesNotExecuteTestsExcludedByName() - throws Exception - { + public void doesNotExecuteTestsExcludedByName() throws Exception { // following is equivalent of adding '-Dtest=!TestClass3#prefix1Suffix2' // '*' needed because it's a nested class and thus has name prefixed with '$' String pattern = "!*TestClass3#prefix1Suffix2"; testExecutionOfMatchingTestMethods( - TestClass3.class, pattern, "prefix1Suffix1()", "prefix2Suffix1()", "prefix2Suffix2()" ); + TestClass3.class, pattern, "prefix1Suffix1()", "prefix2Suffix1()", "prefix2Suffix2()"); } @Test - public void doesNotExecuteTestsExcludedByNamePattern() - throws Exception - { + public void doesNotExecuteTestsExcludedByNamePattern() throws Exception { // following is equivalent of adding '-Dtest=!TestClass3#prefix2*' // '*' needed because it's a nested class and thus has name prefixed with '$' String pattern = "!*TestClass3#prefix2*"; - testExecutionOfMatchingTestMethods( - TestClass3.class, pattern, "prefix1Suffix1()", "prefix1Suffix2()" ); + testExecutionOfMatchingTestMethods(TestClass3.class, pattern, "prefix1Suffix1()", "prefix1Suffix2()"); } - private static void testExecutionOfMatchingTestMethods( Class testClass, String pattern, - String... expectedTestNames ) - throws Exception - { - TestListResolver testListResolver = new TestListResolver( pattern ); - ProviderParameters providerParameters = providerParametersMock( testListResolver, testClass ); + private static void testExecutionOfMatchingTestMethods( + Class testClass, String pattern, String... expectedTestNames) throws Exception { + TestListResolver testListResolver = new TestListResolver(pattern); + ProviderParameters providerParameters = providerParametersMock(testListResolver, testClass); Launcher launcher = LauncherFactory.create(); - JUnitPlatformProvider provider = new JUnitPlatformProvider( providerParameters, launcher ); + JUnitPlatformProvider provider = new JUnitPlatformProvider(providerParameters, launcher); TestPlanSummaryListener executionListener = new TestPlanSummaryListener(); - launcher.registerTestExecutionListeners( executionListener ); + launcher.registerTestExecutionListeners(executionListener); - invokeProvider( provider, null ); + invokeProvider(provider, null); - assertEquals( 1, executionListener.summaries.size() ); - TestExecutionSummary summary = executionListener.summaries.get( 0 ); + assertEquals(1, executionListener.summaries.size()); + TestExecutionSummary summary = executionListener.summaries.get(0); int expectedCount = expectedTestNames.length; - assertEquals( expectedCount, summary.getTestsFoundCount() ); - assertEquals( expectedCount, summary.getTestsFailedCount() ); - assertEquals( expectedCount, summary.getFailures().size() ); + assertEquals(expectedCount, summary.getTestsFoundCount()); + assertEquals(expectedCount, summary.getTestsFailedCount()); + assertEquals(expectedCount, summary.getFailures().size()); - assertThat( failedTestDisplayNames( summary ) ).contains( expectedTestNames ); + assertThat(failedTestDisplayNames(summary)).contains(expectedTestNames); } - private static ProviderParameters providerParametersMock( Class... testClasses ) - { - return providerParametersMock( runListenerMock(), testClasses ); + private static ProviderParameters providerParametersMock(Class... testClasses) { + return providerParametersMock(runListenerMock(), testClasses); } private static ProviderParameters providerParametersMock( - TestReportListener runListener, Class... testClasses ) - { - TestListResolver testListResolver = new TestListResolver( "" ); - return providerParametersMock( runListener, testListResolver, testClasses ); + TestReportListener runListener, Class... testClasses) { + TestListResolver testListResolver = new TestListResolver(""); + return providerParametersMock(runListener, testListResolver, testClasses); } private static ProviderParameters providerParametersMock( - TestListResolver testListResolver, Class... testClasses ) - { - return providerParametersMock( runListenerMock(), testListResolver, testClasses ); + TestListResolver testListResolver, Class... testClasses) { + return providerParametersMock(runListenerMock(), testListResolver, testClasses); } - private static ProviderParameters providerParametersMock( TestReportListener runListener, - TestListResolver testListResolver, - Class... testClasses ) - { - TestsToRun testsToRun = newTestsToRun( testClasses ); + private static ProviderParameters providerParametersMock( + TestReportListener runListener, + TestListResolver testListResolver, + Class... testClasses) { + TestsToRun testsToRun = newTestsToRun(testClasses); - ScanResult scanResult = mock( ScanResult.class ); - when( scanResult.applyFilter( any(), any() ) ).thenReturn( testsToRun ); + ScanResult scanResult = mock(ScanResult.class); + when(scanResult.applyFilter(any(), any())).thenReturn(testsToRun); - RunOrderCalculator runOrderCalculator = mock( RunOrderCalculator.class ); - when( runOrderCalculator.orderTestClasses( any() ) ).thenReturn( testsToRun ); + RunOrderCalculator runOrderCalculator = mock(RunOrderCalculator.class); + when(runOrderCalculator.orderTestClasses(any())).thenReturn(testsToRun); - ReporterFactory reporterFactory = mock( ReporterFactory.class ); - when( reporterFactory.createTestReportListener() ).thenReturn( runListener ); + ReporterFactory reporterFactory = mock(ReporterFactory.class); + when(reporterFactory.createTestReportListener()).thenReturn(runListener); - TestRequest testRequest = mock( TestRequest.class ); - when( testRequest.getTestListResolver() ).thenReturn( testListResolver ); + TestRequest testRequest = mock(TestRequest.class); + when(testRequest.getTestListResolver()).thenReturn(testListResolver); - ProviderParameters providerParameters = mock( ProviderParameters.class ); - when( providerParameters.getScanResult() ).thenReturn( scanResult ); - when( providerParameters.getRunOrderCalculator() ).thenReturn( runOrderCalculator ); - when( providerParameters.getReporterFactory() ).thenReturn( reporterFactory ); - when( providerParameters.getTestRequest() ).thenReturn( testRequest ); + ProviderParameters providerParameters = mock(ProviderParameters.class); + when(providerParameters.getScanResult()).thenReturn(scanResult); + when(providerParameters.getRunOrderCalculator()).thenReturn(runOrderCalculator); + when(providerParameters.getReporterFactory()).thenReturn(reporterFactory); + when(providerParameters.getTestRequest()).thenReturn(testRequest); return providerParameters; } - private static TestReportListener runListenerMock() - { - return mock( TestReportListener.class, withSettings().extraInterfaces( TestOutputReceiver.class ) ); + private static TestReportListener runListenerMock() { + return mock(TestReportListener.class, withSettings().extraInterfaces(TestOutputReceiver.class)); } - private static Set failedTestDisplayNames( TestExecutionSummary summary ) - { + private static Set failedTestDisplayNames(TestExecutionSummary summary) { // @formatter:off - return summary.getFailures() - .stream() - .map( Failure::getTestIdentifier ) - .map( TestIdentifier::getDisplayName ) - .collect( toSet() ); + return summary.getFailures().stream() + .map(Failure::getTestIdentifier) + .map(TestIdentifier::getDisplayName) + .collect(toSet()); // @formatter:on } - private static TestsToRun newTestsToRun( Class... testClasses ) - { - List> classesList = Arrays.asList( testClasses ); - return new TestsToRun( new LinkedHashSet<>( classesList ) ); + private static TestsToRun newTestsToRun(Class... testClasses) { + List> classesList = Arrays.asList(testClasses); + return new TestsToRun(new LinkedHashSet<>(classesList)); } - private static TestsToRun newTestsToRunLazily( Class... testClasses ) - { - class LazyTestsToRunFake extends TestsToRun - { - LazyTestsToRunFake( Set> locatedClasses ) - { - super( locatedClasses ); + private static TestsToRun newTestsToRunLazily(Class... testClasses) { + class LazyTestsToRunFake extends TestsToRun { + LazyTestsToRunFake(Set> locatedClasses) { + super(locatedClasses); } @Override - public boolean allowEagerReading() - { + public boolean allowEagerReading() { return false; } } - List> classesList = Arrays.asList( testClasses ); - return new LazyTestsToRunFake( new LinkedHashSet<>( classesList ) ); + List> classesList = Arrays.asList(testClasses); + return new LazyTestsToRunFake(new LinkedHashSet<>(classesList)); } - private static class TestPlanSummaryListener - extends SummaryGeneratingListener - { + private static class TestPlanSummaryListener extends SummaryGeneratingListener { private final List summaries = new ArrayList<>(); @Override - public void testPlanExecutionFinished( TestPlan testPlan ) - { - super.testPlanExecutionFinished( testPlan ); - summaries.add( getSummary() ); + public void testPlanExecutionFinished(TestPlan testPlan) { + super.testPlanExecutionFinished(testPlan); + summaries.add(getSummary()); } } @@ -1229,24 +1135,19 @@ public void testPlanExecutionFinished( TestPlan testPlan ) * * @see #986 */ - private static void invokeProvider( JUnitPlatformProvider provider, Object forkTestSet ) - throws TestSetFailedException - { + private static void invokeProvider(JUnitPlatformProvider provider, Object forkTestSet) + throws TestSetFailedException { PrintStream systemOut = System.out; PrintStream systemErr = System.err; - try - { - provider.invoke( forkTestSet ); - } - finally - { - System.setOut( systemOut ); - System.setErr( systemErr ); + try { + provider.invoke(forkTestSet); + } finally { + System.setOut(systemOut); + System.setErr(systemErr); } } - static class TestClass1 - { + static class TestClass1 { static final int TESTS_FOUND = 4; @@ -1261,30 +1162,22 @@ static class TestClass1 static final int TESTS_FAILED = 1; @org.junit.jupiter.api.Test - void test1() - { - } + void test1() {} @org.junit.jupiter.api.Test - void test2() - { - } + void test2() {} @Disabled @org.junit.jupiter.api.Test - void test3() - { - } + void test3() {} @org.junit.jupiter.api.Test - void test4() - { + void test4() { throw new RuntimeException(); } } - static class TestClass2 - { + static class TestClass2 { static final int TESTS_FOUND = 3; @@ -1299,272 +1192,203 @@ static class TestClass2 static final int TESTS_FAILED = 1; @org.junit.jupiter.api.Test - void test1() - { - } + void test1() {} @org.junit.jupiter.api.Test - void test2() - { + void test2() { throw new RuntimeException(); } @org.junit.jupiter.api.Test - void test3() - { - assumeTrue( false ); + void test3() { + assumeTrue(false); } } - static class VerboseTestClass - { + static class VerboseTestClass { @org.junit.jupiter.api.Test - void test() - { - System.out.println( "stdout" ); - System.err.println( "stderr" ); + void test() { + System.out.println("stdout"); + System.err.println("stderr"); } } @Test - public void usesClassNamesForXmlReport() - throws TestSetFailedException - { - String[] classNames = { Sub1Tests.class.getName(), Sub2Tests.class.getName() }; - ProviderParameters providerParameters = - providerParametersMock( Sub1Tests.class, Sub2Tests.class ); + public void usesClassNamesForXmlReport() throws TestSetFailedException { + String[] classNames = {Sub1Tests.class.getName(), Sub2Tests.class.getName()}; + ProviderParameters providerParameters = providerParametersMock(Sub1Tests.class, Sub2Tests.class); - JUnitPlatformProvider jUnitPlatformProvider = new JUnitPlatformProvider( providerParameters ); - TestsToRun testsToRun = newTestsToRun( Sub1Tests.class, Sub2Tests.class ); + JUnitPlatformProvider jUnitPlatformProvider = new JUnitPlatformProvider(providerParameters); + TestsToRun testsToRun = newTestsToRun(Sub1Tests.class, Sub2Tests.class); - invokeProvider( jUnitPlatformProvider, testsToRun ); + invokeProvider(jUnitPlatformProvider, testsToRun); RunListener reporter = providerParameters.getReporterFactory().createTestReportListener(); - ArgumentCaptor reportEntryArgumentCaptor = - ArgumentCaptor.forClass( ReportEntry.class ); - verify( reporter, times( 2 ) ).testSucceeded( reportEntryArgumentCaptor.capture() ); + ArgumentCaptor reportEntryArgumentCaptor = ArgumentCaptor.forClass(ReportEntry.class); + verify(reporter, times(2)).testSucceeded(reportEntryArgumentCaptor.capture()); List allValues = reportEntryArgumentCaptor.getAllValues(); - assertThat( allValues ).extracting( ReportEntry::getSourceName ).containsExactly( classNames ); + assertThat(allValues).extracting(ReportEntry::getSourceName).containsExactly(classNames); } - static class AbstractTestClass - { + static class AbstractTestClass { @org.junit.jupiter.api.Test - void test() - { - } + void test() {} } - static class Sub1Tests - extends AbstractTestClass - { - } + static class Sub1Tests extends AbstractTestClass {} - static class Sub2Tests - extends AbstractTestClass - { - } + static class Sub2Tests extends AbstractTestClass {} - static class TestClass3 - { + static class TestClass3 { @org.junit.jupiter.api.Test - void prefix1Suffix1() - { + void prefix1Suffix1() { throw new RuntimeException(); } @org.junit.jupiter.api.Test - void prefix2Suffix1() - { + void prefix2Suffix1() { throw new RuntimeException(); } @org.junit.jupiter.api.Test - void prefix1Suffix2() - { + void prefix1Suffix2() { throw new RuntimeException(); } @org.junit.jupiter.api.Test - void prefix2Suffix2() - { + void prefix2Suffix2() { throw new RuntimeException(); } } - static class TestClass4 - { + static class TestClass4 { static int count; - @org.junit.jupiter.api.DisplayName( "Always passes" ) + @org.junit.jupiter.api.DisplayName("Always passes") @org.junit.jupiter.api.Test - void testPass() - { - } + void testPass() {} @org.junit.jupiter.api.Test - void testAborted() - { - assumeFalse( true ); - throw new IllegalStateException( "this exception should never happen" ); + void testAborted() { + assumeFalse(true); + throw new IllegalStateException("this exception should never happen"); } @org.junit.jupiter.api.Test - void testAlwaysError() - { - throw new Error( "some error" ); + void testAlwaysError() { + throw new Error("some error"); } @org.junit.jupiter.api.Test - void testAlwaysFail() - { - assertTrue( false ); + void testAlwaysFail() { + assertTrue(false); } @org.junit.jupiter.api.Test @org.junit.jupiter.api.Disabled - void testAlwaysSkipped() - { - throw new IllegalStateException( "this test should be never called" ); + void testAlwaysSkipped() { + throw new IllegalStateException("this test should be never called"); } - @org.junit.jupiter.api.DisplayName( "Fails twice" ) + @org.junit.jupiter.api.DisplayName("Fails twice") @org.junit.jupiter.api.Test - void testFailTwice() - { + void testFailTwice() { count += 1; - assertTrue( count >= 3 ); + assertTrue(count >= 3); } } - static class TestClass5 - { + static class TestClass5 { static int count; @org.junit.jupiter.api.Test - void testFailTwice1() - { + void testFailTwice1() { count += 1; - assertTrue( count >= 3 ); + assertTrue(count >= 3); } } - static class TestClass7 - { - static List params() - { - return Arrays.asList( new Object[] { "Always pass", true }, - new Object[] { "Always fail", false } ); + static class TestClass7 { + static List params() { + return Arrays.asList(new Object[] {"Always pass", true}, new Object[] {"Always fail", false}); } @org.junit.jupiter.params.ParameterizedTest - @org.junit.jupiter.params.provider.MethodSource( "params" ) - void testParameterizedTestCases( String testName, boolean value ) - { - assertTrue( value ); + @org.junit.jupiter.params.provider.MethodSource("params") + void testParameterizedTestCases(String testName, boolean value) { + assertTrue(value); } } - static class TestClass8 - { - static List params() - { + static class TestClass8 { + static List params() { throw new RuntimeException(); } @org.junit.jupiter.params.ParameterizedTest - @org.junit.jupiter.params.provider.MethodSource( "params" ) - void testParameterizedTestCases() - { - } + @org.junit.jupiter.params.provider.MethodSource("params") + void testParameterizedTestCases() {} } - static class TestClass9 - { - static List params() - { - assertTrue( false ); + static class TestClass9 { + static List params() { + assertTrue(false); return new ArrayList<>(); } @org.junit.jupiter.params.ParameterizedTest - @org.junit.jupiter.params.provider.MethodSource( "params" ) - void testParameterizedTestCases() - { - } + @org.junit.jupiter.params.provider.MethodSource("params") + void testParameterizedTestCases() {} } - @DisplayName( "<< ✨ >>" ) - static class DisplayNameTest - { + @DisplayName("<< ✨ >>") + static class DisplayNameTest { @org.junit.jupiter.api.Test - @DisplayName( "73$71 ✔" ) - void test1() - { - } + @DisplayName("73$71 ✔") + void test1() {} } - static class NestingTest - { + static class NestingTest { @Nested - class Level1NestedTest - { + class Level1NestedTest { @org.junit.jupiter.api.Test - void level1test() - { - } + void level1test() {} @Nested - class Level2NestedTest - { + class Level2NestedTest { @org.junit.jupiter.api.Test - void level2test() - { - } + void level2test() {} } } } - static class DisabledParameterizedTest - { + static class DisabledParameterizedTest { @org.junit.jupiter.params.ParameterizedTest - @org.junit.jupiter.params.provider.ValueSource( strings = { "1", "2" } ) + @org.junit.jupiter.params.provider.ValueSource(strings = {"1", "2"}) @Disabled - void disabledParameterized( String param ) - { - } + void disabledParameterized(String param) {} } - static class FailingBeforeAllJupiterTest - { + static class FailingBeforeAllJupiterTest { @BeforeAll - static void oneTimeSetUp() - { - fail( "oneTimeSetUp() failed" ); + static void oneTimeSetUp() { + fail("oneTimeSetUp() failed"); } @org.junit.jupiter.api.Test - void test() - { - } - + void test() {} } - static class FailingWithErrorBeforeAllJupiterTest - { + static class FailingWithErrorBeforeAllJupiterTest { @BeforeAll - static void oneTimeSetUp() - { - throw new RuntimeException( "oneTimeSetUp() threw an exception" ); + static void oneTimeSetUp() { + throw new RuntimeException("oneTimeSetUp() threw an exception"); } @org.junit.jupiter.api.Test - void test() - { - } - + void test() {} } } diff --git a/surefire-providers/surefire-junit-platform/src/test/java/org/apache/maven/surefire/junitplatform/RunListenerAdapterTest.java b/surefire-providers/surefire-junit-platform/src/test/java/org/apache/maven/surefire/junitplatform/RunListenerAdapterTest.java index e790bde1e8..8d0d7425fd 100644 --- a/surefire-providers/surefire-junit-platform/src/test/java/org/apache/maven/surefire/junitplatform/RunListenerAdapterTest.java +++ b/surefire-providers/surefire-junit-platform/src/test/java/org/apache/maven/surefire/junitplatform/RunListenerAdapterTest.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.junitplatform; /* @@ -19,40 +37,17 @@ * under the License. */ -import static java.util.Collections.emptyList; -import static java.util.Collections.singleton; -import static java.util.Collections.singletonList; -import static org.apache.maven.surefire.api.report.RunMode.NORMAL_RUN; -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.platform.engine.TestDescriptor.Type.CONTAINER; -import static org.junit.platform.engine.TestDescriptor.Type.TEST; -import static org.junit.platform.engine.TestExecutionResult.aborted; -import static org.junit.platform.engine.TestExecutionResult.failed; -import static org.junit.platform.engine.TestExecutionResult.successful; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.inOrder; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyZeroInteractions; -import static org.mockito.Mockito.verifyNoMoreInteractions; -import static org.mockito.Mockito.when; -import static org.powermock.reflect.Whitebox.getInternalState; - import java.lang.reflect.Method; import java.util.Map; import java.util.Optional; +import org.apache.maven.surefire.api.report.ReportEntry; +import org.apache.maven.surefire.api.report.SimpleReportEntry; +import org.apache.maven.surefire.api.report.StackTraceWriter; import org.apache.maven.surefire.api.report.TestOutputReportEntry; import org.apache.maven.surefire.api.report.TestReportListener; import org.apache.maven.surefire.api.report.TestSetReportEntry; import org.apache.maven.surefire.report.PojoStackTraceWriter; -import org.apache.maven.surefire.api.report.ReportEntry; -import org.apache.maven.surefire.api.report.SimpleReportEntry; -import org.apache.maven.surefire.api.report.StackTraceWriter; import org.junit.Before; import org.junit.Test; import org.junit.jupiter.api.DisplayName; @@ -73,754 +68,656 @@ import org.mockito.InOrder; import org.opentest4j.TestSkippedException; +import static java.util.Collections.emptyList; +import static java.util.Collections.singleton; +import static java.util.Collections.singletonList; +import static org.apache.maven.surefire.api.report.RunMode.NORMAL_RUN; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.platform.engine.TestDescriptor.Type.CONTAINER; +import static org.junit.platform.engine.TestDescriptor.Type.TEST; +import static org.junit.platform.engine.TestExecutionResult.aborted; +import static org.junit.platform.engine.TestExecutionResult.failed; +import static org.junit.platform.engine.TestExecutionResult.successful; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.verifyZeroInteractions; +import static org.mockito.Mockito.when; +import static org.powermock.reflect.Whitebox.getInternalState; + /** * Unit tests for {@link RunListenerAdapter}. * * @since 2.22.0 */ -@SuppressWarnings( "checkstyle:magicnumber" ) -public class RunListenerAdapterTest -{ - private static final ConfigurationParameters CONFIG_PARAMS = mock( ConfigurationParameters.class ); +@SuppressWarnings("checkstyle:magicnumber") +public class RunListenerAdapterTest { + private static final ConfigurationParameters CONFIG_PARAMS = mock(ConfigurationParameters.class); private TestReportListener listener; private RunListenerAdapter adapter; @Before - public void setUp() - { - listener = mock( TestReportListener.class ); - adapter = new RunListenerAdapter( listener ); - adapter.testPlanExecutionStarted( TestPlan.from( emptyList() ) ); - adapter.setRunMode( NORMAL_RUN ); + public void setUp() { + listener = mock(TestReportListener.class); + adapter = new RunListenerAdapter(listener); + adapter.testPlanExecutionStarted(TestPlan.from(emptyList())); + adapter.setRunMode(NORMAL_RUN); } @Test - public void notifiedWithCorrectNamesWhenMethodExecutionStarted() - throws Exception - { - ArgumentCaptor entryCaptor = ArgumentCaptor.forClass( ReportEntry.class ); + public void notifiedWithCorrectNamesWhenMethodExecutionStarted() throws Exception { + ArgumentCaptor entryCaptor = ArgumentCaptor.forClass(ReportEntry.class); - TestPlan testPlan = TestPlan.from( singletonList( new EngineDescriptor( newId(), "Luke's Plan" ) ) ); - adapter.testPlanExecutionStarted( testPlan ); + TestPlan testPlan = TestPlan.from(singletonList(new EngineDescriptor(newId(), "Luke's Plan"))); + adapter.testPlanExecutionStarted(testPlan); TestIdentifier methodIdentifier = - identifiersAsParentOnTestPlan( testPlan, newClassDescriptor(), newMethodDescriptor() ); + identifiersAsParentOnTestPlan(testPlan, newClassDescriptor(), newMethodDescriptor()); - adapter.executionStarted( methodIdentifier ); - verify( listener ).testStarting( entryCaptor.capture() ); + adapter.executionStarted(methodIdentifier); + verify(listener).testStarting(entryCaptor.capture()); ReportEntry entry = entryCaptor.getValue(); - assertEquals( MY_TEST_METHOD_NAME, entry.getName() ); - assertEquals( MyTestClass.class.getName(), entry.getSourceName() ); - assertNull( entry.getStackTraceWriter() ); + assertEquals(MY_TEST_METHOD_NAME, entry.getName()); + assertEquals(MyTestClass.class.getName(), entry.getSourceName()); + assertNull(entry.getStackTraceWriter()); } @Test - public void notifiedWithCompatibleNameForMethodWithArguments() - throws Exception - { - ArgumentCaptor entryCaptor = ArgumentCaptor.forClass( ReportEntry.class ); + public void notifiedWithCompatibleNameForMethodWithArguments() throws Exception { + ArgumentCaptor entryCaptor = ArgumentCaptor.forClass(ReportEntry.class); - TestPlan testPlan = TestPlan.from( singletonList( new EngineDescriptor( newId(), "Luke's Plan" ) ) ); - adapter.testPlanExecutionStarted( testPlan ); + TestPlan testPlan = TestPlan.from(singletonList(new EngineDescriptor(newId(), "Luke's Plan"))); + adapter.testPlanExecutionStarted(testPlan); - TestIdentifier methodIdentifier = identifiersAsParentOnTestPlan( testPlan, newClassDescriptor(), - newMethodDescriptor( String.class ) ); + TestIdentifier methodIdentifier = + identifiersAsParentOnTestPlan(testPlan, newClassDescriptor(), newMethodDescriptor(String.class)); - adapter.executionStarted( methodIdentifier ); - verify( listener ).testStarting( entryCaptor.capture() ); + adapter.executionStarted(methodIdentifier); + verify(listener).testStarting(entryCaptor.capture()); ReportEntry entry = entryCaptor.getValue(); - assertEquals( MY_TEST_METHOD_NAME + "(String)", entry.getName() ); - assertNull( entry.getNameText() ); - assertEquals( MyTestClass.class.getName(), entry.getSourceName() ); - assertNull( entry.getSourceText() ); - assertNull( entry.getStackTraceWriter() ); + assertEquals(MY_TEST_METHOD_NAME + "(String)", entry.getName()); + assertNull(entry.getNameText()); + assertEquals(MyTestClass.class.getName(), entry.getSourceName()); + assertNull(entry.getSourceText()); + assertNull(entry.getStackTraceWriter()); } @Test - public void notifiedEagerlyForTestSetWhenClassExecutionStarted() - throws Exception - { + public void notifiedEagerlyForTestSetWhenClassExecutionStarted() throws Exception { EngineDescriptor engine = newEngineDescriptor(); TestDescriptor parent = newClassDescriptor(); - engine.addChild( parent ); + engine.addChild(parent); TestDescriptor child = newMethodDescriptor(); - parent.addChild( child ); - TestPlan plan = TestPlan.from( singletonList( engine ) ); + parent.addChild(child); + TestPlan plan = TestPlan.from(singletonList(engine)); String className = MyTestClass.class.getName(); - adapter.testPlanExecutionStarted( plan ); - adapter.executionStarted( TestIdentifier.from( engine ) ); - adapter.executionStarted( TestIdentifier.from( parent ) ); - verify( listener ).testSetStarting( new SimpleReportEntry( NORMAL_RUN, 0x0000000100000000L, className, - null, null, null ) ); - verifyNoMoreInteractions( listener ); - - adapter.executionStarted( TestIdentifier.from( child ) ); - verify( listener ).testStarting( new SimpleReportEntry( NORMAL_RUN, 0x0000000100000001L, className, null, - MY_TEST_METHOD_NAME, null ) ); - verifyNoMoreInteractions( listener ); - - adapter.executionFinished( TestIdentifier.from( child ), successful() ); - ArgumentCaptor report = ArgumentCaptor.forClass( SimpleReportEntry.class ); - verify( listener ).testSucceeded( report.capture() ); - assertThat( report.getValue().getRunMode() ) - .isEqualTo( NORMAL_RUN ); - assertThat( report.getValue().getTestRunId() ) - .isEqualTo( 0x0000000100000001L ); - assertThat( report.getValue().getSourceName() ) - .isEqualTo( className ); - assertThat( report.getValue().getSourceText() ) - .isNull(); - assertThat( report.getValue().getName() ) - .isEqualTo( MY_TEST_METHOD_NAME ); - assertThat( report.getValue().getNameText() ) - .isNull(); - assertThat( report.getValue().getElapsed() ) - .isNotNull(); - assertThat( report.getValue().getSystemProperties() ) - .isEmpty(); - verifyNoMoreInteractions( listener ); - - adapter.executionFinished( TestIdentifier.from( parent ), successful() ); - report = ArgumentCaptor.forClass( SimpleReportEntry.class ); - verify( listener ).testSetCompleted( report.capture() ); - assertThat( report.getValue().getSourceName() ) - .isEqualTo( className ); - assertThat( report.getValue().getName() ) - .isNull(); - assertThat( report.getValue().getElapsed() ) - .isNotNull(); - assertThat( report.getValue().getSystemProperties() ) - .isNotEmpty(); - verifyNoMoreInteractions( listener ); - - adapter.executionFinished( TestIdentifier.from( engine ), successful() ); - verifyNoMoreInteractions( listener ); + adapter.testPlanExecutionStarted(plan); + adapter.executionStarted(TestIdentifier.from(engine)); + adapter.executionStarted(TestIdentifier.from(parent)); + verify(listener) + .testSetStarting(new SimpleReportEntry(NORMAL_RUN, 0x0000000100000000L, className, null, null, null)); + verifyNoMoreInteractions(listener); + + adapter.executionStarted(TestIdentifier.from(child)); + verify(listener) + .testStarting(new SimpleReportEntry( + NORMAL_RUN, 0x0000000100000001L, className, null, MY_TEST_METHOD_NAME, null)); + verifyNoMoreInteractions(listener); + + adapter.executionFinished(TestIdentifier.from(child), successful()); + ArgumentCaptor report = ArgumentCaptor.forClass(SimpleReportEntry.class); + verify(listener).testSucceeded(report.capture()); + assertThat(report.getValue().getRunMode()).isEqualTo(NORMAL_RUN); + assertThat(report.getValue().getTestRunId()).isEqualTo(0x0000000100000001L); + assertThat(report.getValue().getSourceName()).isEqualTo(className); + assertThat(report.getValue().getSourceText()).isNull(); + assertThat(report.getValue().getName()).isEqualTo(MY_TEST_METHOD_NAME); + assertThat(report.getValue().getNameText()).isNull(); + assertThat(report.getValue().getElapsed()).isNotNull(); + assertThat(report.getValue().getSystemProperties()).isEmpty(); + verifyNoMoreInteractions(listener); + + adapter.executionFinished(TestIdentifier.from(parent), successful()); + report = ArgumentCaptor.forClass(SimpleReportEntry.class); + verify(listener).testSetCompleted(report.capture()); + assertThat(report.getValue().getSourceName()).isEqualTo(className); + assertThat(report.getValue().getName()).isNull(); + assertThat(report.getValue().getElapsed()).isNotNull(); + assertThat(report.getValue().getSystemProperties()).isNotEmpty(); + verifyNoMoreInteractions(listener); + + adapter.executionFinished(TestIdentifier.from(engine), successful()); + verifyNoMoreInteractions(listener); } @Test - public void displayNamesInClassAndMethods() - throws Exception - { + public void displayNamesInClassAndMethods() throws Exception { EngineDescriptor engine = newEngineDescriptor(); - TestDescriptor parent = newClassDescriptor( "parent" ); - engine.addChild( parent ); - - UniqueId id1 = parent.getUniqueId().append( MyTestClass.class.getName(), MY_NAMED_TEST_METHOD_NAME ); - Method m1 = MyTestClass.class.getDeclaredMethod( MY_NAMED_TEST_METHOD_NAME ); - TestDescriptor child1 = new TestMethodTestDescriptorWithDisplayName( id1, MyTestClass.class, m1, "dn1" ); - parent.addChild( child1 ); - - UniqueId id2 = parent.getUniqueId().append( MyTestClass.class.getName(), MY_TEST_METHOD_NAME ); - Method m2 = MyTestClass.class.getDeclaredMethod( MY_TEST_METHOD_NAME, String.class ); - TestDescriptor child2 = new TestMethodTestDescriptor( id2, MyTestClass.class, m2 ); - parent.addChild( child2 ); - - TestPlan plan = TestPlan.from( singletonList( engine ) ); - - InOrder inOrder = inOrder( listener ); - - adapter.testPlanExecutionStarted( plan ); - - adapter.executionStarted( TestIdentifier.from( engine ) ); - adapter.executionStarted( TestIdentifier.from( parent ) ); - ArgumentCaptor report = ArgumentCaptor.forClass( SimpleReportEntry.class ); - inOrder.verify( listener ).testSetStarting( report.capture() ); - assertThat( report.getValue().getTestRunId() ) - .isEqualTo( 0x0000000100000000L ); - assertThat( report.getValue().getSourceName() ) - .isEqualTo( MyTestClass.class.getName() ); - assertThat( report.getValue().getSourceText() ) - .isEqualTo( "parent" ); - assertThat( report.getValue().getName() ) - .isNull(); - assertThat( report.getValue().getSystemProperties() ) - .isEmpty(); - verifyZeroInteractions( listener ); - - adapter.executionStarted( TestIdentifier.from( child1 ) ); - inOrder.verify( listener ).testStarting( new SimpleReportEntry( NORMAL_RUN, 0x0000000100000001L, - MyTestClass.class.getName(), "parent", MY_NAMED_TEST_METHOD_NAME, "dn1" ) ); + TestDescriptor parent = newClassDescriptor("parent"); + engine.addChild(parent); + + UniqueId id1 = parent.getUniqueId().append(MyTestClass.class.getName(), MY_NAMED_TEST_METHOD_NAME); + Method m1 = MyTestClass.class.getDeclaredMethod(MY_NAMED_TEST_METHOD_NAME); + TestDescriptor child1 = new TestMethodTestDescriptorWithDisplayName(id1, MyTestClass.class, m1, "dn1"); + parent.addChild(child1); + + UniqueId id2 = parent.getUniqueId().append(MyTestClass.class.getName(), MY_TEST_METHOD_NAME); + Method m2 = MyTestClass.class.getDeclaredMethod(MY_TEST_METHOD_NAME, String.class); + TestDescriptor child2 = new TestMethodTestDescriptor(id2, MyTestClass.class, m2); + parent.addChild(child2); + + TestPlan plan = TestPlan.from(singletonList(engine)); + + InOrder inOrder = inOrder(listener); + + adapter.testPlanExecutionStarted(plan); + + adapter.executionStarted(TestIdentifier.from(engine)); + adapter.executionStarted(TestIdentifier.from(parent)); + ArgumentCaptor report = ArgumentCaptor.forClass(SimpleReportEntry.class); + inOrder.verify(listener).testSetStarting(report.capture()); + assertThat(report.getValue().getTestRunId()).isEqualTo(0x0000000100000000L); + assertThat(report.getValue().getSourceName()).isEqualTo(MyTestClass.class.getName()); + assertThat(report.getValue().getSourceText()).isEqualTo("parent"); + assertThat(report.getValue().getName()).isNull(); + assertThat(report.getValue().getSystemProperties()).isEmpty(); + verifyZeroInteractions(listener); + + adapter.executionStarted(TestIdentifier.from(child1)); + inOrder.verify(listener) + .testStarting(new SimpleReportEntry( + NORMAL_RUN, + 0x0000000100000001L, + MyTestClass.class.getName(), + "parent", + MY_NAMED_TEST_METHOD_NAME, + "dn1")); inOrder.verifyNoMoreInteractions(); - adapter.executionFinished( TestIdentifier.from( child1 ), successful() ); - report = ArgumentCaptor.forClass( SimpleReportEntry.class ); - inOrder.verify( listener ).testSucceeded( report.capture() ); - assertThat( report.getValue().getRunMode() ) - .isEqualTo( NORMAL_RUN ); - assertThat( report.getValue().getTestRunId() ) - .isEqualTo( 0x0000000100000001L ); - assertThat( report.getValue().getSourceName() ) - .isEqualTo( MyTestClass.class.getName() ); - assertThat( report.getValue().getSourceText() ) - .isEqualTo( "parent" ); - assertThat( report.getValue().getName() ) - .isEqualTo( MY_NAMED_TEST_METHOD_NAME ); - assertThat( report.getValue().getNameText() ) - .isEqualTo( "dn1" ); - assertThat( report.getValue().getElapsed() ) - .isNotNull(); - assertThat( report.getValue().getSystemProperties() ) - .isEmpty(); + adapter.executionFinished(TestIdentifier.from(child1), successful()); + report = ArgumentCaptor.forClass(SimpleReportEntry.class); + inOrder.verify(listener).testSucceeded(report.capture()); + assertThat(report.getValue().getRunMode()).isEqualTo(NORMAL_RUN); + assertThat(report.getValue().getTestRunId()).isEqualTo(0x0000000100000001L); + assertThat(report.getValue().getSourceName()).isEqualTo(MyTestClass.class.getName()); + assertThat(report.getValue().getSourceText()).isEqualTo("parent"); + assertThat(report.getValue().getName()).isEqualTo(MY_NAMED_TEST_METHOD_NAME); + assertThat(report.getValue().getNameText()).isEqualTo("dn1"); + assertThat(report.getValue().getElapsed()).isNotNull(); + assertThat(report.getValue().getSystemProperties()).isEmpty(); inOrder.verifyNoMoreInteractions(); - adapter.executionStarted( TestIdentifier.from( child2 ) ); - inOrder.verify( listener ) - .testStarting( new SimpleReportEntry( NORMAL_RUN, 0x0000000100000002L, MyTestClass.class.getName(), - "parent", MY_TEST_METHOD_NAME + "(String)", null ) ); + adapter.executionStarted(TestIdentifier.from(child2)); + inOrder.verify(listener) + .testStarting(new SimpleReportEntry( + NORMAL_RUN, + 0x0000000100000002L, + MyTestClass.class.getName(), + "parent", + MY_TEST_METHOD_NAME + "(String)", + null)); inOrder.verifyNoMoreInteractions(); Exception assumptionFailure = new Exception(); - adapter.executionFinished( TestIdentifier.from( child2 ), aborted( assumptionFailure ) ); - report = ArgumentCaptor.forClass( SimpleReportEntry.class ); - inOrder.verify( listener ).testAssumptionFailure( report.capture() ); - assertThat( report.getValue().getRunMode() ) - .isEqualTo( NORMAL_RUN ); - assertThat( report.getValue().getTestRunId() ) - .isEqualTo( 0x0000000100000002L ); - assertThat( report.getValue().getSourceName() ) - .isEqualTo( MyTestClass.class.getName() ); - assertThat( report.getValue().getSourceText() ) - .isEqualTo( "parent" ); - assertThat( report.getValue().getName() ) - .isEqualTo( MY_TEST_METHOD_NAME + "(String)" ); - assertThat( report.getValue().getNameText() ) - .isNull(); - assertThat( report.getValue().getElapsed() ) - .isNotNull(); - assertThat( report.getValue().getSystemProperties() ) - .isEmpty(); - assertThat( report.getValue().getStackTraceWriter() ) - .isNotNull(); - assertThat( report.getValue().getStackTraceWriter().getThrowable().getTarget() ) - .isSameAs( assumptionFailure ); + adapter.executionFinished(TestIdentifier.from(child2), aborted(assumptionFailure)); + report = ArgumentCaptor.forClass(SimpleReportEntry.class); + inOrder.verify(listener).testAssumptionFailure(report.capture()); + assertThat(report.getValue().getRunMode()).isEqualTo(NORMAL_RUN); + assertThat(report.getValue().getTestRunId()).isEqualTo(0x0000000100000002L); + assertThat(report.getValue().getSourceName()).isEqualTo(MyTestClass.class.getName()); + assertThat(report.getValue().getSourceText()).isEqualTo("parent"); + assertThat(report.getValue().getName()).isEqualTo(MY_TEST_METHOD_NAME + "(String)"); + assertThat(report.getValue().getNameText()).isNull(); + assertThat(report.getValue().getElapsed()).isNotNull(); + assertThat(report.getValue().getSystemProperties()).isEmpty(); + assertThat(report.getValue().getStackTraceWriter()).isNotNull(); + assertThat(report.getValue().getStackTraceWriter().getThrowable().getTarget()) + .isSameAs(assumptionFailure); inOrder.verifyNoMoreInteractions(); - adapter.executionFinished( TestIdentifier.from( parent ), successful() ); - inOrder.verify( listener ).testSetCompleted( report.capture() ); - assertThat( report.getValue().getSourceName() ) - .isEqualTo( MyTestClass.class.getName() ); - assertThat( report.getValue().getSourceText() ) - .isEqualTo( "parent" ); - assertThat( report.getValue().getName() ) - .isNull(); - assertThat( report.getValue().getNameText() ) - .isNull(); - assertThat( report.getValue().getElapsed() ) - .isNotNull(); - assertThat( report.getValue().getSystemProperties() ) - .isNotEmpty(); - assertThat( report.getValue().getStackTraceWriter() ) - .isNull(); + adapter.executionFinished(TestIdentifier.from(parent), successful()); + inOrder.verify(listener).testSetCompleted(report.capture()); + assertThat(report.getValue().getSourceName()).isEqualTo(MyTestClass.class.getName()); + assertThat(report.getValue().getSourceText()).isEqualTo("parent"); + assertThat(report.getValue().getName()).isNull(); + assertThat(report.getValue().getNameText()).isNull(); + assertThat(report.getValue().getElapsed()).isNotNull(); + assertThat(report.getValue().getSystemProperties()).isNotEmpty(); + assertThat(report.getValue().getStackTraceWriter()).isNull(); inOrder.verifyNoMoreInteractions(); - adapter.executionFinished( TestIdentifier.from( engine ), successful() ); + adapter.executionFinished(TestIdentifier.from(engine), successful()); inOrder.verifyNoMoreInteractions(); } @Test - public void notifiedForUnclassifiedTestIdentifier() - { - EngineDescriptor engine = new EngineDescriptor( UniqueId.forEngine( "engine" ), "engine" ) - { + public void notifiedForUnclassifiedTestIdentifier() { + EngineDescriptor engine = new EngineDescriptor(UniqueId.forEngine("engine"), "engine") { @Override - public Type getType() - { + public Type getType() { return TEST; } }; - TestPlan plan = TestPlan.from( singletonList( engine ) ); - - adapter.testPlanExecutionStarted( plan ); - assertThat( (TestPlan) getInternalState( adapter, "testPlan" ) ) - .isSameAs( plan ); - assertThat( (Map) getInternalState( adapter, "testStartTime" ) ) - .isEmpty(); - - - adapter.executionStarted( TestIdentifier.from( engine ) ); - verify( listener ).testStarting( new SimpleReportEntry( NORMAL_RUN, 0x0000000100000001L, "engine", null, - "engine", null ) ); - verifyNoMoreInteractions( listener ); - - adapter.executionFinished( TestIdentifier.from( engine ), successful() ); - ArgumentCaptor report = ArgumentCaptor.forClass( SimpleReportEntry.class ); - verify( listener ).testSucceeded( report.capture() ); - assertThat( report.getValue().getRunMode() ) - .isEqualTo( NORMAL_RUN ); - assertThat( report.getValue().getTestRunId() ) - .isEqualTo( 0x0000000100000001L ); - assertThat( report.getValue().getSourceName() ) - .isEqualTo( "engine" ); - assertThat( report.getValue().getSourceText() ) - .isNull(); - assertThat( report.getValue().getName() ) - .isEqualTo( "engine" ); - assertThat( report.getValue().getNameText() ) - .isNull(); - assertThat( report.getValue().getElapsed() ) - .isNotNull(); - assertThat( report.getValue().getStackTraceWriter() ) - .isNull(); - assertThat( report.getValue().getSystemProperties() ) - .isEmpty(); - - adapter.testPlanExecutionFinished( plan ); - assertThat( (TestPlan) getInternalState( adapter, "testPlan" ) ) - .isNull(); - assertThat( (Map) getInternalState( adapter, "testStartTime" ) ) - .isEmpty(); - - verifyNoMoreInteractions( listener ); + TestPlan plan = TestPlan.from(singletonList(engine)); + + adapter.testPlanExecutionStarted(plan); + assertThat((TestPlan) getInternalState(adapter, "testPlan")).isSameAs(plan); + assertThat((Map) getInternalState(adapter, "testStartTime")).isEmpty(); + + adapter.executionStarted(TestIdentifier.from(engine)); + verify(listener) + .testStarting(new SimpleReportEntry(NORMAL_RUN, 0x0000000100000001L, "engine", null, "engine", null)); + verifyNoMoreInteractions(listener); + + adapter.executionFinished(TestIdentifier.from(engine), successful()); + ArgumentCaptor report = ArgumentCaptor.forClass(SimpleReportEntry.class); + verify(listener).testSucceeded(report.capture()); + assertThat(report.getValue().getRunMode()).isEqualTo(NORMAL_RUN); + assertThat(report.getValue().getTestRunId()).isEqualTo(0x0000000100000001L); + assertThat(report.getValue().getSourceName()).isEqualTo("engine"); + assertThat(report.getValue().getSourceText()).isNull(); + assertThat(report.getValue().getName()).isEqualTo("engine"); + assertThat(report.getValue().getNameText()).isNull(); + assertThat(report.getValue().getElapsed()).isNotNull(); + assertThat(report.getValue().getStackTraceWriter()).isNull(); + assertThat(report.getValue().getSystemProperties()).isEmpty(); + + adapter.testPlanExecutionFinished(plan); + assertThat((TestPlan) getInternalState(adapter, "testPlan")).isNull(); + assertThat((Map) getInternalState(adapter, "testStartTime")).isEmpty(); + + verifyNoMoreInteractions(listener); } @Test - public void notNotifiedWhenEngineExecutionStarted() - { - adapter.executionStarted( newEngineIdentifier() ); - verify( listener, never() ).testStarting( any() ); + public void notNotifiedWhenEngineExecutionStarted() { + adapter.executionStarted(newEngineIdentifier()); + verify(listener, never()).testStarting(any()); } @Test - public void notifiedWhenMethodExecutionSkipped() - throws Exception - { - adapter.executionSkipped( newMethodIdentifier(), "test" ); - verify( listener ).testSkipped( any() ); + public void notifiedWhenMethodExecutionSkipped() throws Exception { + adapter.executionSkipped(newMethodIdentifier(), "test"); + verify(listener).testSkipped(any()); } @Test - public void notifiedWithCorrectNamesWhenClassExecutionSkipped() throws Exception - { - EngineDescriptor engineDescriptor = new EngineDescriptor( newId(), "Luke's Plan" ); + public void notifiedWithCorrectNamesWhenClassExecutionSkipped() throws Exception { + EngineDescriptor engineDescriptor = new EngineDescriptor(newId(), "Luke's Plan"); TestDescriptor classTestDescriptor = newClassDescriptor(); TestDescriptor method1 = newMethodDescriptor(); - classTestDescriptor.addChild( method1 ); + classTestDescriptor.addChild(method1); TestDescriptor method2 = newMethodDescriptor(); - classTestDescriptor.addChild( method2 ); - engineDescriptor.addChild( classTestDescriptor ); - TestPlan testPlan = TestPlan.from( singletonList( engineDescriptor ) ); - adapter.testPlanExecutionStarted( testPlan ); + classTestDescriptor.addChild(method2); + engineDescriptor.addChild(classTestDescriptor); + TestPlan testPlan = TestPlan.from(singletonList(engineDescriptor)); + adapter.testPlanExecutionStarted(testPlan); TestIdentifier classIdentifier = - identifiersAsParentOnTestPlan( testPlan, newEngineDescriptor(), newClassDescriptor() ); + identifiersAsParentOnTestPlan(testPlan, newEngineDescriptor(), newClassDescriptor()); - ArgumentCaptor entryCaptor1 = ArgumentCaptor.forClass( TestSetReportEntry.class ); - ArgumentCaptor entryCaptor2 = ArgumentCaptor.forClass( ReportEntry.class ); - ArgumentCaptor entryCaptor3 = ArgumentCaptor.forClass( ReportEntry.class ); - ArgumentCaptor entryCaptor4 = ArgumentCaptor.forClass( TestSetReportEntry.class ); + ArgumentCaptor entryCaptor1 = ArgumentCaptor.forClass(TestSetReportEntry.class); + ArgumentCaptor entryCaptor2 = ArgumentCaptor.forClass(ReportEntry.class); + ArgumentCaptor entryCaptor3 = ArgumentCaptor.forClass(ReportEntry.class); + ArgumentCaptor entryCaptor4 = ArgumentCaptor.forClass(TestSetReportEntry.class); - adapter.executionSkipped( classIdentifier, "test" ); - verify( listener ).testSetStarting( entryCaptor1.capture() ); - verify( listener ).testSkipped( entryCaptor2.capture() ); - verify( listener ).testSkipped( entryCaptor3.capture() ); - verify( listener ).testSetCompleted( entryCaptor4.capture() ); + adapter.executionSkipped(classIdentifier, "test"); + verify(listener).testSetStarting(entryCaptor1.capture()); + verify(listener).testSkipped(entryCaptor2.capture()); + verify(listener).testSkipped(entryCaptor3.capture()); + verify(listener).testSetCompleted(entryCaptor4.capture()); ReportEntry entry1 = entryCaptor1.getValue(); - assertNull( entry1.getName() ); - assertEquals( MyTestClass.class.getTypeName(), entry1.getSourceName() ); + assertNull(entry1.getName()); + assertEquals(MyTestClass.class.getTypeName(), entry1.getSourceName()); ReportEntry entry4 = entryCaptor1.getValue(); - assertNull( entry4.getName() ); - assertEquals( MyTestClass.class.getTypeName(), entry4.getSourceName() ); + assertNull(entry4.getName()); + assertEquals(MyTestClass.class.getTypeName(), entry4.getSourceName()); } @Test - public void notifiedWhenMethodExecutionAborted() - throws Exception - { - adapter.executionFinished( newMethodIdentifier(), aborted( null ) ); - verify( listener ).testAssumptionFailure( any() ); + public void notifiedWhenMethodExecutionAborted() throws Exception { + adapter.executionFinished(newMethodIdentifier(), aborted(null)); + verify(listener).testAssumptionFailure(any()); } @Test - public void notifiedWhenClassExecutionAborted() - { - TestSkippedException t = new TestSkippedException( "skipped" ); - adapter.executionFinished( newClassIdentifier(), aborted( t ) ); + public void notifiedWhenClassExecutionAborted() { + TestSkippedException t = new TestSkippedException("skipped"); + adapter.executionFinished(newClassIdentifier(), aborted(t)); String source = MyTestClass.class.getName(); - StackTraceWriter stw = new PojoStackTraceWriter( source, null, t ); - ArgumentCaptor report = ArgumentCaptor.forClass( SimpleReportEntry.class ); - verify( listener ).testSetCompleted( report.capture() ); - assertThat( report.getValue().getSourceName() ) - .isEqualTo( source ); - assertThat( report.getValue().getStackTraceWriter() ) - .isEqualTo( stw ); + StackTraceWriter stw = new PojoStackTraceWriter(source, null, t); + ArgumentCaptor report = ArgumentCaptor.forClass(SimpleReportEntry.class); + verify(listener).testSetCompleted(report.capture()); + assertThat(report.getValue().getSourceName()).isEqualTo(source); + assertThat(report.getValue().getStackTraceWriter()).isEqualTo(stw); } @Test - public void notifiedOfContainerFailureWhenErrored() - throws Exception - { - adapter.executionFinished( newContainerIdentifier(), failed( new RuntimeException() ) ); - verify( listener ).testError( any() ); + public void notifiedOfContainerFailureWhenErrored() throws Exception { + adapter.executionFinished(newContainerIdentifier(), failed(new RuntimeException())); + verify(listener).testError(any()); } @Test - public void notifiedOfContainerFailureWhenFailed() - throws Exception - { - adapter.executionFinished( newContainerIdentifier(), failed( new AssertionError() ) ); - verify( listener ).testFailed( any() ); + public void notifiedOfContainerFailureWhenFailed() throws Exception { + adapter.executionFinished(newContainerIdentifier(), failed(new AssertionError())); + verify(listener).testFailed(any()); } @Test - public void notifiedWhenMethodExecutionFailed() - throws Exception - { - adapter.executionFinished( newMethodIdentifier(), failed( new AssertionError() ) ); - verify( listener ).testFailed( any() ); + public void notifiedWhenMethodExecutionFailed() throws Exception { + adapter.executionFinished(newMethodIdentifier(), failed(new AssertionError())); + verify(listener).testFailed(any()); } @Test - public void notifiedWhenMethodExecutionFailedWithError() - throws Exception - { - adapter.executionFinished( newMethodIdentifier(), failed( new RuntimeException() ) ); - verify( listener ).testError( any() ); + public void notifiedWhenMethodExecutionFailedWithError() throws Exception { + adapter.executionFinished(newMethodIdentifier(), failed(new RuntimeException())); + verify(listener).testError(any()); } @Test - public void notifiedWithCorrectNamesWhenClassExecutionFailed() - { - ArgumentCaptor entryCaptor = ArgumentCaptor.forClass( ReportEntry.class ); - TestPlan testPlan = TestPlan.from( singletonList( new EngineDescriptor( newId(), "Luke's Plan" ) ) ); - adapter.testPlanExecutionStarted( testPlan ); + public void notifiedWithCorrectNamesWhenClassExecutionFailed() { + ArgumentCaptor entryCaptor = ArgumentCaptor.forClass(ReportEntry.class); + TestPlan testPlan = TestPlan.from(singletonList(new EngineDescriptor(newId(), "Luke's Plan"))); + adapter.testPlanExecutionStarted(testPlan); - adapter.executionFinished( identifiersAsParentOnTestPlan( testPlan, newClassDescriptor() ), - failed( new AssertionError() ) ); - verify( listener ).testFailed( entryCaptor.capture() ); + adapter.executionFinished( + identifiersAsParentOnTestPlan(testPlan, newClassDescriptor()), failed(new AssertionError())); + verify(listener).testFailed(entryCaptor.capture()); ReportEntry entry = entryCaptor.getValue(); - assertEquals( MyTestClass.class.getTypeName(), entry.getSourceName() ); - assertNull( entry.getName() ); - assertNotNull( entry.getStackTraceWriter() ); - assertNotNull( entry.getStackTraceWriter().getThrowable() ); - assertThat( entry.getStackTraceWriter().getThrowable().getTarget() ) - .isInstanceOf( AssertionError.class ); + assertEquals(MyTestClass.class.getTypeName(), entry.getSourceName()); + assertNull(entry.getName()); + assertNotNull(entry.getStackTraceWriter()); + assertNotNull(entry.getStackTraceWriter().getThrowable()); + assertThat(entry.getStackTraceWriter().getThrowable().getTarget()).isInstanceOf(AssertionError.class); } @Test - public void notifiedWithCorrectNamesWhenClassExecutionErrored() - { - ArgumentCaptor entryCaptor = ArgumentCaptor.forClass( ReportEntry.class ); - TestPlan testPlan = TestPlan.from( singletonList( new EngineDescriptor( newId(), "Luke's Plan" ) ) ); - adapter.testPlanExecutionStarted( testPlan ); + public void notifiedWithCorrectNamesWhenClassExecutionErrored() { + ArgumentCaptor entryCaptor = ArgumentCaptor.forClass(ReportEntry.class); + TestPlan testPlan = TestPlan.from(singletonList(new EngineDescriptor(newId(), "Luke's Plan"))); + adapter.testPlanExecutionStarted(testPlan); - adapter.executionFinished( identifiersAsParentOnTestPlan( testPlan, newClassDescriptor() ), - failed( new RuntimeException() ) ); - verify( listener ).testError( entryCaptor.capture() ); + adapter.executionFinished( + identifiersAsParentOnTestPlan(testPlan, newClassDescriptor()), failed(new RuntimeException())); + verify(listener).testError(entryCaptor.capture()); ReportEntry entry = entryCaptor.getValue(); - assertEquals( MyTestClass.class.getTypeName(), entry.getSourceName() ); - assertNull( entry.getName() ); - assertNotNull( entry.getStackTraceWriter() ); - assertNotNull( entry.getStackTraceWriter().getThrowable() ); - assertThat( entry.getStackTraceWriter().getThrowable().getTarget() ) - .isInstanceOf( RuntimeException.class ); + assertEquals(MyTestClass.class.getTypeName(), entry.getSourceName()); + assertNull(entry.getName()); + assertNotNull(entry.getStackTraceWriter()); + assertNotNull(entry.getStackTraceWriter().getThrowable()); + assertThat(entry.getStackTraceWriter().getThrowable().getTarget()).isInstanceOf(RuntimeException.class); } @Test - public void notifiedWithCorrectNamesWhenContainerFailed() - throws Exception - { - ArgumentCaptor entryCaptor = ArgumentCaptor.forClass( ReportEntry.class ); - TestPlan testPlan = TestPlan.from( singletonList( new EngineDescriptor( newId(), "Luke's Plan" ) ) ); - adapter.testPlanExecutionStarted( testPlan ); + public void notifiedWithCorrectNamesWhenContainerFailed() throws Exception { + ArgumentCaptor entryCaptor = ArgumentCaptor.forClass(ReportEntry.class); + TestPlan testPlan = TestPlan.from(singletonList(new EngineDescriptor(newId(), "Luke's Plan"))); + adapter.testPlanExecutionStarted(testPlan); - adapter.executionFinished( newContainerIdentifier(), failed( new RuntimeException() ) ); - verify( listener ).testError( entryCaptor.capture() ); + adapter.executionFinished(newContainerIdentifier(), failed(new RuntimeException())); + verify(listener).testError(entryCaptor.capture()); ReportEntry entry = entryCaptor.getValue(); - assertEquals( MyTestClass.class.getTypeName(), entry.getSourceName() ); - assertEquals( MY_TEST_METHOD_NAME, entry.getName() ); - assertNotNull( entry.getStackTraceWriter() ); - assertNotNull( entry.getStackTraceWriter().getThrowable() ); - assertThat( entry.getStackTraceWriter().getThrowable().getTarget() ) - .isInstanceOf( RuntimeException.class ); + assertEquals(MyTestClass.class.getTypeName(), entry.getSourceName()); + assertEquals(MY_TEST_METHOD_NAME, entry.getName()); + assertNotNull(entry.getStackTraceWriter()); + assertNotNull(entry.getStackTraceWriter().getThrowable()); + assertThat(entry.getStackTraceWriter().getThrowable().getTarget()).isInstanceOf(RuntimeException.class); } @Test - public void notifiedWhenMethodExecutionSucceeded() - throws Exception - { - adapter.executionFinished( newMethodIdentifier(), successful() ); - verify( listener ).testSucceeded( any() ); + public void notifiedWhenMethodExecutionSucceeded() throws Exception { + adapter.executionFinished(newMethodIdentifier(), successful()); + verify(listener).testSucceeded(any()); } @Test - public void notifiedForTestSetWhenClassExecutionSucceeded() - { + public void notifiedForTestSetWhenClassExecutionSucceeded() { EngineDescriptor engineDescriptor = newEngineDescriptor(); TestDescriptor classDescriptor = newClassDescriptor(); - engineDescriptor.addChild( classDescriptor ); - adapter.testPlanExecutionStarted( TestPlan.from( singleton( engineDescriptor ) ) ); - adapter.executionStarted( TestIdentifier.from( classDescriptor ) ); + engineDescriptor.addChild(classDescriptor); + adapter.testPlanExecutionStarted(TestPlan.from(singleton(engineDescriptor))); + adapter.executionStarted(TestIdentifier.from(classDescriptor)); - adapter.executionFinished( TestIdentifier.from( classDescriptor ), successful() ); + adapter.executionFinished(TestIdentifier.from(classDescriptor), successful()); String className = MyTestClass.class.getName(); - verify( listener ).testSetStarting( new SimpleReportEntry( NORMAL_RUN, 0x0000000100000000L, className, null, - null, null ) ); - - ArgumentCaptor report = ArgumentCaptor.forClass( SimpleReportEntry.class ); - verify( listener ) - .testSetCompleted( report.capture() ); - assertThat( report.getValue().getRunMode() ) - .isEqualTo( NORMAL_RUN ); - assertThat( report.getValue().getTestRunId() ) - .isEqualTo( 0x0000000100000000L ); - assertThat( report.getValue().getSourceName() ) - .isEqualTo( className ); - assertThat( report.getValue().getSourceText() ) - .isNull(); - assertThat( report.getValue().getName() ) - .isNull(); - assertThat( report.getValue().getNameText() ) - .isNull(); - assertThat( report.getValue().getStackTraceWriter() ) - .isNull(); - assertThat( report.getValue().getElapsed() ) - .isNotNull(); - assertThat( report.getValue().getSystemProperties() ) - .isNotEmpty(); - - verify( listener, never() ) - .testSucceeded( any() ); - - verifyNoMoreInteractions( listener ); + verify(listener) + .testSetStarting(new SimpleReportEntry(NORMAL_RUN, 0x0000000100000000L, className, null, null, null)); + + ArgumentCaptor report = ArgumentCaptor.forClass(SimpleReportEntry.class); + verify(listener).testSetCompleted(report.capture()); + assertThat(report.getValue().getRunMode()).isEqualTo(NORMAL_RUN); + assertThat(report.getValue().getTestRunId()).isEqualTo(0x0000000100000000L); + assertThat(report.getValue().getSourceName()).isEqualTo(className); + assertThat(report.getValue().getSourceText()).isNull(); + assertThat(report.getValue().getName()).isNull(); + assertThat(report.getValue().getNameText()).isNull(); + assertThat(report.getValue().getStackTraceWriter()).isNull(); + assertThat(report.getValue().getElapsed()).isNotNull(); + assertThat(report.getValue().getSystemProperties()).isNotEmpty(); + + verify(listener, never()).testSucceeded(any()); + + verifyNoMoreInteractions(listener); } @Test - public void notifiedWithParentDisplayNameWhenTestClassUnknown() - { + public void notifiedWithParentDisplayNameWhenTestClassUnknown() { // Set up a test plan - TestPlan plan = TestPlan.from( singletonList( new EngineDescriptor( newId(), "Luke's Plan" ) ) ); - adapter.testPlanExecutionStarted( plan ); + TestPlan plan = TestPlan.from(singletonList(new EngineDescriptor(newId(), "Luke's Plan"))); + adapter.testPlanExecutionStarted(plan); // Use the test plan to set up child with parent. final String parentDisplay = "I am your father"; - TestIdentifier child = newSourcelessChildIdentifierWithParent( plan, parentDisplay, null ); - adapter.executionStarted( child ); + TestIdentifier child = newSourcelessChildIdentifierWithParent(plan, parentDisplay, null); + adapter.executionStarted(child); // Check that the adapter has informed Surefire that the test has been invoked, // with the parent name as source (since the test case itself had no source). - ArgumentCaptor entryCaptor = ArgumentCaptor.forClass( ReportEntry.class ); - verify( listener ).testStarting( entryCaptor.capture() ); - assertEquals( parentDisplay, entryCaptor.getValue().getSourceName() ); - assertNull( entryCaptor.getValue().getSourceText() ); - assertNull( entryCaptor.getValue().getName() ); - assertNull( entryCaptor.getValue().getNameText() ); + ArgumentCaptor entryCaptor = ArgumentCaptor.forClass(ReportEntry.class); + verify(listener).testStarting(entryCaptor.capture()); + assertEquals(parentDisplay, entryCaptor.getValue().getSourceName()); + assertNull(entryCaptor.getValue().getSourceText()); + assertNull(entryCaptor.getValue().getName()); + assertNull(entryCaptor.getValue().getNameText()); } @Test - public void stackTraceWriterPresentWhenParentHasSource() - { - TestPlan plan = TestPlan.from( singletonList( new EngineDescriptor( newId(), "Some Plan" ) ) ); - adapter.testPlanExecutionStarted( plan ); + public void stackTraceWriterPresentWhenParentHasSource() { + TestPlan plan = TestPlan.from(singletonList(new EngineDescriptor(newId(), "Some Plan"))); + adapter.testPlanExecutionStarted(plan); TestIdentifier child = - newSourcelessChildIdentifierWithParent( plan, "Parent", ClassSource.from( MyTestClass.class ) ); - adapter.executionFinished( child, failed( new RuntimeException() ) ); - ArgumentCaptor entryCaptor = ArgumentCaptor.forClass( ReportEntry.class ); - verify( listener ).testError( entryCaptor.capture() ); - assertNotNull( entryCaptor.getValue().getStackTraceWriter() ); + newSourcelessChildIdentifierWithParent(plan, "Parent", ClassSource.from(MyTestClass.class)); + adapter.executionFinished(child, failed(new RuntimeException())); + ArgumentCaptor entryCaptor = ArgumentCaptor.forClass(ReportEntry.class); + verify(listener).testError(entryCaptor.capture()); + assertNotNull(entryCaptor.getValue().getStackTraceWriter()); } @Test - public void stackTraceWriterDefaultsToTestClass() - { - TestPlan plan = TestPlan.from( singletonList( new EngineDescriptor( newId(), "Some Plan" ) ) ); - adapter.testPlanExecutionStarted( plan ); + public void stackTraceWriterDefaultsToTestClass() { + TestPlan plan = TestPlan.from(singletonList(new EngineDescriptor(newId(), "Some Plan"))); + adapter.testPlanExecutionStarted(plan); - TestIdentifier child = newSourcelessChildIdentifierWithParent( plan, "Parent", null ); - adapter.executionFinished( child, failed( new RuntimeException( "message" ) ) ); - ArgumentCaptor entryCaptor = ArgumentCaptor.forClass( ReportEntry.class ); - verify( listener ).testError( entryCaptor.capture() ); - assertNotNull( entryCaptor.getValue().getStackTraceWriter() ); - assertNotNull( entryCaptor.getValue().getStackTraceWriter().smartTrimmedStackTrace() ); - assertNotNull( entryCaptor.getValue().getStackTraceWriter().writeTraceToString() ); - assertNotNull( entryCaptor.getValue().getStackTraceWriter().writeTrimmedTraceToString() ); + TestIdentifier child = newSourcelessChildIdentifierWithParent(plan, "Parent", null); + adapter.executionFinished(child, failed(new RuntimeException("message"))); + ArgumentCaptor entryCaptor = ArgumentCaptor.forClass(ReportEntry.class); + verify(listener).testError(entryCaptor.capture()); + assertNotNull(entryCaptor.getValue().getStackTraceWriter()); + assertNotNull(entryCaptor.getValue().getStackTraceWriter().smartTrimmedStackTrace()); + assertNotNull(entryCaptor.getValue().getStackTraceWriter().writeTraceToString()); + assertNotNull(entryCaptor.getValue().getStackTraceWriter().writeTrimmedTraceToString()); } @Test - public void stackTraceWriterPresentEvenWithoutException() - throws Exception - { - adapter.executionFinished( newMethodIdentifier(), failed( null ) ); - ArgumentCaptor entryCaptor = ArgumentCaptor.forClass( ReportEntry.class ); - verify( listener ).testError( entryCaptor.capture() ); - assertNotNull( entryCaptor.getValue().getStackTraceWriter() ); + public void stackTraceWriterPresentEvenWithoutException() throws Exception { + adapter.executionFinished(newMethodIdentifier(), failed(null)); + ArgumentCaptor entryCaptor = ArgumentCaptor.forClass(ReportEntry.class); + verify(listener).testError(entryCaptor.capture()); + assertNotNull(entryCaptor.getValue().getStackTraceWriter()); } @Test - public void displayNamesIgnoredInReport() - throws NoSuchMethodException - { - TestMethodTestDescriptorWithDisplayName descriptor = new TestMethodTestDescriptorWithDisplayName( newId(), - MyTestClass.class, MyTestClass.class.getDeclaredMethod( "myNamedTestMethod" ), "some display name" ); + public void displayNamesIgnoredInReport() throws NoSuchMethodException { + TestMethodTestDescriptorWithDisplayName descriptor = new TestMethodTestDescriptorWithDisplayName( + newId(), + MyTestClass.class, + MyTestClass.class.getDeclaredMethod("myNamedTestMethod"), + "some display name"); - TestIdentifier factoryIdentifier = TestIdentifier.from( descriptor ); - ArgumentCaptor entryCaptor = ArgumentCaptor.forClass( ReportEntry.class ); + TestIdentifier factoryIdentifier = TestIdentifier.from(descriptor); + ArgumentCaptor entryCaptor = ArgumentCaptor.forClass(ReportEntry.class); - adapter.executionSkipped( factoryIdentifier, "" ); - verify( listener ).testSkipped( entryCaptor.capture() ); + adapter.executionSkipped(factoryIdentifier, ""); + verify(listener).testSkipped(entryCaptor.capture()); ReportEntry value = entryCaptor.getValue(); - assertEquals( MyTestClass.class.getName(), value.getSourceName() ); - assertNull( value.getSourceText() ); - assertEquals( "myNamedTestMethod", value.getName() ); - assertEquals( "some display name", value.getNameText() ); + assertEquals(MyTestClass.class.getName(), value.getSourceName()); + assertNull(value.getSourceText()); + assertEquals("myNamedTestMethod", value.getName()); + assertEquals("some display name", value.getNameText()); } - private static TestIdentifier newMethodIdentifier() - throws Exception - { - return TestIdentifier.from( newMethodDescriptor() ); + private static TestIdentifier newMethodIdentifier() throws Exception { + return TestIdentifier.from(newMethodDescriptor()); } - private static TestDescriptor newMethodDescriptor( Class... parameterTypes ) - throws Exception - { + private static TestDescriptor newMethodDescriptor(Class... parameterTypes) throws Exception { return new TestMethodTestDescriptor( - UniqueId.forEngine( "method" ), - MyTestClass.class, - MyTestClass.class.getDeclaredMethod( MY_TEST_METHOD_NAME, parameterTypes ) ); + UniqueId.forEngine("method"), + MyTestClass.class, + MyTestClass.class.getDeclaredMethod(MY_TEST_METHOD_NAME, parameterTypes)); } - private static TestIdentifier newClassIdentifier() - { - return TestIdentifier.from( newClassDescriptor() ); + private static TestIdentifier newClassIdentifier() { + return TestIdentifier.from(newClassDescriptor()); } - private static TestDescriptor newClassDescriptor( String displayName ) - { - return new ClassTestDescriptor( UniqueId.root( "class", MyTestClass.class.getName() ), - c -> displayName, MyTestClass.class, CONFIG_PARAMS ) - { }; + private static TestDescriptor newClassDescriptor(String displayName) { + return new ClassTestDescriptor( + UniqueId.root("class", MyTestClass.class.getName()), + c -> displayName, + MyTestClass.class, + CONFIG_PARAMS) {}; } - private static TestDescriptor newClassDescriptor() - { - return new ClassTestDescriptor( UniqueId.root( "class", MyTestClass.class.getName() ), - MyTestClass.class, CONFIG_PARAMS ); + private static TestDescriptor newClassDescriptor() { + return new ClassTestDescriptor( + UniqueId.root("class", MyTestClass.class.getName()), MyTestClass.class, CONFIG_PARAMS); } private static TestIdentifier newSourcelessChildIdentifierWithParent( - TestPlan testPlan, String parentDisplay, TestSource parentTestSource ) - { + TestPlan testPlan, String parentDisplay, TestSource parentTestSource) { // A parent test identifier with a name. - TestDescriptor parent = mock( TestDescriptor.class ); - when( parent.getUniqueId() ).thenReturn( newId() ); - when( parent.getDisplayName() ).thenReturn( parentDisplay ); - when( parent.getLegacyReportingName() ).thenReturn( parentDisplay ); - when( parent.getSource() ).thenReturn( Optional.ofNullable( parentTestSource ) ); - when( parent.getType() ).thenReturn( CONTAINER ); - TestIdentifier parentId = TestIdentifier.from( parent ); + TestDescriptor parent = mock(TestDescriptor.class); + when(parent.getUniqueId()).thenReturn(newId()); + when(parent.getDisplayName()).thenReturn(parentDisplay); + when(parent.getLegacyReportingName()).thenReturn(parentDisplay); + when(parent.getSource()).thenReturn(Optional.ofNullable(parentTestSource)); + when(parent.getType()).thenReturn(CONTAINER); + TestIdentifier parentId = TestIdentifier.from(parent); // The (child) test case that is to be executed as part of a test plan. - TestDescriptor child = mock( TestDescriptor.class ); - when( child.getUniqueId() ).thenReturn( newId() ); - when( child.getType() ).thenReturn( TEST ); - when( child.getLegacyReportingName() ).thenReturn( "child" ); + TestDescriptor child = mock(TestDescriptor.class); + when(child.getUniqueId()).thenReturn(newId()); + when(child.getType()).thenReturn(TEST); + when(child.getLegacyReportingName()).thenReturn("child"); // Ensure the child source is null yet that there is a parent -- the special case to be tested. - when( child.getSource() ).thenReturn( Optional.empty() ); - when( child.getParent() ).thenReturn( Optional.of( parent ) ); - TestIdentifier childId = TestIdentifier.from( child ); + when(child.getSource()).thenReturn(Optional.empty()); + when(child.getParent()).thenReturn(Optional.of(parent)); + TestIdentifier childId = TestIdentifier.from(child); - testPlan.add( childId ); - testPlan.add( parentId ); + testPlan.add(childId); + testPlan.add(parentId); return childId; } - private static TestIdentifier newContainerIdentifier() - throws Exception - { - return TestIdentifier.from( - new TestTemplateTestDescriptor( UniqueId.forEngine( "method" ), - MyTestClass.class, - MyTestClass.class.getDeclaredMethod( MY_TEST_METHOD_NAME ) ) ); + private static TestIdentifier newContainerIdentifier() throws Exception { + return TestIdentifier.from(new TestTemplateTestDescriptor( + UniqueId.forEngine("method"), + MyTestClass.class, + MyTestClass.class.getDeclaredMethod(MY_TEST_METHOD_NAME))); } - private static TestIdentifier newEngineIdentifier() - { + private static TestIdentifier newEngineIdentifier() { TestDescriptor testDescriptor = newEngineDescriptor(); - return TestIdentifier.from( testDescriptor ); + return TestIdentifier.from(testDescriptor); } - private static EngineDescriptor newEngineDescriptor() - { - return new EngineDescriptor( UniqueId.forEngine( "engine" ), "engine" ); + private static EngineDescriptor newEngineDescriptor() { + return new EngineDescriptor(UniqueId.forEngine("engine"), "engine"); } private static TestIdentifier identifiersAsParentOnTestPlan( - TestPlan plan, TestDescriptor parent, TestDescriptor child ) - { - child.setParent( parent ); + TestPlan plan, TestDescriptor parent, TestDescriptor child) { + child.setParent(parent); - TestIdentifier parentIdentifier = TestIdentifier.from( parent ); - TestIdentifier childIdentifier = TestIdentifier.from( child ); + TestIdentifier parentIdentifier = TestIdentifier.from(parent); + TestIdentifier childIdentifier = TestIdentifier.from(child); - plan.add( parentIdentifier ); - plan.add( childIdentifier ); + plan.add(parentIdentifier); + plan.add(childIdentifier); return childIdentifier; } - private static TestIdentifier identifiersAsParentOnTestPlan( TestPlan plan, TestDescriptor root ) - { - TestIdentifier rootIdentifier = TestIdentifier.from( root ); - plan.add( rootIdentifier ); + private static TestIdentifier identifiersAsParentOnTestPlan(TestPlan plan, TestDescriptor root) { + TestIdentifier rootIdentifier = TestIdentifier.from(root); + plan.add(rootIdentifier); return rootIdentifier; } - private static UniqueId newId() - { - return UniqueId.forEngine( "engine" ); + private static UniqueId newId() { + return UniqueId.forEngine("engine"); } private static final String MY_TEST_METHOD_NAME = "myTestMethod"; private static final String MY_NAMED_TEST_METHOD_NAME = "myNamedTestMethod"; - private static class MyTestClass - { + private static class MyTestClass { @org.junit.jupiter.api.Test - void myTestMethod() - { - } + void myTestMethod() {} @org.junit.jupiter.api.Test - void myTestMethod( String foo ) - { - } + void myTestMethod(String foo) {} - @DisplayName( "name" ) + @DisplayName("name") @org.junit.jupiter.api.Test - void myNamedTestMethod() - { - } + void myNamedTestMethod() {} } - static class TestMethodTestDescriptorWithDisplayName extends AbstractTestDescriptor - { - private TestMethodTestDescriptorWithDisplayName( UniqueId uniqueId, - Class testClass, Method testMethod, String displayName ) - { - super( uniqueId, displayName, MethodSource.from( testClass, testMethod ) ); + static class TestMethodTestDescriptorWithDisplayName extends AbstractTestDescriptor { + private TestMethodTestDescriptorWithDisplayName( + UniqueId uniqueId, Class testClass, Method testMethod, String displayName) { + super(uniqueId, displayName, MethodSource.from(testClass, testMethod)); } @Override - public Type getType() - { + public Type getType() { return Type.TEST; } } diff --git a/surefire-providers/surefire-junit-platform/src/test/java/org/apache/maven/surefire/junitplatform/TestMethodFilterTest.java b/surefire-providers/surefire-junit-platform/src/test/java/org/apache/maven/surefire/junitplatform/TestMethodFilterTest.java index 33f14e9afd..6ef28708b2 100644 --- a/surefire-providers/surefire-junit-platform/src/test/java/org/apache/maven/surefire/junitplatform/TestMethodFilterTest.java +++ b/surefire-providers/surefire-junit-platform/src/test/java/org/apache/maven/surefire/junitplatform/TestMethodFilterTest.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.junitplatform; /* @@ -19,12 +37,6 @@ * under the License. */ -import static org.apache.maven.surefire.api.testset.TestListResolver.toClassFileName; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - import java.lang.reflect.Method; import org.apache.maven.surefire.api.testset.TestListResolver; @@ -35,74 +47,68 @@ import org.junit.platform.engine.FilterResult; import org.junit.platform.engine.UniqueId; +import static org.apache.maven.surefire.api.testset.TestListResolver.toClassFileName; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + /** * Unit tests for {@link TestMethodFilter}. * * @since 2.22.0 */ -public class TestMethodFilterTest -{ - private static final ConfigurationParameters CONFIG_PARAMS = mock( ConfigurationParameters.class ); +public class TestMethodFilterTest { + private static final ConfigurationParameters CONFIG_PARAMS = mock(ConfigurationParameters.class); - private final TestListResolver resolver = mock( TestListResolver.class ); + private final TestListResolver resolver = mock(TestListResolver.class); - private final TestMethodFilter filter = new TestMethodFilter( this.resolver ); + private final TestMethodFilter filter = new TestMethodFilter(this.resolver); @Test - public void includesBasedOnTestListResolver() - throws Exception - { - when( resolver.shouldRun( toClassFileName( TestClass.class ), "testMethod" ) ).thenReturn( true ); + public void includesBasedOnTestListResolver() throws Exception { + when(resolver.shouldRun(toClassFileName(TestClass.class), "testMethod")).thenReturn(true); - FilterResult result = filter.apply( newTestMethodDescriptor() ); + FilterResult result = filter.apply(newTestMethodDescriptor()); - assertTrue( result.included() ); - assertFalse( result.excluded() ); + assertTrue(result.included()); + assertFalse(result.excluded()); } @Test - public void excludesBasedOnTestListResolver() - throws Exception - { - when( resolver.shouldRun( toClassFileName( TestClass.class ), "testMethod" ) ).thenReturn( false ); + public void excludesBasedOnTestListResolver() throws Exception { + when(resolver.shouldRun(toClassFileName(TestClass.class), "testMethod")).thenReturn(false); - FilterResult result = filter.apply( newTestMethodDescriptor() ); + FilterResult result = filter.apply(newTestMethodDescriptor()); - assertFalse( result.included() ); - assertTrue( result.excluded() ); + assertFalse(result.included()); + assertTrue(result.excluded()); } @Test - public void includesTestDescriptorWithClassSource() - { - FilterResult result = filter.apply( newClassTestDescriptor() ); + public void includesTestDescriptorWithClassSource() { + FilterResult result = filter.apply(newClassTestDescriptor()); - assertTrue( result.included() ); - assertFalse( result.excluded() ); + assertTrue(result.included()); + assertFalse(result.excluded()); } - private static TestMethodTestDescriptor newTestMethodDescriptor() - throws Exception - { - UniqueId uniqueId = UniqueId.forEngine( "method" ); + private static TestMethodTestDescriptor newTestMethodDescriptor() throws Exception { + UniqueId uniqueId = UniqueId.forEngine("method"); Class testClass = TestClass.class; - Method testMethod = testClass.getMethod( "testMethod" ); - return new TestMethodTestDescriptor( uniqueId, testClass, testMethod ); + Method testMethod = testClass.getMethod("testMethod"); + return new TestMethodTestDescriptor(uniqueId, testClass, testMethod); } - private static ClassTestDescriptor newClassTestDescriptor() - { - UniqueId uniqueId = UniqueId.forEngine( "class" ); - return new ClassTestDescriptor( uniqueId, TestClass.class, CONFIG_PARAMS ); + private static ClassTestDescriptor newClassTestDescriptor() { + UniqueId uniqueId = UniqueId.forEngine("class"); + return new ClassTestDescriptor(uniqueId, TestClass.class, CONFIG_PARAMS); } /** * */ - public static class TestClass - { - public void testMethod() - { - } + public static class TestClass { + public void testMethod() {} } } diff --git a/surefire-providers/surefire-junit-platform/src/test/java/org/apache/maven/surefire/junitplatform/TestPlanScannerFilterTest.java b/surefire-providers/surefire-junit-platform/src/test/java/org/apache/maven/surefire/junitplatform/TestPlanScannerFilterTest.java index a703a4b457..26428d0f63 100644 --- a/surefire-providers/surefire-junit-platform/src/test/java/org/apache/maven/surefire/junitplatform/TestPlanScannerFilterTest.java +++ b/surefire-providers/surefire-junit-platform/src/test/java/org/apache/maven/surefire/junitplatform/TestPlanScannerFilterTest.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.junitplatform; /* @@ -19,10 +37,6 @@ * under the License. */ -import static java.util.Collections.emptyList; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; - import java.util.List; import java.util.stream.Stream; @@ -33,153 +47,119 @@ import org.junit.platform.engine.Filter; import org.junit.platform.launcher.core.LauncherFactory; +import static java.util.Collections.emptyList; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + /** * Unit tests for {@link TestPlanScannerFilter}. * * @since 2.22.0 */ -public class TestPlanScannerFilterTest -{ +public class TestPlanScannerFilterTest { @Test - public void emptyClassIsNotAccepted() - { - assertFalse( newFilter().accept( EmptyClass.class ), "does not accept empty class" ); + public void emptyClassIsNotAccepted() { + assertFalse(newFilter().accept(EmptyClass.class), "does not accept empty class"); } @Test - public void classWithNoTestMethodsIsNotAccepted() - { - assertFalse( newFilter().accept( ClassWithMethods.class ), "does not accept class with no @Test methods" ); + public void classWithNoTestMethodsIsNotAccepted() { + assertFalse(newFilter().accept(ClassWithMethods.class), "does not accept class with no @Test methods"); } @Test - public void classWithTestMethodsIsAccepted() - { - assertTrue( newFilter().accept( ClassWithTestMethods.class ) ); + public void classWithTestMethodsIsAccepted() { + assertTrue(newFilter().accept(ClassWithTestMethods.class)); } @Test - public void classWithNestedTestClassIsAccepted() - { - assertTrue( newFilter().accept( ClassWithNestedTestClass.class ) ); + public void classWithNestedTestClassIsAccepted() { + assertTrue(newFilter().accept(ClassWithNestedTestClass.class)); } @Test - public void classWithDeeplyNestedTestClassIsAccepted() - { - assertTrue( newFilter().accept( ClassWithDeeplyNestedTestClass.class ) ); + public void classWithDeeplyNestedTestClassIsAccepted() { + assertTrue(newFilter().accept(ClassWithDeeplyNestedTestClass.class)); } @Test - public void classWithTestFactoryIsAccepted() - { - assertTrue( newFilter().accept( ClassWithTestFactory.class ) ); + public void classWithTestFactoryIsAccepted() { + assertTrue(newFilter().accept(ClassWithTestFactory.class)); } @Test - public void classWithNestedTestFactoryIsAccepted() - { - assertTrue( newFilter().accept( ClassWithNestedTestFactory.class ) ); + public void classWithNestedTestFactoryIsAccepted() { + assertTrue(newFilter().accept(ClassWithNestedTestFactory.class)); } - private static TestPlanScannerFilter newFilter() - { - return new TestPlanScannerFilter( LauncherFactory.create(), new Filter[0] ); + private static TestPlanScannerFilter newFilter() { + return new TestPlanScannerFilter(LauncherFactory.create(), new Filter[0]); } - static class EmptyClass - { - } + static class EmptyClass {} - static class ClassWithMethods - { + static class ClassWithMethods { - void method1() - { - } + void method1() {} - void method2() - { - } + void method2() {} } - static class ClassWithTestMethods - { + static class ClassWithTestMethods { @Test - void test1() - { - } + void test1() {} @org.junit.jupiter.api.Test - public void test2() - { - } + public void test2() {} } - static class ClassWithNestedTestClass - { + static class ClassWithNestedTestClass { - void method() - { - } + void method() {} @Nested - class TestClass - { + class TestClass { @org.junit.jupiter.api.Test - void test1() - { - } + void test1() {} } } - static class ClassWithDeeplyNestedTestClass - { + static class ClassWithDeeplyNestedTestClass { @Nested - class Level1 - { + class Level1 { @Nested - class Level2 - { + class Level2 { @Nested - class TestClass - { + class TestClass { @org.junit.jupiter.api.Test - void test1() - { - } + void test1() {} } } } } - static class ClassWithTestFactory - { + static class ClassWithTestFactory { @TestFactory - Stream tests() - { + Stream tests() { return Stream.empty(); } } - static class ClassWithNestedTestFactory - { + static class ClassWithNestedTestFactory { @Nested - class TestClass - { + class TestClass { @TestFactory - List tests() - { + List tests() { return emptyList(); } } diff --git a/surefire-providers/surefire-junit3/pom.xml b/surefire-providers/surefire-junit3/pom.xml index 7fe7c06aee..8d8b0e1829 100644 --- a/surefire-providers/surefire-junit3/pom.xml +++ b/surefire-providers/surefire-junit3/pom.xml @@ -1,3 +1,4 @@ + - 4.0.0 @@ -31,6 +31,10 @@ SureFire JUnit Runner SureFire JUnit3 Runner + + surefire-3.0.0-M8 + + junit @@ -55,6 +59,9 @@ org.jacoco jacoco-maven-plugin + + jacoco.agent + jacoco-agent @@ -63,9 +70,6 @@ - - jacoco.agent - maven-surefire-plugin @@ -76,14 +80,11 @@ org.apache.maven.surefire surefire-shadefire - 3.0.0-M7 + 3.0.0-M7 + - - - surefire-3.0.0-M8 - diff --git a/surefire-providers/surefire-junit3/src/main/java/org/apache/maven/surefire/junit/JUnit3Provider.java b/surefire-providers/surefire-junit3/src/main/java/org/apache/maven/surefire/junit/JUnit3Provider.java index 39d561414d..e018096dc9 100644 --- a/surefire-providers/surefire-junit3/src/main/java/org/apache/maven/surefire/junit/JUnit3Provider.java +++ b/surefire-providers/surefire-junit3/src/main/java/org/apache/maven/surefire/junit/JUnit3Provider.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.junit; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.junit; import java.util.Map; @@ -43,9 +42,7 @@ /** * @author Kristian Rosenvold */ -public class JUnit3Provider - extends AbstractProvider -{ +public class JUnit3Provider extends AbstractProvider { private final ClassLoader testClassLoader; private final PojoAndJUnit3Checker testChecker; @@ -60,111 +57,92 @@ public class JUnit3Provider private final ScanResult scanResult; - public JUnit3Provider( ProviderParameters booterParameters ) - { + public JUnit3Provider(ProviderParameters booterParameters) { this.providerParameters = booterParameters; testClassLoader = booterParameters.getTestClassLoader(); scanResult = booterParameters.getScanResult(); runOrderCalculator = booterParameters.getRunOrderCalculator(); - reflector = new JUnit3Reflector( testClassLoader ); - jUnit3TestChecker = new JUnit3TestChecker( testClassLoader ); - testChecker = new PojoAndJUnit3Checker( jUnit3TestChecker ); // Todo; use reflector + reflector = new JUnit3Reflector(testClassLoader); + jUnit3TestChecker = new JUnit3TestChecker(testClassLoader); + testChecker = new PojoAndJUnit3Checker(jUnit3TestChecker); // Todo; use reflector } @Override - public RunResult invoke( Object forkTestSet ) - throws TestSetFailedException - { + public RunResult invoke(Object forkTestSet) throws TestSetFailedException { ReporterFactory reporterFactory = providerParameters.getReporterFactory(); - JUnit3Reporter reporter = new JUnit3Reporter( reporterFactory.createTestReportListener() ); - reporter.setRunMode( NORMAL_RUN ); - startCapture( reporter ); + JUnit3Reporter reporter = new JUnit3Reporter(reporterFactory.createTestReportListener()); + reporter.setRunMode(NORMAL_RUN); + startCapture(reporter); final TestsToRun testsToRun; - if ( forkTestSet instanceof TestsToRun ) - { + if (forkTestSet instanceof TestsToRun) { testsToRun = (TestsToRun) forkTestSet; - } - else if ( forkTestSet instanceof Class ) - { - testsToRun = TestsToRun.fromClass( (Class) forkTestSet ); - } - else - { + } else if (forkTestSet instanceof Class) { + testsToRun = TestsToRun.fromClass((Class) forkTestSet); + } else { testsToRun = scanClassPath(); } RunResult runResult; - try - { + try { Map systemProperties = systemProps(); - setSystemManager( System.getProperty( "surefire.security.manager" ) ); + setSystemManager(System.getProperty("surefire.security.manager")); - for ( Class clazz : testsToRun ) - { - SurefireTestSetExecutor surefireTestSetExecutor = createTestSet( clazz, reporter ); - executeTestSet( clazz, surefireTestSetExecutor, reporter, systemProperties ); + for (Class clazz : testsToRun) { + SurefireTestSetExecutor surefireTestSetExecutor = createTestSet(clazz, reporter); + executeTestSet(clazz, surefireTestSetExecutor, reporter, systemProperties); } - } - finally - { + } finally { runResult = reporterFactory.close(); } return runResult; } - static void setSystemManager( String smClassName ) throws TestSetFailedException - { - if ( smClassName != null ) - { - if ( !isSecurityManagerSupported() ) - { - throw new TestSetFailedException( "JDK does not support overriding Security Manager with " - + "a value in system property 'surefire.security.manager'." ); + static void setSystemManager(String smClassName) throws TestSetFailedException { + if (smClassName != null) { + if (!isSecurityManagerSupported()) { + throw new TestSetFailedException("JDK does not support overriding Security Manager with " + + "a value in system property 'surefire.security.manager'."); } ClassLoader classLoader = JUnit3Provider.class.getClassLoader(); - SecurityManager sm = instantiate( classLoader, smClassName, SecurityManager.class ); - System.setSecurityManager( sm ); + SecurityManager sm = instantiate(classLoader, smClassName, SecurityManager.class); + System.setSecurityManager(sm); } } - private SurefireTestSetExecutor createTestSet( Class clazz, JUnit3Reporter reporter ) - { - return reflector.isJUnit3Available() && jUnit3TestChecker.accept( clazz ) - ? new JUnitTestSetExecutor( reflector, reporter ) - : new PojoTestSetExecutor( reporter ); + private SurefireTestSetExecutor createTestSet(Class clazz, JUnit3Reporter reporter) { + return reflector.isJUnit3Available() && jUnit3TestChecker.accept(clazz) + ? new JUnitTestSetExecutor(reflector, reporter) + : new PojoTestSetExecutor(reporter); } - private void executeTestSet( Class testSet, SurefireTestSetExecutor testSetExecutor, JUnit3Reporter reporter, - Map systemProperties ) - throws TestSetFailedException - { + private void executeTestSet( + Class testSet, + SurefireTestSetExecutor testSetExecutor, + JUnit3Reporter reporter, + Map systemProperties) + throws TestSetFailedException { String clazz = testSet.getName(); - long testId = reporter.getClassMethodIndexer().indexClass( clazz ); + long testId = reporter.getClassMethodIndexer().indexClass(clazz); - try - { - TestSetReportEntry started = new SimpleReportEntry( NORMAL_RUN, testId, clazz, null, null, null ); - reporter.testSetStarting( started ); - testSetExecutor.execute( testSet, testClassLoader ); - } - finally - { + try { + TestSetReportEntry started = new SimpleReportEntry(NORMAL_RUN, testId, clazz, null, null, null); + reporter.testSetStarting(started); + testSetExecutor.execute(testSet, testClassLoader); + } finally { TestSetReportEntry completed = - new SimpleReportEntry( NORMAL_RUN, testId, clazz, null, null, null, systemProperties ); - reporter.testSetCompleted( completed ); + new SimpleReportEntry(NORMAL_RUN, testId, clazz, null, null, null, systemProperties); + reporter.testSetCompleted(completed); } } - private TestsToRun scanClassPath() - { - TestsToRun testsToRun = scanResult.applyFilter( testChecker, testClassLoader ); - return runOrderCalculator.orderTestClasses( testsToRun ); + private TestsToRun scanClassPath() { + TestsToRun testsToRun = scanResult.applyFilter(testChecker, testClassLoader); + return runOrderCalculator.orderTestClasses(testsToRun); } @Override - public Iterable> getSuites() - { + public Iterable> getSuites() { return scanClassPath(); } } diff --git a/surefire-providers/surefire-junit3/src/main/java/org/apache/maven/surefire/junit/JUnit3Reporter.java b/surefire-providers/surefire-junit3/src/main/java/org/apache/maven/surefire/junit/JUnit3Reporter.java index d9dfe8045e..234ff72b7e 100644 --- a/surefire-providers/surefire-junit3/src/main/java/org/apache/maven/surefire/junit/JUnit3Reporter.java +++ b/surefire-providers/surefire-junit3/src/main/java/org/apache/maven/surefire/junit/JUnit3Reporter.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.junit; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.junit; import org.apache.maven.surefire.api.report.OutputReportEntry; import org.apache.maven.surefire.api.report.ReportEntry; @@ -36,87 +35,72 @@ * delegates the report entry to the {@link TestReportListener}. * This object necessarily requires setting the {@link RunMode} in order to behave properly. */ -final class JUnit3Reporter - implements RunListener, TestOutputReceiver, RunModeSetter -{ +final class JUnit3Reporter implements RunListener, TestOutputReceiver, RunModeSetter { private final ClassMethodIndexer classMethodIndexer = new ClassMethodIndexer(); private final TestReportListener reporter; private volatile RunMode runMode; - JUnit3Reporter( TestReportListener reporter ) - { + JUnit3Reporter(TestReportListener reporter) { this.reporter = reporter; } - ClassMethodIndexer getClassMethodIndexer() - { + ClassMethodIndexer getClassMethodIndexer() { return classMethodIndexer; } @Override - public void setRunMode( RunMode runMode ) - { + public void setRunMode(RunMode runMode) { this.runMode = runMode; } @Override - public void testSetStarting( TestSetReportEntry report ) - { - reporter.testSetStarting( report ); + public void testSetStarting(TestSetReportEntry report) { + reporter.testSetStarting(report); } @Override - public void testSetCompleted( TestSetReportEntry report ) - { - reporter.testSetCompleted( report ); + public void testSetCompleted(TestSetReportEntry report) { + reporter.testSetCompleted(report); } @Override - public void testStarting( ReportEntry report ) - { - reporter.testStarting( report ); + public void testStarting(ReportEntry report) { + reporter.testStarting(report); } @Override - public void testSucceeded( ReportEntry report ) - { - reporter.testSucceeded( report ); + public void testSucceeded(ReportEntry report) { + reporter.testSucceeded(report); } @Override - public void testAssumptionFailure( ReportEntry report ) - { - reporter.testAssumptionFailure( report ); + public void testAssumptionFailure(ReportEntry report) { + reporter.testAssumptionFailure(report); } @Override - public void testError( ReportEntry report ) - { - reporter.testError( report ); + public void testError(ReportEntry report) { + reporter.testError(report); } @Override - public void testFailed( ReportEntry report ) - { - reporter.testFailed( report ); + public void testFailed(ReportEntry report) { + reporter.testFailed(report); } @Override - public void testSkipped( ReportEntry report ) - { - reporter.testSkipped( report ); + public void testSkipped(ReportEntry report) { + reporter.testSkipped(report); } @Override - public void testExecutionSkippedByUser() - { + public void testExecutionSkippedByUser() { reporter.testExecutionSkippedByUser(); } @Override - public void writeTestOutput( OutputReportEntry reportEntry ) - { + public void writeTestOutput(OutputReportEntry reportEntry) { Long testRunId = classMethodIndexer.getLocalIndex(); - reporter.writeTestOutput( new TestOutputReportEntry( reportEntry, runMode, testRunId ) ); + reporter.writeTestOutput(new TestOutputReportEntry(reportEntry, runMode, testRunId)); } } diff --git a/surefire-providers/surefire-junit3/src/main/java/org/apache/maven/surefire/junit/JUnitTestSetExecutor.java b/surefire-providers/surefire-junit3/src/main/java/org/apache/maven/surefire/junit/JUnitTestSetExecutor.java index 3772e2a837..2d113d385d 100644 --- a/surefire-providers/surefire-junit3/src/main/java/org/apache/maven/surefire/junit/JUnitTestSetExecutor.java +++ b/surefire-providers/surefire-junit3/src/main/java/org/apache/maven/surefire/junit/JUnitTestSetExecutor.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.junit; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.junit; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; @@ -30,15 +29,12 @@ * JUnit3 test set * */ -public final class JUnitTestSetExecutor - implements SurefireTestSetExecutor -{ +public final class JUnitTestSetExecutor implements SurefireTestSetExecutor { private final JUnit3Reflector reflector; private final JUnit3Reporter reporter; - public JUnitTestSetExecutor( JUnit3Reflector reflector, JUnit3Reporter reporter ) - { + public JUnitTestSetExecutor(JUnit3Reflector reflector, JUnit3Reporter reporter) { this.reflector = reflector; this.reporter = reporter; @@ -58,49 +54,37 @@ public JUnitTestSetExecutor( JUnit3Reflector reflector, JUnit3Reporter reporter } @Override - public void execute( Class testClass, ClassLoader loader ) - throws TestSetFailedException - { - try - { - Object testObject = reflector.constructTestObject( testClass ); + public void execute(Class testClass, ClassLoader loader) throws TestSetFailedException { + try { + Object testObject = reflector.constructTestObject(testClass); final Method runMethod; - if ( reflector.getTestInterface().isAssignableFrom( testObject.getClass() ) ) - { + if (reflector.getTestInterface().isAssignableFrom(testObject.getClass())) { runMethod = reflector.getTestInterfaceRunMethod(); - } - else - { - runMethod = reflector.getRunMethod( testClass ); + } else { + runMethod = reflector.getRunMethod(testClass); } Object instanceOfTestResult = reflector.getTestResultClass().newInstance(); - TestListenerInvocationHandler invocationHandler = new TestListenerInvocationHandler( reporter ); + TestListenerInvocationHandler invocationHandler = new TestListenerInvocationHandler(reporter); - Object testListener = - Proxy.newProxyInstance( loader, reflector.getInterfacesImplementedByDynamicProxy(), invocationHandler ); + Object testListener = Proxy.newProxyInstance( + loader, reflector.getInterfacesImplementedByDynamicProxy(), invocationHandler); - Object[] addTestListenerParams = { testListener }; + Object[] addTestListenerParams = {testListener}; - reflector.getAddListenerMethod().invoke( instanceOfTestResult, addTestListenerParams ); + reflector.getAddListenerMethod().invoke(instanceOfTestResult, addTestListenerParams); - Object[] runParams = { instanceOfTestResult }; + Object[] runParams = {instanceOfTestResult}; - runMethod.invoke( testObject, runParams ); - } - catch ( InvocationTargetException e ) - { - throw new TestSetFailedException( testClass.getName(), e.getTargetException() ); - } - catch ( NoSuchMethodException e ) - { - throw new TestSetFailedException( "Class is not a JUnit TestCase", e ); - } - catch ( ReflectiveOperationException e ) - { - throw new TestSetFailedException( testClass.getName(), e ); + runMethod.invoke(testObject, runParams); + } catch (InvocationTargetException e) { + throw new TestSetFailedException(testClass.getName(), e.getTargetException()); + } catch (NoSuchMethodException e) { + throw new TestSetFailedException("Class is not a JUnit TestCase", e); + } catch (ReflectiveOperationException e) { + throw new TestSetFailedException(testClass.getName(), e); } } } diff --git a/surefire-providers/surefire-junit3/src/main/java/org/apache/maven/surefire/junit/PojoAndJUnit3Checker.java b/surefire-providers/surefire-junit3/src/main/java/org/apache/maven/surefire/junit/PojoAndJUnit3Checker.java index 021a57627f..6f7fa1009c 100644 --- a/surefire-providers/surefire-junit3/src/main/java/org/apache/maven/surefire/junit/PojoAndJUnit3Checker.java +++ b/surefire-providers/surefire-junit3/src/main/java/org/apache/maven/surefire/junit/PojoAndJUnit3Checker.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.junit; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,44 +16,35 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.junit; import org.apache.maven.surefire.api.filter.NonAbstractClassFilter; -import org.apache.maven.surefire.common.junit3.JUnit3TestChecker; import org.apache.maven.surefire.api.util.ScannerFilter; +import org.apache.maven.surefire.common.junit3.JUnit3TestChecker; /** * @author Kristian Rosenvold */ -public class PojoAndJUnit3Checker - implements ScannerFilter -{ +public class PojoAndJUnit3Checker implements ScannerFilter { private final JUnit3TestChecker jUnit3TestChecker; private final NonAbstractClassFilter nonAbstractClassFilter = new NonAbstractClassFilter(); - public PojoAndJUnit3Checker( JUnit3TestChecker jUnit3TestChecker ) - { + public PojoAndJUnit3Checker(JUnit3TestChecker jUnit3TestChecker) { this.jUnit3TestChecker = jUnit3TestChecker; } @Override - public boolean accept( Class testClass ) - { - return jUnit3TestChecker.accept( testClass ) - || nonAbstractClassFilter.accept( testClass ) && isPojoTest( testClass ); + public boolean accept(Class testClass) { + return jUnit3TestChecker.accept(testClass) || nonAbstractClassFilter.accept(testClass) && isPojoTest(testClass); } - private boolean isPojoTest( Class testClass ) - { - try - { + private boolean isPojoTest(Class testClass) { + try { testClass.getConstructor(); return true; - } - catch ( Exception e ) - { + } catch (Exception e) { return false; } } - } diff --git a/surefire-providers/surefire-junit3/src/main/java/org/apache/maven/surefire/junit/PojoTestSetExecutor.java b/surefire-providers/surefire-junit3/src/main/java/org/apache/maven/surefire/junit/PojoTestSetExecutor.java index 45ca779846..f9769aea35 100644 --- a/surefire-providers/surefire-junit3/src/main/java/org/apache/maven/surefire/junit/PojoTestSetExecutor.java +++ b/surefire-providers/surefire-junit3/src/main/java/org/apache/maven/surefire/junit/PojoTestSetExecutor.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.junit; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.junit; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; @@ -39,9 +38,7 @@ * Executes a JUnit3 test class * */ -public class PojoTestSetExecutor - implements SurefireTestSetExecutor -{ +public class PojoTestSetExecutor implements SurefireTestSetExecutor { private static final String TEST_METHOD_PREFIX = "test"; private static final String SETUP_METHOD_NAME = "setUp"; @@ -52,60 +49,47 @@ public class PojoTestSetExecutor private final JUnit3Reporter reporter; - public PojoTestSetExecutor( JUnit3Reporter reporter ) - { - this.reporter = requireNonNull( reporter, "reportManager is null" ); + public PojoTestSetExecutor(JUnit3Reporter reporter) { + this.reporter = requireNonNull(reporter, "reportManager is null"); } @Override - public void execute( Class testClass, ClassLoader loader ) - throws TestSetFailedException - { - DiscoveredTestMethods discoveredTestMethods = discoverTestMethods( requireNonNull( testClass ) ); + public void execute(Class testClass, ClassLoader loader) throws TestSetFailedException { + DiscoveredTestMethods discoveredTestMethods = discoverTestMethods(requireNonNull(testClass)); - for ( Method testMethod : discoveredTestMethods.testMethods ) - { + for (Method testMethod : discoveredTestMethods.testMethods) { ClassMethodIndexer indexer = reporter.getClassMethodIndexer(); - long testRunId = indexer.indexClassMethod( testClass.getName(), testMethod.getName() ); - boolean abort = executeTestMethod( testClass, testMethod, testRunId, discoveredTestMethods ); - if ( abort ) - { + long testRunId = indexer.indexClassMethod(testClass.getName(), testMethod.getName()); + boolean abort = executeTestMethod(testClass, testMethod, testRunId, discoveredTestMethods); + if (abort) { break; } } } - private boolean executeTestMethod( Class testClass, Method method, long testRunId, - DiscoveredTestMethods methods ) - throws TestSetFailedException - { + private boolean executeTestMethod(Class testClass, Method method, long testRunId, DiscoveredTestMethods methods) + throws TestSetFailedException { final Object testObject; - try - { + try { testObject = testClass.getDeclaredConstructor().newInstance(); - } - catch ( ReflectiveOperationException e ) - { - throw new TestSetFailedException( "Unable to instantiate POJO '" + testClass + "'.", e ); + } catch (ReflectiveOperationException e) { + throw new TestSetFailedException("Unable to instantiate POJO '" + testClass + "'.", e); } final String testClassName = testClass.getName(); final String methodName = method.getName(); final String userFriendlyMethodName = methodName + "()"; - final String testName = getTestName( testClassName, userFriendlyMethodName ); + final String testName = getTestName(testClassName, userFriendlyMethodName); - reporter.testStarting( new SimpleReportEntry( NORMAL_RUN, testRunId, testClassName, null, testName, null ) ); + reporter.testStarting(new SimpleReportEntry(NORMAL_RUN, testRunId, testClassName, null, testName, null)); - try - { - setUpFixture( testObject, methods ); - } - catch ( Throwable e ) - { - StackTraceWriter stackTraceWriter = new LegacyPojoStackTraceWriter( testClassName, methodName, e ); + try { + setUpFixture(testObject, methods); + } catch (Throwable e) { + StackTraceWriter stackTraceWriter = new LegacyPojoStackTraceWriter(testClassName, methodName, e); reporter.testFailed( - withException( NORMAL_RUN, testRunId, testClassName, null, testName, null, stackTraceWriter ) ); + withException(NORMAL_RUN, testRunId, testClassName, null, testName, null, stackTraceWriter)); // A return value of true indicates to this class's executeTestMethods // method that it should abort and not attempt to execute @@ -116,40 +100,31 @@ private boolean executeTestMethod( Class testClass, Method method, long testR } // Make sure that tearDownFixture - try - { - method.invoke( testObject, EMPTY_OBJECT_ARRAY ); - reporter.testSucceeded( - new SimpleReportEntry( NORMAL_RUN, testRunId, testClassName, null, testName, null ) ); - } - catch ( InvocationTargetException e ) - { + try { + method.invoke(testObject, EMPTY_OBJECT_ARRAY); + reporter.testSucceeded(new SimpleReportEntry(NORMAL_RUN, testRunId, testClassName, null, testName, null)); + } catch (InvocationTargetException e) { Throwable t = e.getTargetException(); - StackTraceWriter stackTraceWriter = new LegacyPojoStackTraceWriter( testClassName, methodName, t ); + StackTraceWriter stackTraceWriter = new LegacyPojoStackTraceWriter(testClassName, methodName, t); reporter.testFailed( - withException( NORMAL_RUN, testRunId, testClassName, null, testName, null, stackTraceWriter ) ); + withException(NORMAL_RUN, testRunId, testClassName, null, testName, null, stackTraceWriter)); // Don't return here, because tearDownFixture should be called even // if the test method throws an exception. - } - catch ( Throwable t ) - { - StackTraceWriter stackTraceWriter = new LegacyPojoStackTraceWriter( testClassName, methodName, t ); + } catch (Throwable t) { + StackTraceWriter stackTraceWriter = new LegacyPojoStackTraceWriter(testClassName, methodName, t); reporter.testFailed( - withException( NORMAL_RUN, testRunId, testClassName, null, testName, null, stackTraceWriter ) ); + withException(NORMAL_RUN, testRunId, testClassName, null, testName, null, stackTraceWriter)); // Don't return here, because tearDownFixture should be called even // if the test method throws an exception. } - try - { - tearDownFixture( testObject, methods ); - } - catch ( Throwable t ) - { - StackTraceWriter stackTraceWriter = new LegacyPojoStackTraceWriter( testClassName, methodName, t ); + try { + tearDownFixture(testObject, methods); + } catch (Throwable t) { + StackTraceWriter stackTraceWriter = new LegacyPojoStackTraceWriter(testClassName, methodName, t); // Treat any exception from tearDownFixture as a failure of the test. reporter.testFailed( - withException( NORMAL_RUN, testRunId, testClassName, null, testName, null, stackTraceWriter ) ); + withException(NORMAL_RUN, testRunId, testClassName, null, testName, null, stackTraceWriter)); // A return value of true indicates to this class's executeTestMethods // method that it should abort and not attempt to execute @@ -167,46 +142,31 @@ private boolean executeTestMethod( Class testClass, Method method, long testR return false; } - private String getTestName( String testClassName, String testMethodName ) - { - return testClassName + "." + requireNonNull( testMethodName, "testMethodName is null" ); + private String getTestName(String testClassName, String testMethodName) { + return testClassName + "." + requireNonNull(testMethodName, "testMethodName is null"); } - private void setUpFixture( Object testObject, DiscoveredTestMethods methods ) - throws Throwable - { - if ( methods.setUpMethod != null ) - { - methods.setUpMethod.invoke( testObject ); + private void setUpFixture(Object testObject, DiscoveredTestMethods methods) throws Throwable { + if (methods.setUpMethod != null) { + methods.setUpMethod.invoke(testObject); } } - private void tearDownFixture( Object testObject, DiscoveredTestMethods methods ) - throws Throwable - { - if ( methods.tearDownMethod != null ) - { - methods.tearDownMethod.invoke( testObject ); + private void tearDownFixture(Object testObject, DiscoveredTestMethods methods) throws Throwable { + if (methods.tearDownMethod != null) { + methods.tearDownMethod.invoke(testObject); } } - private DiscoveredTestMethods discoverTestMethods( Class testClass ) - { + private DiscoveredTestMethods discoverTestMethods(Class testClass) { DiscoveredTestMethods methods = new DiscoveredTestMethods(); - for ( Method m : testClass.getMethods() ) - { - if ( isNoArgsInstanceMethod( m ) ) - { - if ( isValidTestMethod( m ) ) - { - methods.testMethods.add( m ); - } - else if ( SETUP_METHOD_NAME.equals( m.getName() ) ) - { + for (Method m : testClass.getMethods()) { + if (isNoArgsInstanceMethod(m)) { + if (isValidTestMethod(m)) { + methods.testMethods.add(m); + } else if (SETUP_METHOD_NAME.equals(m.getName())) { methods.setUpMethod = m; - } - else if ( TEARDOWN_METHOD_NAME.equals( m.getName() ) ) - { + } else if (TEARDOWN_METHOD_NAME.equals(m.getName())) { methods.tearDownMethod = m; } } @@ -214,21 +174,18 @@ else if ( TEARDOWN_METHOD_NAME.equals( m.getName() ) ) return methods; } - private static boolean isNoArgsInstanceMethod( Method m ) - { - boolean isInstanceMethod = !Modifier.isStatic( m.getModifiers() ); - boolean returnsVoid = m.getReturnType().equals( void.class ); + private static boolean isNoArgsInstanceMethod(Method m) { + boolean isInstanceMethod = !Modifier.isStatic(m.getModifiers()); + boolean returnsVoid = m.getReturnType().equals(void.class); boolean hasNoParams = m.getParameterTypes().length == 0; return isInstanceMethod && returnsVoid && hasNoParams; } - private static boolean isValidTestMethod( Method m ) - { - return m.getName().startsWith( TEST_METHOD_PREFIX ); + private static boolean isValidTestMethod(Method m) { + return m.getName().startsWith(TEST_METHOD_PREFIX); } - private static class DiscoveredTestMethods - { + private static class DiscoveredTestMethods { final Collection testMethods = new ArrayList<>(); Method setUpMethod; Method tearDownMethod; diff --git a/surefire-providers/surefire-junit3/src/main/java/org/apache/maven/surefire/junit/SurefireTestSetExecutor.java b/surefire-providers/surefire-junit3/src/main/java/org/apache/maven/surefire/junit/SurefireTestSetExecutor.java index 1b5bb71771..6379c6ae12 100644 --- a/surefire-providers/surefire-junit3/src/main/java/org/apache/maven/surefire/junit/SurefireTestSetExecutor.java +++ b/surefire-providers/surefire-junit3/src/main/java/org/apache/maven/surefire/junit/SurefireTestSetExecutor.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.junit; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.junit; import org.apache.maven.surefire.api.testset.TestSetFailedException; @@ -25,8 +24,6 @@ * Describes a single test set * */ -public interface SurefireTestSetExecutor -{ - void execute( Class testClass, ClassLoader loader ) - throws TestSetFailedException; +public interface SurefireTestSetExecutor { + void execute(Class testClass, ClassLoader loader) throws TestSetFailedException; } diff --git a/surefire-providers/surefire-junit3/src/main/java/org/apache/maven/surefire/junit/TestListenerInvocationHandler.java b/surefire-providers/surefire-junit3/src/main/java/org/apache/maven/surefire/junit/TestListenerInvocationHandler.java index b5cf55ccb8..083d076f33 100644 --- a/surefire-providers/surefire-junit3/src/main/java/org/apache/maven/surefire/junit/TestListenerInvocationHandler.java +++ b/surefire-providers/surefire-junit3/src/main/java/org/apache/maven/surefire/junit/TestListenerInvocationHandler.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.junit; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.junit; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; @@ -40,9 +39,7 @@ * Invocation Handler for TestListener proxies to delegate to our {@link RunListener} * */ -public class TestListenerInvocationHandler - implements InvocationHandler -{ +public class TestListenerInvocationHandler implements InvocationHandler { // The String names of the four methods in interface junit.framework.TestListener private static final String START_TEST = "startTest"; @@ -56,43 +53,32 @@ public class TestListenerInvocationHandler private final JUnit3Reporter reporter; - private static final Class[] EMPTY_CLASS_ARRAY = { }; + private static final Class[] EMPTY_CLASS_ARRAY = {}; - private static final Object[] EMPTY_STRING_ARRAY = { }; + private static final Object[] EMPTY_STRING_ARRAY = {}; - private static class FailedTest - { + private static class FailedTest { private final Object testThatFailed; private final Thread threadOnWhichTestFailed; - FailedTest( Object testThatFailed, Thread threadOnWhichTestFailed ) - { - this.testThatFailed = - requireNonNull( testThatFailed, "testThatFailed is null" ); + FailedTest(Object testThatFailed, Thread threadOnWhichTestFailed) { + this.testThatFailed = requireNonNull(testThatFailed, "testThatFailed is null"); - this.threadOnWhichTestFailed = - requireNonNull( threadOnWhichTestFailed, "threadOnWhichTestFailed is null" ); + this.threadOnWhichTestFailed = requireNonNull(threadOnWhichTestFailed, "threadOnWhichTestFailed is null"); } @Override - public boolean equals( Object obj ) - { + public boolean equals(Object obj) { boolean retVal = true; - if ( obj == null || getClass() != obj.getClass() ) - { + if (obj == null || getClass() != obj.getClass()) { retVal = false; - } - else - { + } else { FailedTest ft = (FailedTest) obj; - if ( ft.testThatFailed != testThatFailed ) - { + if (ft.testThatFailed != testThatFailed) { retVal = false; - } - else if ( !ft.threadOnWhichTestFailed.equals( threadOnWhichTestFailed ) ) - { + } else if (!ft.threadOnWhichTestFailed.equals(threadOnWhichTestFailed)) { retVal = false; } } @@ -101,36 +87,31 @@ else if ( !ft.threadOnWhichTestFailed.equals( threadOnWhichTestFailed ) ) } @Override - public int hashCode() - { + public int hashCode() { return threadOnWhichTestFailed.hashCode(); } } - public TestListenerInvocationHandler( JUnit3Reporter reporter ) - { - this.reporter = requireNonNull( reporter, "reporter is null" ); + public TestListenerInvocationHandler(JUnit3Reporter reporter) { + this.reporter = requireNonNull(reporter, "reporter is null"); } @Override - public Object invoke( Object proxy, Method method, Object[] args ) - throws Throwable - { + public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { String methodName = method.getName(); - switch ( methodName ) - { + switch (methodName) { case START_TEST: - handleStartTest( args ); + handleStartTest(args); break; case ADD_ERROR: - handleAddError( args ); + handleAddError(args); break; case ADD_FAILURE: - handleAddFailure( args ); + handleAddFailure(args); break; case END_TEST: - handleEndTest( args ); + handleEndTest(args); break; default: break; @@ -140,81 +121,66 @@ public Object invoke( Object proxy, Method method, Object[] args ) } // Handler for TestListener.startTest(Test) - private void handleStartTest( Object[] args ) - { - ReportEntry report = createStartEndReportEntry( args ); + private void handleStartTest(Object[] args) { + ReportEntry report = createStartEndReportEntry(args); - reporter.testStarting( report ); + reporter.testStarting(report); } // Handler for TestListener.addFailure(Test, Throwable) - private void handleAddError( Object[] args ) - throws ReflectiveOperationException - { - ReportEntry report = toReportEntryWithException( args ); + private void handleAddError(Object[] args) throws ReflectiveOperationException { + ReportEntry report = toReportEntryWithException(args); - reporter.testError( report ); + reporter.testError(report); - failedTestsSet.add( new FailedTest( args[0], Thread.currentThread() ) ); + failedTestsSet.add(new FailedTest(args[0], Thread.currentThread())); } - private static LegacyPojoStackTraceWriter toStackTraceWriter( Object[] args ) - throws ReflectiveOperationException - { + private static LegacyPojoStackTraceWriter toStackTraceWriter(Object[] args) throws ReflectiveOperationException { String testName; - try - { - Method m = args[0].getClass().getMethod( "getName", EMPTY_CLASS_ARRAY ); - testName = (String) m.invoke( args[0], EMPTY_STRING_ARRAY ); - } - catch ( NoSuchMethodException e ) - { + try { + Method m = args[0].getClass().getMethod("getName", EMPTY_CLASS_ARRAY); + testName = (String) m.invoke(args[0], EMPTY_STRING_ARRAY); + } catch (NoSuchMethodException e) { testName = "UNKNOWN"; } - return new LegacyPojoStackTraceWriter( args[0].getClass().getName(), testName, (Throwable) args[1] ); + return new LegacyPojoStackTraceWriter(args[0].getClass().getName(), testName, (Throwable) args[1]); } - private void handleAddFailure( Object[] args ) - throws ReflectiveOperationException - { - ReportEntry report = toReportEntryWithException( args ); + private void handleAddFailure(Object[] args) throws ReflectiveOperationException { + ReportEntry report = toReportEntryWithException(args); - reporter.testFailed( report ); + reporter.testFailed(report); - failedTestsSet.add( new FailedTest( args[0], Thread.currentThread() ) ); + failedTestsSet.add(new FailedTest(args[0], Thread.currentThread())); } - private void handleEndTest( Object[] args ) - { - boolean testHadFailed = failedTestsSet.remove( new FailedTest( args[0], Thread.currentThread() ) ); + private void handleEndTest(Object[] args) { + boolean testHadFailed = failedTestsSet.remove(new FailedTest(args[0], Thread.currentThread())); - if ( !testHadFailed ) - { - ReportEntry report = createStartEndReportEntry( args ); + if (!testHadFailed) { + ReportEntry report = createStartEndReportEntry(args); - reporter.testSucceeded( report ); + reporter.testSucceeded(report); } } - private ReportEntry toReportEntryWithException( Object[] args ) - throws ReflectiveOperationException - { + private ReportEntry toReportEntryWithException(Object[] args) throws ReflectiveOperationException { String description = args[0].toString(); - String className = extractClassName( description ); - String methodName = extractMethodName( description ); - StackTraceWriter stackTraceWriter = toStackTraceWriter( args ); - long testRunId = reporter.getClassMethodIndexer().indexClassMethod( className, methodName ); - return withException( NORMAL_RUN, testRunId, className, null, methodName, null, stackTraceWriter ); + String className = extractClassName(description); + String methodName = extractMethodName(description); + StackTraceWriter stackTraceWriter = toStackTraceWriter(args); + long testRunId = reporter.getClassMethodIndexer().indexClassMethod(className, methodName); + return withException(NORMAL_RUN, testRunId, className, null, methodName, null, stackTraceWriter); } - private SimpleReportEntry createStartEndReportEntry( Object[] args ) - { + private SimpleReportEntry createStartEndReportEntry(Object[] args) { String description = args[0].toString(); - String className = extractClassName( description ); - String methodName = extractMethodName( description ); - long testRunId = reporter.getClassMethodIndexer().indexClassMethod( className, methodName ); - return new SimpleReportEntry( NORMAL_RUN, testRunId, className, null, methodName, null ); + String className = extractClassName(description); + String methodName = extractMethodName(description); + long testRunId = reporter.getClassMethodIndexer().indexClassMethod(className, methodName); + return new SimpleReportEntry(NORMAL_RUN, testRunId, className, null, methodName, null); } } diff --git a/surefire-providers/surefire-junit3/src/test/java/org/apache/maven/surefire/junit/JUnitTestSetTest.java b/surefire-providers/surefire-junit3/src/test/java/org/apache/maven/surefire/junit/JUnitTestSetTest.java index 417511a722..35979a1ecf 100644 --- a/surefire-providers/surefire-junit3/src/test/java/org/apache/maven/surefire/junit/JUnitTestSetTest.java +++ b/surefire-providers/surefire-junit3/src/test/java/org/apache/maven/surefire/junit/JUnitTestSetTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.junit; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,23 +16,24 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.junit; + +import java.security.AccessControlException; +import java.security.AccessController; +import java.security.PrivilegedAction; +import java.util.ArrayList; +import java.util.List; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; +import org.apache.maven.surefire.api.report.ReportEntry; +import org.apache.maven.surefire.api.report.RunListener; import org.apache.maven.surefire.api.report.TestOutputReportEntry; import org.apache.maven.surefire.api.report.TestReportListener; +import org.apache.maven.surefire.api.report.TestSetReportEntry; import org.apache.maven.surefire.api.testset.TestSetFailedException; import org.apache.maven.surefire.common.junit3.JUnit3Reflector; -import org.apache.maven.surefire.api.report.ReportEntry; -import org.apache.maven.surefire.api.report.RunListener; -import org.apache.maven.surefire.api.report.TestSetReportEntry; - -import java.security.AccessControlException; -import java.security.AccessController; -import java.security.PrivilegedAction; -import java.util.ArrayList; -import java.util.List; import static org.apache.maven.surefire.shared.lang3.JavaVersion.JAVA_17; import static org.apache.maven.surefire.shared.lang3.JavaVersion.JAVA_RECENT; @@ -42,72 +41,54 @@ /** * */ -public class JUnitTestSetTest - extends TestCase -{ +public class JUnitTestSetTest extends TestCase { - public void testExecuteSuiteClass() - throws Exception - { + public void testExecuteSuiteClass() throws Exception { ClassLoader testClassLoader = this.getClass().getClassLoader(); - JUnit3Reflector reflector = new JUnit3Reflector( testClassLoader ); + JUnit3Reflector reflector = new JUnit3Reflector(testClassLoader); SuccessListener listener = new SuccessListener(); - JUnit3Reporter reporter = new JUnit3Reporter( listener ); - JUnitTestSetExecutor testSet = new JUnitTestSetExecutor( reflector, reporter ); - testSet.execute( Suite.class, testClassLoader ); + JUnit3Reporter reporter = new JUnit3Reporter(listener); + JUnitTestSetExecutor testSet = new JUnitTestSetExecutor(reflector, reporter); + testSet.execute(Suite.class, testClassLoader); List succeededTests = listener.getSucceededTests(); - assertEquals( 1, succeededTests.size() ); - assertEquals( "org.apache.maven.surefire.junit.JUnitTestSetTest$AlwaysSucceeds", - succeededTests.get( 0 ).getSourceName() ); - assertEquals( "testSuccess", - succeededTests.get( 0 ).getName() ); + assertEquals(1, succeededTests.size()); + assertEquals( + "org.apache.maven.surefire.junit.JUnitTestSetTest$AlwaysSucceeds", + succeededTests.get(0).getSourceName()); + assertEquals("testSuccess", succeededTests.get(0).getName()); } - public void testSystemManager() - { - boolean isDeprecated = !JAVA_RECENT.atMost( JAVA_17 ); + public void testSystemManager() { + boolean isDeprecated = !JAVA_RECENT.atMost(JAVA_17); Object originalSm = null; - try - { - if ( !isDeprecated ) - { + try { + if (!isDeprecated) { originalSm = System.getSecurityManager(); } - JUnit3Provider.setSystemManager( "java.lang.SecurityManager" ); + JUnit3Provider.setSystemManager("java.lang.SecurityManager"); - if ( isDeprecated ) - { + if (isDeprecated) { fail(); } Object sm = System.getSecurityManager(); - assertNotNull( sm ); - assertEquals( "java.lang.SecurityManager", sm.getClass().getName() ); - assertNotSame( originalSm, sm ); - } - catch ( TestSetFailedException e ) - { - if ( !isDeprecated ) - { + assertNotNull(sm); + assertEquals("java.lang.SecurityManager", sm.getClass().getName()); + assertNotSame(originalSm, sm); + } catch (TestSetFailedException e) { + if (!isDeprecated) { fail(); } - } - finally - { - if ( !isDeprecated ) - { - try - { + } finally { + if (!isDeprecated) { + try { SecurityManager sm = (SecurityManager) originalSm; - AccessController.doPrivileged( (PrivilegedAction) () -> - { - System.setSecurityManager( sm ); + AccessController.doPrivileged((PrivilegedAction) () -> { + System.setSecurityManager(sm); return null; - } ); - } - catch ( AccessControlException e ) - { + }); + } catch (AccessControlException e) { // ignore } } @@ -117,156 +98,110 @@ public void testSystemManager() /** * */ - public static final class AlwaysSucceeds - extends TestCase - { - public void testSuccess() - { - assertTrue( true ); + public static final class AlwaysSucceeds extends TestCase { + public void testSuccess() { + assertTrue(true); } } /** * */ - public static class SuccessListener - implements RunListener, TestReportListener - { + public static class SuccessListener implements RunListener, TestReportListener { private List succeededTests = new ArrayList<>(); @Override - public void testSetStarting( TestSetReportEntry report ) - { - } + public void testSetStarting(TestSetReportEntry report) {} @Override - public void testSetCompleted( TestSetReportEntry report ) - { - } + public void testSetCompleted(TestSetReportEntry report) {} @Override - public void testStarting( ReportEntry report ) - { - } + public void testStarting(ReportEntry report) {} @Override - public void testSucceeded( ReportEntry report ) - { - succeededTests.add( report ); + public void testSucceeded(ReportEntry report) { + succeededTests.add(report); } @Override - public void testAssumptionFailure( ReportEntry report ) - { + public void testAssumptionFailure(ReportEntry report) { throw new IllegalStateException(); } @Override - public void testError( ReportEntry report ) - { + public void testError(ReportEntry report) { throw new IllegalStateException(); } @Override - public void testFailed( ReportEntry report ) - { + public void testFailed(ReportEntry report) { throw new IllegalStateException(); } @Override - public void testSkipped( ReportEntry report ) - { + public void testSkipped(ReportEntry report) { throw new IllegalStateException(); } @Override - public void testExecutionSkippedByUser() - { - } + public void testExecutionSkippedByUser() {} - List getSucceededTests() - { + List getSucceededTests() { return succeededTests; } @Override - public void writeTestOutput( TestOutputReportEntry reportEntry ) - { - - } + public void writeTestOutput(TestOutputReportEntry reportEntry) {} @Override - public boolean isDebugEnabled() - { + public boolean isDebugEnabled() { return false; } @Override - public void debug( String message ) - { - - } + public void debug(String message) {} @Override - public boolean isInfoEnabled() - { + public boolean isInfoEnabled() { return false; } @Override - public void info( String message ) - { - - } + public void info(String message) {} @Override - public boolean isWarnEnabled() - { + public boolean isWarnEnabled() { return false; } @Override - public void warning( String message ) - { - - } + public void warning(String message) {} @Override - public boolean isErrorEnabled() - { + public boolean isErrorEnabled() { return false; } @Override - public void error( String message ) - { - - } + public void error(String message) {} @Override - public void error( String message, Throwable t ) - { - - } + public void error(String message, Throwable t) {} @Override - public void error( Throwable t ) - { - - } + public void error(Throwable t) {} } /** * */ - public static class Suite - { + public static class Suite { - public static Test suite() - { + public static Test suite() { TestSuite suite = new TestSuite(); - suite.addTestSuite( AlwaysSucceeds.class ); + suite.addTestSuite(AlwaysSucceeds.class); return suite; } } diff --git a/surefire-providers/surefire-junit4/pom.xml b/surefire-providers/surefire-junit4/pom.xml index 7b6a27901e..0f09949314 100644 --- a/surefire-providers/surefire-junit4/pom.xml +++ b/surefire-providers/surefire-junit4/pom.xml @@ -1,3 +1,4 @@ + - 4.0.0 @@ -31,6 +31,10 @@ SureFire JUnit4 Runner SureFire JUnit 4.0+ Runner + + surefire-3.0.0-M8 + + junit @@ -50,6 +54,9 @@ org.jacoco jacoco-maven-plugin + + jacoco.agent + jacoco-agent @@ -58,9 +65,6 @@ - - jacoco.agent - maven-surefire-plugin @@ -74,14 +78,11 @@ org.apache.maven.surefire surefire-shadefire - 3.0.0-M7 + 3.0.0-M7 + - - - surefire-3.0.0-M8 - diff --git a/surefire-providers/surefire-junit4/src/main/java/org/apache/maven/surefire/junit4/JUnit4Provider.java b/surefire-providers/surefire-junit4/src/main/java/org/apache/maven/surefire/junit4/JUnit4Provider.java index 5c38caa70d..2668290e9a 100644 --- a/surefire-providers/surefire-junit4/src/main/java/org/apache/maven/surefire/junit4/JUnit4Provider.java +++ b/surefire-providers/surefire-junit4/src/main/java/org/apache/maven/surefire/junit4/JUnit4Provider.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.junit4; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,23 +16,21 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.junit4; + +import java.util.Collection; +import java.util.Set; import org.apache.maven.surefire.api.booter.Command; +import org.apache.maven.surefire.api.provider.AbstractProvider; import org.apache.maven.surefire.api.provider.CommandChainReader; import org.apache.maven.surefire.api.provider.CommandListener; -import org.apache.maven.surefire.api.report.TestOutputReportEntry; -import org.apache.maven.surefire.api.report.TestReportListener; -import org.apache.maven.surefire.common.junit4.JUnit4RunListener; -import org.apache.maven.surefire.common.junit4.JUnit4TestChecker; -import org.apache.maven.surefire.common.junit4.JUnitTestFailureListener; -import org.apache.maven.surefire.common.junit4.Notifier; -import org.apache.maven.surefire.api.provider.AbstractProvider; import org.apache.maven.surefire.api.provider.ProviderParameters; -import org.apache.maven.surefire.report.ClassMethodIndexer; -import org.apache.maven.surefire.report.PojoStackTraceWriter; import org.apache.maven.surefire.api.report.ReporterFactory; import org.apache.maven.surefire.api.report.RunListener; import org.apache.maven.surefire.api.report.SimpleReportEntry; +import org.apache.maven.surefire.api.report.TestOutputReportEntry; +import org.apache.maven.surefire.api.report.TestReportListener; import org.apache.maven.surefire.api.suite.RunResult; import org.apache.maven.surefire.api.testset.TestListResolver; import org.apache.maven.surefire.api.testset.TestRequest; @@ -42,6 +38,12 @@ import org.apache.maven.surefire.api.util.RunOrderCalculator; import org.apache.maven.surefire.api.util.ScanResult; import org.apache.maven.surefire.api.util.TestsToRun; +import org.apache.maven.surefire.common.junit4.JUnit4RunListener; +import org.apache.maven.surefire.common.junit4.JUnit4TestChecker; +import org.apache.maven.surefire.common.junit4.JUnitTestFailureListener; +import org.apache.maven.surefire.common.junit4.Notifier; +import org.apache.maven.surefire.report.ClassMethodIndexer; +import org.apache.maven.surefire.report.PojoStackTraceWriter; import org.apache.maven.surefire.report.RunModeSetter; import org.junit.runner.Description; import org.junit.runner.Request; @@ -50,13 +52,15 @@ import org.junit.runner.manipulation.Filter; import org.junit.runner.notification.StoppedByUserException; -import java.util.Collection; -import java.util.Set; - import static java.lang.reflect.Modifier.isAbstract; import static java.lang.reflect.Modifier.isInterface; +import static org.apache.maven.surefire.api.report.ConsoleOutputCapture.startCapture; import static org.apache.maven.surefire.api.report.RunMode.NORMAL_RUN; import static org.apache.maven.surefire.api.report.RunMode.RERUN_TEST_AFTER_FAILURE; +import static org.apache.maven.surefire.api.report.SimpleReportEntry.withException; +import static org.apache.maven.surefire.api.testset.TestListResolver.optionallyWildcardFilter; +import static org.apache.maven.surefire.api.util.TestsToRun.fromClass; +import static org.apache.maven.surefire.api.util.internal.ObjectUtils.systemProps; import static org.apache.maven.surefire.common.junit4.JUnit4ProviderUtil.createMatchAnyDescriptionFilter; import static org.apache.maven.surefire.common.junit4.JUnit4ProviderUtil.generateFailingTestDescriptions; import static org.apache.maven.surefire.common.junit4.JUnit4ProviderUtil.isFailureInsideJUnitItself; @@ -65,19 +69,12 @@ import static org.apache.maven.surefire.common.junit4.JUnit4RunListener.rethrowAnyTestMechanismFailures; import static org.apache.maven.surefire.common.junit4.JUnit4RunListenerFactory.createCustomListeners; import static org.apache.maven.surefire.common.junit4.Notifier.pureNotifier; -import static org.apache.maven.surefire.api.report.ConsoleOutputCapture.startCapture; -import static org.apache.maven.surefire.api.report.SimpleReportEntry.withException; -import static org.apache.maven.surefire.api.testset.TestListResolver.optionallyWildcardFilter; -import static org.apache.maven.surefire.api.util.TestsToRun.fromClass; -import static org.apache.maven.surefire.api.util.internal.ObjectUtils.systemProps; import static org.junit.runner.Request.aClass; /** * @author Kristian Rosenvold */ -public class JUnit4Provider - extends AbstractProvider -{ +public class JUnit4Provider extends AbstractProvider { private static final String UNDETERMINED_TESTS_DESCRIPTION = "cannot determine test in forked JVM with surefire"; private final ClassMethodIndexer classMethodIndexer = new ClassMethodIndexer(); @@ -102,279 +99,221 @@ public class JUnit4Provider private TestsToRun testsToRun; - public JUnit4Provider( ProviderParameters bootParams ) - { + public JUnit4Provider(ProviderParameters bootParams) { // don't start a thread in CommandReader while we are in in-plugin process commandsReader = bootParams.isInsideFork() ? bootParams.getCommandReader() : null; providerParameters = bootParams; testClassLoader = bootParams.getTestClassLoader(); scanResult = bootParams.getScanResult(); runOrderCalculator = bootParams.getRunOrderCalculator(); - customRunListeners = bootParams.getProviderProperties().get( "listener" ); - jUnit4TestChecker = new JUnit4TestChecker( testClassLoader ); + customRunListeners = bootParams.getProviderProperties().get("listener"); + jUnit4TestChecker = new JUnit4TestChecker(testClassLoader); TestRequest testRequest = bootParams.getTestRequest(); testResolver = testRequest.getTestListResolver(); rerunFailingTestsCount = testRequest.getRerunFailingTestsCount(); } @Override - public RunResult invoke( Object forkTestSet ) - throws TestSetFailedException - { + public RunResult invoke(Object forkTestSet) throws TestSetFailedException { upgradeCheck(); ReporterFactory reporterFactory = providerParameters.getReporterFactory(); RunResult runResult; - try - { + try { TestReportListener reporter = reporterFactory.createTestReportListener(); - JUnit4RunListener listener = new JUnit4RunListener( reporter ); - listener.setRunMode( NORMAL_RUN ); + JUnit4RunListener listener = new JUnit4RunListener(reporter); + listener.setRunMode(NORMAL_RUN); - startCapture( listener ); + startCapture(listener); // startCapture() called in prior to setTestsToRun() - if ( testsToRun == null ) - { - setTestsToRun( forkTestSet ); + if (testsToRun == null) { + setTestsToRun(forkTestSet); } - Notifier notifier = new Notifier( listener, getSkipAfterFailureCount() ); + Notifier notifier = new Notifier(listener, getSkipAfterFailureCount()); Result result = new Result(); - notifier.addListeners( createCustomListeners( customRunListeners ) ) - .addListener( result.createListener() ); + notifier.addListeners(createCustomListeners(customRunListeners)).addListener(result.createListener()); - if ( isFailFast() && commandsReader != null ) - { - registerPleaseStopJUnitListener( notifier ); + if (isFailFast() && commandsReader != null) { + registerPleaseStopJUnitListener(notifier); } - try - { - notifier.fireTestRunStarted( testsToRun.allowEagerReading() - ? createTestsDescription( testsToRun ) - : createDescription( UNDETERMINED_TESTS_DESCRIPTION ) ); + try { + notifier.fireTestRunStarted( + testsToRun.allowEagerReading() + ? createTestsDescription(testsToRun) + : createDescription(UNDETERMINED_TESTS_DESCRIPTION)); - if ( commandsReader != null ) - { - registerShutdownListener( testsToRun ); + if (commandsReader != null) { + registerShutdownListener(testsToRun); commandsReader.awaitStarted(); } - for ( Class testToRun : testsToRun ) - { - executeTestSet( testToRun, reporter, notifier, listener ); + for (Class testToRun : testsToRun) { + executeTestSet(testToRun, reporter, notifier, listener); } - } - finally - { - notifier.fireTestRunFinished( result ); + } finally { + notifier.fireTestRunFinished(result); notifier.removeListeners(); } - rethrowAnyTestMechanismFailures( result ); - } - finally - { + rethrowAnyTestMechanismFailures(result); + } finally { runResult = reporterFactory.close(); } return runResult; } - private void setTestsToRun( Object forkTestSet ) - throws TestSetFailedException - { - if ( forkTestSet instanceof TestsToRun ) - { + private void setTestsToRun(Object forkTestSet) throws TestSetFailedException { + if (forkTestSet instanceof TestsToRun) { testsToRun = (TestsToRun) forkTestSet; - } - else if ( forkTestSet instanceof Class ) - { - testsToRun = fromClass( (Class) forkTestSet ); - } - else - { + } else if (forkTestSet instanceof Class) { + testsToRun = fromClass((Class) forkTestSet); + } else { testsToRun = scanClassPath(); } } - private boolean isRerunFailingTests() - { + private boolean isRerunFailingTests() { return rerunFailingTestsCount > 0; } - private boolean isFailFast() - { + private boolean isFailFast() { return providerParameters.getSkipAfterFailureCount() > 0; } - private int getSkipAfterFailureCount() - { + private int getSkipAfterFailureCount() { return isFailFast() ? providerParameters.getSkipAfterFailureCount() : 0; } - private void registerShutdownListener( final TestsToRun testsToRun ) - { - commandsReader.addShutdownListener( new CommandListener() - { + private void registerShutdownListener(final TestsToRun testsToRun) { + commandsReader.addShutdownListener(new CommandListener() { @Override - public void update( Command command ) - { + public void update(Command command) { testsToRun.markTestSetFinished(); } - } ); + }); } - private void registerPleaseStopJUnitListener( final Notifier notifier ) - { - commandsReader.addSkipNextTestsListener( new CommandListener() - { + private void registerPleaseStopJUnitListener(final Notifier notifier) { + commandsReader.addSkipNextTestsListener(new CommandListener() { @Override - public void update( Command command ) - { + public void update(Command command) { notifier.pleaseStop(); } - } ); + }); } - private void executeTestSet( Class clazz, RunListener reporter, Notifier notifier, RunModeSetter runMode ) - { - long testRunId = classMethodIndexer.indexClass( clazz.getName() ); + private void executeTestSet(Class clazz, RunListener reporter, Notifier notifier, RunModeSetter runMode) { + long testRunId = classMethodIndexer.indexClass(clazz.getName()); SimpleReportEntry report = - new SimpleReportEntry( NORMAL_RUN, testRunId, clazz.getName(), null, null, null, systemProps() ); - reporter.testSetStarting( report ); - try - { - executeWithRerun( clazz, notifier, runMode ); - } - catch ( Throwable e ) - { - if ( isFailFast() && e instanceof StoppedByUserException ) - { + new SimpleReportEntry(NORMAL_RUN, testRunId, clazz.getName(), null, null, null, systemProps()); + reporter.testSetStarting(report); + try { + executeWithRerun(clazz, notifier, runMode); + } catch (Throwable e) { + if (isFailFast() && e instanceof StoppedByUserException) { String reason = e.getClass().getName(); - Description skippedTest = createDescription( clazz.getName(), createIgnored( reason ) ); - notifier.fireTestIgnored( skippedTest ); - } - else - { + Description skippedTest = createDescription(clazz.getName(), createIgnored(reason)); + notifier.fireTestIgnored(skippedTest); + } else { String reportName = report.getName(); String reportSourceName = report.getSourceName(); - PojoStackTraceWriter stackWriter = new PojoStackTraceWriter( reportSourceName, reportName, e ); - reporter.testError( withException( NORMAL_RUN, testRunId, reportSourceName, null, reportName, null, - stackWriter ) ); + PojoStackTraceWriter stackWriter = new PojoStackTraceWriter(reportSourceName, reportName, e); + reporter.testError( + withException(NORMAL_RUN, testRunId, reportSourceName, null, reportName, null, stackWriter)); } - } - finally - { - reporter.testSetCompleted( report ); + } finally { + reporter.testSetCompleted(report); } } - private void executeWithRerun( Class clazz, Notifier notifier, RunModeSetter runMode ) - { + private void executeWithRerun(Class clazz, Notifier notifier, RunModeSetter runMode) { JUnitTestFailureListener failureListener = new JUnitTestFailureListener(); - notifier.addListener( failureListener ); + notifier.addListener(failureListener); boolean hasMethodFilter = testResolver != null && testResolver.hasMethodPatterns(); - try - { - try - { - notifier.asFailFast( isFailFast() ); - execute( clazz, notifier, hasMethodFilter ? createMethodFilter() : null ); - } - finally - { - notifier.asFailFast( false ); + try { + try { + notifier.asFailFast(isFailFast()); + execute(clazz, notifier, hasMethodFilter ? createMethodFilter() : null); + } finally { + notifier.asFailFast(false); } // Rerun failing tests if rerunFailingTestsCount is larger than 0 - if ( isRerunFailingTests() ) - { - runMode.setRunMode( RERUN_TEST_AFTER_FAILURE ); + if (isRerunFailingTests()) { + runMode.setRunMode(RERUN_TEST_AFTER_FAILURE); Notifier rerunNotifier = pureNotifier(); - notifier.copyListenersTo( rerunNotifier ); - for ( int i = 0; i < rerunFailingTestsCount && !failureListener.getAllFailures().isEmpty(); i++ ) - { - Set failures = generateFailingTestDescriptions( failureListener.getAllFailures() ); + notifier.copyListenersTo(rerunNotifier); + for (int i = 0; + i < rerunFailingTestsCount + && !failureListener.getAllFailures().isEmpty(); + i++) { + Set failures = generateFailingTestDescriptions(failureListener.getAllFailures()); failureListener.reset(); - Filter failureDescriptionFilter = createMatchAnyDescriptionFilter( failures ); - execute( clazz, rerunNotifier, failureDescriptionFilter ); + Filter failureDescriptionFilter = createMatchAnyDescriptionFilter(failures); + execute(clazz, rerunNotifier, failureDescriptionFilter); } } - } - finally - { - notifier.removeListener( failureListener ); + } finally { + notifier.removeListener(failureListener); } } @Override - public Iterable> getSuites() - { + public Iterable> getSuites() { testsToRun = scanClassPath(); return testsToRun; } - private TestsToRun scanClassPath() - { - final TestsToRun scannedClasses = scanResult.applyFilter( jUnit4TestChecker, testClassLoader ); - return runOrderCalculator.orderTestClasses( scannedClasses ); + private TestsToRun scanClassPath() { + final TestsToRun scannedClasses = scanResult.applyFilter(jUnit4TestChecker, testClassLoader); + return runOrderCalculator.orderTestClasses(scannedClasses); } - private void upgradeCheck() - throws TestSetFailedException - { - if ( isJUnit4UpgradeCheck() ) - { + private void upgradeCheck() throws TestSetFailedException { + if (isJUnit4UpgradeCheck()) { Collection> classesSkippedByValidation = - scanResult.getClassesSkippedByValidation( jUnit4TestChecker, testClassLoader ); - if ( !classesSkippedByValidation.isEmpty() ) - { + scanResult.getClassesSkippedByValidation(jUnit4TestChecker, testClassLoader); + if (!classesSkippedByValidation.isEmpty()) { StringBuilder reason = new StringBuilder(); - reason.append( "Updated check failed\n" ); - reason.append( "There are tests that would be run with junit4 / surefire 2.6 but not with [2.7,):\n" ); - for ( Class testClass : classesSkippedByValidation ) - { - reason.append( " " ); - reason.append( testClass.getName() ); - reason.append( "\n" ); + reason.append("Updated check failed\n"); + reason.append("There are tests that would be run with junit4 / surefire 2.6 but not with [2.7,):\n"); + for (Class testClass : classesSkippedByValidation) { + reason.append(" "); + reason.append(testClass.getName()); + reason.append("\n"); } - throw new TestSetFailedException( reason.toString() ); + throw new TestSetFailedException(reason.toString()); } } } - static Description createTestsDescription( Iterable> classes ) - { + static Description createTestsDescription(Iterable> classes) { // "null" string rather than null; otherwise NPE in junit:4.0 - Description description = createDescription( "null" ); - for ( Class clazz : classes ) - { - description.addChild( createDescription( clazz.getName() ) ); + Description description = createDescription("null"); + for (Class clazz : classes) { + description.addChild(createDescription(clazz.getName())); } return description; } - private static boolean isJUnit4UpgradeCheck() - { - return System.getProperty( "surefire.junit4.upgradecheck" ) != null; + private static boolean isJUnit4UpgradeCheck() { + return System.getProperty("surefire.junit4.upgradecheck") != null; } - private static void execute( Class testClass, Notifier notifier, Filter filter ) - { + private static void execute(Class testClass, Notifier notifier, Filter filter) { final int classModifiers = testClass.getModifiers(); - if ( !isAbstract( classModifiers ) && !isInterface( classModifiers ) ) - { - Request request = aClass( testClass ); - if ( filter != null ) - { - request = request.filterWith( filter ); + if (!isAbstract(classModifiers) && !isInterface(classModifiers)) { + Request request = aClass(testClass); + if (filter != null) { + request = request.filterWith(filter); } Runner runner = request.getRunner(); - if ( countTestsInRunner( runner.getDescription() ) != 0 ) - { - runner.run( notifier ); + if (countTestsInRunner(runner.getDescription()) != 0) { + runner.run(notifier); } } } @@ -386,53 +325,39 @@ private static void execute( Class testClass, Notifier notifier, Filter filte * and Description#isTest() returns true, but this description is not a real test * and therefore it should not be included in the entire test count. */ - private static int countTestsInRunner( Description description ) - { - if ( description.isSuite() ) - { + private static int countTestsInRunner(Description description) { + if (description.isSuite()) { int count = 0; - for ( Description child : description.getChildren() ) - { - if ( !hasFilteredOutAllChildren( child ) ) - { - count += countTestsInRunner( child ); + for (Description child : description.getChildren()) { + if (!hasFilteredOutAllChildren(child)) { + count += countTestsInRunner(child); } } return count; - } - else if ( description.isTest() ) - { - return hasFilteredOutAllChildren( description ) ? 0 : 1; - } - else - { + } else if (description.isTest()) { + return hasFilteredOutAllChildren(description) ? 0 : 1; + } else { return 0; } } - private static boolean hasFilteredOutAllChildren( Description description ) - { - if ( isFailureInsideJUnitItself( description ) ) - { + private static boolean hasFilteredOutAllChildren(Description description) { + if (isFailureInsideJUnitItself(description)) { return true; } String name = description.getDisplayName(); // JUnit 4.0: initializationError0; JUnit 4.12: initializationError. - if ( name == null ) - { + if (name == null) { return true; - } - else - { + } else { name = name.trim(); - return name.startsWith( "initializationError0(org.junit.runner.manipulation.Filter)" ) - || name.startsWith( "initializationError(org.junit.runner.manipulation.Filter)" ); + return name.startsWith("initializationError0(org.junit.runner.manipulation.Filter)") + || name.startsWith("initializationError(org.junit.runner.manipulation.Filter)"); } } - private Filter createMethodFilter() - { - TestListResolver methodFilter = optionallyWildcardFilter( testResolver ); - return methodFilter.isEmpty() || methodFilter.isWildcard() ? null : new TestResolverFilter( methodFilter ); + private Filter createMethodFilter() { + TestListResolver methodFilter = optionallyWildcardFilter(testResolver); + return methodFilter.isEmpty() || methodFilter.isWildcard() ? null : new TestResolverFilter(methodFilter); } } diff --git a/surefire-providers/surefire-junit4/src/main/java/org/apache/maven/surefire/junit4/TestResolverFilter.java b/surefire-providers/surefire-junit4/src/main/java/org/apache/maven/surefire/junit4/TestResolverFilter.java index a50ec56b46..1d05aabb92 100644 --- a/surefire-providers/surefire-junit4/src/main/java/org/apache/maven/surefire/junit4/TestResolverFilter.java +++ b/surefire-providers/surefire-junit4/src/main/java/org/apache/maven/surefire/junit4/TestResolverFilter.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.junit4; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,43 +16,39 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.junit4; -import org.apache.maven.surefire.api.util.internal.ClassMethod; import org.apache.maven.surefire.api.testset.TestListResolver; +import org.apache.maven.surefire.api.util.internal.ClassMethod; import org.junit.runner.Description; import org.junit.runner.manipulation.Filter; -import static org.apache.maven.surefire.common.junit4.JUnit4ProviderUtil.toClassMethod; import static org.apache.maven.surefire.api.testset.TestListResolver.toClassFileName; +import static org.apache.maven.surefire.common.junit4.JUnit4ProviderUtil.toClassMethod; /** * Method filter used in {@link JUnit4Provider}. */ -final class TestResolverFilter - extends Filter -{ +final class TestResolverFilter extends Filter { private final TestListResolver methodFilter; - TestResolverFilter( TestListResolver methodFilter ) - { + TestResolverFilter(TestListResolver methodFilter) { this.methodFilter = methodFilter; } @Override - public boolean shouldRun( Description description ) - { + public boolean shouldRun(Description description) { // class: Java class name; method: 1. "testMethod" or 2. "testMethod[5+whatever]" in @Parameterized - final ClassMethod cm = toClassMethod( description ); + final ClassMethod cm = toClassMethod(description); final boolean isSuite = description.isSuite(); final boolean isValidTest = description.isTest() && cm.isValidTest(); final String clazz = cm.getClazz(); final String method = cm.getMethod(); - return isSuite || isValidTest && methodFilter.shouldRun( toClassFileName( clazz ), method ); + return isSuite || isValidTest && methodFilter.shouldRun(toClassFileName(clazz), method); } @Override - public String describe() - { + public String describe() { return methodFilter.toString(); } } diff --git a/surefire-providers/surefire-junit4/src/test/java/org/apache/maven/surefire/junit4/JUnit4ProviderTest.java b/surefire-providers/surefire-junit4/src/test/java/org/apache/maven/surefire/junit4/JUnit4ProviderTest.java index 9e048385d2..c66ae824d5 100644 --- a/surefire-providers/surefire-junit4/src/test/java/org/apache/maven/surefire/junit4/JUnit4ProviderTest.java +++ b/surefire-providers/surefire-junit4/src/test/java/org/apache/maven/surefire/junit4/JUnit4ProviderTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.junit4; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,10 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.junit4; + +import java.io.File; +import java.util.HashMap; import org.apache.maven.surefire.api.booter.BaseProviderFactory; import org.apache.maven.surefire.api.testset.RunOrderParameters; @@ -25,9 +27,6 @@ import org.junit.Test; import org.junit.runner.Description; -import java.io.File; -import java.util.HashMap; - import static java.util.Arrays.asList; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; @@ -42,42 +41,34 @@ /** * @author Kristian Rosenvold */ -public class JUnit4ProviderTest -{ +public class JUnit4ProviderTest { @Test - public void testCreateProvider() - { - assertNotNull( getJUnit4Provider() ); + public void testCreateProvider() { + assertNotNull(getJUnit4Provider()); } - private JUnit4Provider getJUnit4Provider() - { - BaseProviderFactory providerParameters = new BaseProviderFactory( true ); - providerParameters.setProviderProperties( new HashMap() ); - providerParameters.setClassLoaders( getClass().getClassLoader() ); - providerParameters.setTestRequest( new TestRequest( null, null, null ) ); - providerParameters.setRunOrderParameters( new RunOrderParameters( "hourly", new File( "" ) ) ); - return new JUnit4Provider( providerParameters ); + private JUnit4Provider getJUnit4Provider() { + BaseProviderFactory providerParameters = new BaseProviderFactory(true); + providerParameters.setProviderProperties(new HashMap()); + providerParameters.setClassLoaders(getClass().getClassLoader()); + providerParameters.setTestRequest(new TestRequest(null, null, null)); + providerParameters.setRunOrderParameters(new RunOrderParameters("hourly", new File(""))); + return new JUnit4Provider(providerParameters); } @Test - public void testShouldCreateDescription() - { - class A - { - } + public void testShouldCreateDescription() { + class A {} - class B - { - } + class B {} - Description d = JUnit4Provider.createTestsDescription( asList( A.class, B.class ) ); - assertThat( d, is( notNullValue() ) ); - assertThat( d.getDisplayName(), not( isEmptyOrNullString() ) ); - assertThat( d.getDisplayName(), is( "null" ) ); - assertThat( d.getChildren(), hasSize( 2 ) ); - Description a = createSuiteDescription( A.class ); - Description b = createSuiteDescription( B.class ); - assertThat( d.getChildren(), contains( a, b ) ); + Description d = JUnit4Provider.createTestsDescription(asList(A.class, B.class)); + assertThat(d, is(notNullValue())); + assertThat(d.getDisplayName(), not(isEmptyOrNullString())); + assertThat(d.getDisplayName(), is("null")); + assertThat(d.getChildren(), hasSize(2)); + Description a = createSuiteDescription(A.class); + Description b = createSuiteDescription(B.class); + assertThat(d.getChildren(), contains(a, b)); } } diff --git a/surefire-providers/surefire-junit4/src/test/java/org/apache/maven/surefire/junit4/JUnit4SuiteTest.java b/surefire-providers/surefire-junit4/src/test/java/org/apache/maven/surefire/junit4/JUnit4SuiteTest.java index 2d4fb72882..98203f8982 100644 --- a/surefire-providers/surefire-junit4/src/test/java/org/apache/maven/surefire/junit4/JUnit4SuiteTest.java +++ b/surefire-providers/surefire-junit4/src/test/java/org/apache/maven/surefire/junit4/JUnit4SuiteTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.junit4; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.junit4; import junit.framework.JUnit4TestAdapter; import junit.framework.Test; @@ -26,10 +25,8 @@ /** * Adapt the JUnit4 tests which use only annotations to the JUnit3 test suite. */ -public class JUnit4SuiteTest extends TestCase -{ - public static Test suite() - { - return new JUnit4TestAdapter( JUnit4ProviderTest.class ); +public class JUnit4SuiteTest extends TestCase { + public static Test suite() { + return new JUnit4TestAdapter(JUnit4ProviderTest.class); } } diff --git a/surefire-providers/surefire-junit47/pom.xml b/surefire-providers/surefire-junit47/pom.xml index d0902b3d82..cbd818a1d0 100644 --- a/surefire-providers/surefire-junit47/pom.xml +++ b/surefire-providers/surefire-junit47/pom.xml @@ -1,3 +1,4 @@ + - - 4.0.0 - - - org.apache.maven.surefire - surefire-providers - 3.0.0-M10-SNAPSHOT - + 4.0.0 - surefire-junit47 + + org.apache.maven.surefire + surefire-providers + 3.0.0-M10-SNAPSHOT + - SureFire JUnitCore Runner - SureFire JUnitCore (JUnit 4.7+) Runner - - - - org.apache.maven.surefire - common-junit48 - ${project.version} - - - junit - junit - 4.8.2 - provided - - - org.apache.maven.surefire - maven-surefire-common - ${project.version} - test - - - com.github.stephenc.jcip - jcip-annotations - 1.0-1 - test - - - org.mockito - mockito-core - test - - + surefire-junit47 - - - - org.jacoco - jacoco-maven-plugin - - - jacoco-agent - - prepare-agent - - - - - jacoco.agent - - - - maven-surefire-plugin - - ${jvm.args.tests} ${jacoco.agent} - true - - **/JUnit47SuiteTest.java - - - - - org.apache.maven.surefire - surefire-shadefire - 3.0.0-M7 - - - - - + SureFire JUnitCore Runner + SureFire JUnitCore (JUnit 4.7+) Runner surefire-3.0.0-M8 + + + + org.apache.maven.surefire + common-junit48 + ${project.version} + + + junit + junit + 4.8.2 + provided + + + org.apache.maven.surefire + maven-surefire-common + ${project.version} + test + + + com.github.stephenc.jcip + jcip-annotations + 1.0-1 + test + + + org.mockito + mockito-core + test + + + + + + + org.jacoco + jacoco-maven-plugin + + jacoco.agent + + + + jacoco-agent + + prepare-agent + + + + + + maven-surefire-plugin + + ${jvm.args.tests} ${jacoco.agent} + true + + **/JUnit47SuiteTest.java + + + + + org.apache.maven.surefire + surefire-shadefire + 3.0.0-M7 + + + + + + diff --git a/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/AsynchronousRunner.java b/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/AsynchronousRunner.java index 0d9bacf1cf..cd7fe47728 100644 --- a/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/AsynchronousRunner.java +++ b/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/AsynchronousRunner.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.junitcore; /* @@ -36,50 +54,35 @@ * @author Kristian Rosenvold */ @Deprecated -public class AsynchronousRunner - implements RunnerScheduler -{ - private final List> futures = Collections.synchronizedList( new ArrayList>() ); +public class AsynchronousRunner implements RunnerScheduler { + private final List> futures = Collections.synchronizedList(new ArrayList>()); private final ExecutorService fService; - public AsynchronousRunner( ExecutorService fService ) - { + public AsynchronousRunner(ExecutorService fService) { this.fService = fService; } @Override - public void schedule( final Runnable childStatement ) - { - futures.add( fService.submit( Executors.callable( childStatement ) ) ); + public void schedule(final Runnable childStatement) { + futures.add(fService.submit(Executors.callable(childStatement))); } - @Override - public void finished() - { - try - { + public void finished() { + try { waitForCompletion(); - } - catch ( ExecutionException e ) - { - throw new RuntimeException( e ); + } catch (ExecutionException e) { + throw new RuntimeException(e); } } - public void waitForCompletion() - throws ExecutionException - { - for ( Future each : futures ) - { - try - { + public void waitForCompletion() throws ExecutionException { + for (Future each : futures) { + try { each.get(); - } - catch ( InterruptedException e ) - { - throw new RuntimeException( e ); + } catch (InterruptedException e) { + throw new RuntimeException(e); } } } diff --git a/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/ClassesParallelRunListener.java b/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/ClassesParallelRunListener.java index c73eedb89a..6788b8c711 100644 --- a/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/ClassesParallelRunListener.java +++ b/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/ClassesParallelRunListener.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.junitcore; /* @@ -27,21 +45,16 @@ * @author Kristian Rosenvold */ @Deprecated // remove this class after StatelessXmlReporter is capable of parallel test sets processing -final class ClassesParallelRunListener - extends ConcurrentRunListener -{ - ClassesParallelRunListener( Map classMethodCounts, ReporterFactory reporterFactory ) - { - super( reporterFactory, false, classMethodCounts ); +final class ClassesParallelRunListener extends ConcurrentRunListener { + ClassesParallelRunListener(Map classMethodCounts, ReporterFactory reporterFactory) { + super(reporterFactory, false, classMethodCounts); } @Override - protected void checkIfTestSetCanBeReported( TestSet testSetForTest ) - { + protected void checkIfTestSetCanBeReported(TestSet testSetForTest) { TestSet currentlyAttached = TestSet.getThreadTestSet(); - if ( currentlyAttached != null && currentlyAttached != testSetForTest ) - { - currentlyAttached.setAllScheduled( getRunListener() ); + if (currentlyAttached != null && currentlyAttached != testSetForTest) { + currentlyAttached.setAllScheduled(getRunListener()); } } } diff --git a/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/ConcurrentRunListener.java b/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/ConcurrentRunListener.java index f61bd9c675..0f0ad71985 100644 --- a/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/ConcurrentRunListener.java +++ b/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/ConcurrentRunListener.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.junitcore; /* @@ -44,9 +62,7 @@ * @author Kristian Rosenvold */ @Deprecated // remove this class after StatelessXmlReporter is capable of parallel test sets processing -abstract class ConcurrentRunListener - implements TestReportListener -{ +abstract class ConcurrentRunListener implements TestReportListener { private final Map classMethodCounts; private final ThreadLocal> reporterManagerThreadLocal; @@ -55,228 +71,187 @@ abstract class ConcurrentRunListener private final ConsoleLogger logger; - ConcurrentRunListener( final ReporterFactory reporterFactory, boolean reportImmediately, - Map classMethodCounts ) - { + ConcurrentRunListener( + final ReporterFactory reporterFactory, boolean reportImmediately, Map classMethodCounts) { this.reportImmediately = reportImmediately; this.classMethodCounts = classMethodCounts; logger = reporterFactory.createTestReportListener(); - reporterManagerThreadLocal = withInitial( reporterFactory::createTestReportListener ); + reporterManagerThreadLocal = withInitial(reporterFactory::createTestReportListener); } @Override - public void testSetStarting( TestSetReportEntry description ) - { - } + public void testSetStarting(TestSetReportEntry description) {} @Override - public void testSetCompleted( TestSetReportEntry result ) - { - try - { + public void testSetCompleted(TestSetReportEntry result) { + try { TestReportListener reporterManager = getRunListener(); - for ( TestSet testSet : classMethodCounts.values() ) - { - testSet.replay( reporterManager ); + for (TestSet testSet : classMethodCounts.values()) { + testSet.replay(reporterManager); } - } - finally - { + } finally { reporterManagerThreadLocal.remove(); } } @Override - public void testFailed( ReportEntry failure ) - { - final TestMethod testMethod = getOrCreateThreadAttachedTestMethod( failure ); - if ( testMethod != null ) - { - testMethod.testFailure( failure ); + public void testFailed(ReportEntry failure) { + final TestMethod testMethod = getOrCreateThreadAttachedTestMethod(failure); + if (testMethod != null) { + testMethod.testFailure(failure); testMethod.detachFromCurrentThread(); } } @Override - public void testError( ReportEntry failure ) - { - final TestMethod testMethod = getOrCreateThreadAttachedTestMethod( failure ); - if ( testMethod != null ) - { - testMethod.testError( failure ); + public void testError(ReportEntry failure) { + final TestMethod testMethod = getOrCreateThreadAttachedTestMethod(failure); + if (testMethod != null) { + testMethod.testError(failure); testMethod.detachFromCurrentThread(); } } @Override - public void testSkipped( ReportEntry description ) - { - TestSet testSet = getTestSet( description ); - TestMethod testMethod = testSet.createThreadAttachedTestMethod( description ); - testMethod.testIgnored( description ); - testSet.incrementFinishedTests( getRunListener(), reportImmediately ); + public void testSkipped(ReportEntry description) { + TestSet testSet = getTestSet(description); + TestMethod testMethod = testSet.createThreadAttachedTestMethod(description); + testMethod.testIgnored(description); + testSet.incrementFinishedTests(getRunListener(), reportImmediately); testMethod.detachFromCurrentThread(); } @Override - public void testExecutionSkippedByUser() - { + public void testExecutionSkippedByUser() { // cannot guarantee proper call to all listeners getRunListener().testExecutionSkippedByUser(); } @Override - public void testAssumptionFailure( ReportEntry failure ) - { - final TestMethod testMethod = getOrCreateThreadAttachedTestMethod( failure ); - if ( testMethod != null ) - { - testMethod.testAssumption( failure ); + public void testAssumptionFailure(ReportEntry failure) { + final TestMethod testMethod = getOrCreateThreadAttachedTestMethod(failure); + if (testMethod != null) { + testMethod.testAssumption(failure); testMethod.detachFromCurrentThread(); } } @Override - public void testStarting( ReportEntry description ) - { - TestSet testSet = getTestSet( description ); - testSet.createThreadAttachedTestMethod( description ); + public void testStarting(ReportEntry description) { + TestSet testSet = getTestSet(description); + testSet.createThreadAttachedTestMethod(description); - checkIfTestSetCanBeReported( testSet ); + checkIfTestSetCanBeReported(testSet); testSet.attachToThread(); } @Override - public void testSucceeded( ReportEntry report ) - { + public void testSucceeded(ReportEntry report) { TestMethod testMethod = getThreadTestMethod(); - if ( testMethod != null ) - { + if (testMethod != null) { testMethod.testFinished(); - testMethod.getTestSet().incrementFinishedTests( getRunListener(), reportImmediately ); + testMethod.getTestSet().incrementFinishedTests(getRunListener(), reportImmediately); testMethod.detachFromCurrentThread(); } } - private TestMethod getOrCreateThreadAttachedTestMethod( ReportEntry description ) - { + private TestMethod getOrCreateThreadAttachedTestMethod(ReportEntry description) { TestMethod threadTestMethod = getThreadTestMethod(); - if ( threadTestMethod != null ) - { + if (threadTestMethod != null) { return threadTestMethod; } - TestSet testSet = getTestSet( description ); - if ( testSet == null ) - { - logger.warning( description.getName() ); + TestSet testSet = getTestSet(description); + if (testSet == null) { + logger.warning(description.getName()); StackTraceWriter writer = description.getStackTraceWriter(); - if ( writer != null ) - { - logger.error( writer.writeTraceToString() ); + if (writer != null) { + logger.error(writer.writeTraceToString()); } return null; - } - else - { - return testSet.createThreadAttachedTestMethod( description ); + } else { + return testSet.createThreadAttachedTestMethod(description); } } - protected abstract void checkIfTestSetCanBeReported( TestSet testSetForTest ); + protected abstract void checkIfTestSetCanBeReported(TestSet testSetForTest); - private TestSet getTestSet( ReportEntry description ) - { - return classMethodCounts.get( description.getSourceName() ); + private TestSet getTestSet(ReportEntry description) { + return classMethodCounts.get(description.getSourceName()); } - final TestReportListener getRunListener() - { + final TestReportListener getRunListener() { return reporterManagerThreadLocal.get(); } - public static ConcurrentRunListener createInstance( Map classMethodCounts, - ReporterFactory reporterFactory, - boolean parallelClasses, boolean parallelBoth ) - { + public static ConcurrentRunListener createInstance( + Map classMethodCounts, + ReporterFactory reporterFactory, + boolean parallelClasses, + boolean parallelBoth) { return parallelClasses - ? new ClassesParallelRunListener( classMethodCounts, reporterFactory ) - : new MethodsParallelRunListener( classMethodCounts, reporterFactory, !parallelBoth ); + ? new ClassesParallelRunListener(classMethodCounts, reporterFactory) + : new MethodsParallelRunListener(classMethodCounts, reporterFactory, !parallelBoth); } - @Override - public void writeTestOutput( TestOutputReportEntry reportEntry ) - { + public void writeTestOutput(TestOutputReportEntry reportEntry) { TestMethod threadTestMethod = getThreadTestMethod(); - if ( threadTestMethod != null ) - { + if (threadTestMethod != null) { LogicalStream logicalStream = threadTestMethod.getLogicalStream(); - logicalStream.write( reportEntry ); - } - else - { + logicalStream.write(reportEntry); + } else { // Not able to associate output with any thread. Just dump to console - logger.info( reportEntry.getLog() ); + logger.info(reportEntry.getLog()); } } @Override - public boolean isDebugEnabled() - { + public boolean isDebugEnabled() { return logger.isDebugEnabled(); } @Override - public void debug( String message ) - { - logger.debug( message ); + public void debug(String message) { + logger.debug(message); } @Override - public boolean isInfoEnabled() - { + public boolean isInfoEnabled() { return logger.isInfoEnabled(); } @Override - public void info( String message ) - { - logger.info( message ); + public void info(String message) { + logger.info(message); } @Override - public boolean isWarnEnabled() - { + public boolean isWarnEnabled() { return logger.isWarnEnabled(); } @Override - public void warning( String message ) - { - logger.warning( message ); + public void warning(String message) { + logger.warning(message); } @Override - public boolean isErrorEnabled() - { + public boolean isErrorEnabled() { return logger.isErrorEnabled(); } @Override - public void error( String message ) - { - logger.error( message ); + public void error(String message) { + logger.error(message); } @Override - public void error( String message, Throwable t ) - { - logger.error( message, t ); + public void error(String message, Throwable t) { + logger.error(message, t); } @Override - public void error( Throwable t ) - { - logger.error( t ); + public void error(Throwable t) { + logger.error(t); } } diff --git a/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/ConfigurableParallelComputer.java b/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/ConfigurableParallelComputer.java index 03dea04551..4fce6ba656 100644 --- a/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/ConfigurableParallelComputer.java +++ b/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/ConfigurableParallelComputer.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.junitcore; /* @@ -43,9 +61,7 @@ * @author Kristian Rosenvold */ @Deprecated -public class ConfigurableParallelComputer - extends Computer -{ +public class ConfigurableParallelComputer extends Computer { private static final ThreadFactory DAEMON_THREAD_FACTORY = DaemonThreadFactory.newDaemonThreadFactory(); private final boolean fClasses; @@ -57,117 +73,94 @@ public class ConfigurableParallelComputer private final ExecutorService fService; private final List nonBlockers = - Collections.synchronizedList( new ArrayList() ); - + Collections.synchronizedList(new ArrayList()); - public ConfigurableParallelComputer() - { - this( true, true, Executors.newCachedThreadPool( DAEMON_THREAD_FACTORY ), false ); + public ConfigurableParallelComputer() { + this(true, true, Executors.newCachedThreadPool(DAEMON_THREAD_FACTORY), false); } - public ConfigurableParallelComputer( boolean fClasses, boolean fMethods ) - { - this( fClasses, fMethods, Executors.newCachedThreadPool( DAEMON_THREAD_FACTORY ), false ); + public ConfigurableParallelComputer(boolean fClasses, boolean fMethods) { + this(fClasses, fMethods, Executors.newCachedThreadPool(DAEMON_THREAD_FACTORY), false); } - public ConfigurableParallelComputer( boolean fClasses, boolean fMethods, Integer numberOfThreads, boolean perCore ) - { - this( fClasses, fMethods, - Executors.newFixedThreadPool( - numberOfThreads * ( perCore ? Runtime.getRuntime().availableProcessors() : 1 ), - DAEMON_THREAD_FACTORY ), - true ); + public ConfigurableParallelComputer(boolean fClasses, boolean fMethods, Integer numberOfThreads, boolean perCore) { + this( + fClasses, + fMethods, + Executors.newFixedThreadPool( + numberOfThreads * (perCore ? Runtime.getRuntime().availableProcessors() : 1), + DAEMON_THREAD_FACTORY), + true); } - private ConfigurableParallelComputer( boolean fClasses, boolean fMethods, ExecutorService executorService, - boolean fixedPool ) - { + private ConfigurableParallelComputer( + boolean fClasses, boolean fMethods, ExecutorService executorService, boolean fixedPool) { this.fClasses = fClasses; this.fMethods = fMethods; fService = executorService; this.fixedPool = fixedPool; } - @SuppressWarnings( { "UnusedDeclaration" } ) - public void close() - throws ExecutionException - { - for ( AsynchronousRunner nonBlocker : nonBlockers ) - { + @SuppressWarnings({"UnusedDeclaration"}) + public void close() throws ExecutionException { + for (AsynchronousRunner nonBlocker : nonBlockers) { nonBlocker.waitForCompletion(); } fService.shutdown(); - try - { - if ( !fService.awaitTermination( 10, java.util.concurrent.TimeUnit.SECONDS ) ) - { - throw new RuntimeException( "Executor did not shut down within timeout" ); + try { + if (!fService.awaitTermination(10, java.util.concurrent.TimeUnit.SECONDS)) { + throw new RuntimeException("Executor did not shut down within timeout"); } - } - catch ( InterruptedException e ) - { - throw new RuntimeException( e ); + } catch (InterruptedException e) { + throw new RuntimeException(e); } } - private Runner parallelize( Runner runner, RunnerScheduler runnerInterceptor ) - { - if ( runner instanceof ParentRunner ) - { - ( (ParentRunner) runner ).setScheduler( runnerInterceptor ); + private Runner parallelize(Runner runner, RunnerScheduler runnerInterceptor) { + if (runner instanceof ParentRunner) { + ((ParentRunner) runner).setScheduler(runnerInterceptor); } return runner; } - private RunnerScheduler getMethodInterceptor() - { - if ( fClasses && fMethods ) - { - final AsynchronousRunner blockingAsynchronousRunner = new AsynchronousRunner( fService ); - nonBlockers.add( blockingAsynchronousRunner ); + private RunnerScheduler getMethodInterceptor() { + if (fClasses && fMethods) { + final AsynchronousRunner blockingAsynchronousRunner = new AsynchronousRunner(fService); + nonBlockers.add(blockingAsynchronousRunner); return blockingAsynchronousRunner; } - return fMethods ? new AsynchronousRunner( fService ) : new SynchronousRunner(); + return fMethods ? new AsynchronousRunner(fService) : new SynchronousRunner(); } - private RunnerScheduler getClassInterceptor() - { - if ( fClasses ) - { - return fMethods ? new SynchronousRunner() : new AsynchronousRunner( fService ); + private RunnerScheduler getClassInterceptor() { + if (fClasses) { + return fMethods ? new SynchronousRunner() : new AsynchronousRunner(fService); } return new SynchronousRunner(); } @Override - public Runner getSuite( RunnerBuilder builder, java.lang.Class[] classes ) - throws InitializationError - { - Runner suite = super.getSuite( builder, classes ); - return fClasses ? parallelize( suite, getClassInterceptor() ) : suite; + public Runner getSuite(RunnerBuilder builder, java.lang.Class[] classes) throws InitializationError { + Runner suite = super.getSuite(builder, classes); + return fClasses ? parallelize(suite, getClassInterceptor()) : suite; } @Override - protected Runner getRunner( RunnerBuilder builder, Class testClass ) - throws Throwable - { - Runner runner = super.getRunner( builder, testClass ); - return fMethods && !isTestSuite( testClass ) ? parallelize( runner, getMethodInterceptor() ) : runner; + protected Runner getRunner(RunnerBuilder builder, Class testClass) throws Throwable { + Runner runner = super.getRunner(builder, testClass); + return fMethods && !isTestSuite(testClass) ? parallelize(runner, getMethodInterceptor()) : runner; } - private boolean isTestSuite( Class testClass ) - { + private boolean isTestSuite(Class testClass) { // Todo: Find out how/if this is enough - final Suite.SuiteClasses annotation = testClass.getAnnotation( Suite.SuiteClasses.class ); - return ( annotation != null ); + final Suite.SuiteClasses annotation = testClass.getAnnotation(Suite.SuiteClasses.class); + return (annotation != null); } @Override - public String toString() - { + public String toString() { return "ConfigurableParallelComputer{" + "classes=" + fClasses + ", methods=" + fMethods + ", fixedPool=" - + fixedPool + '}'; + + fixedPool + '}'; } - } diff --git a/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/FilteringRequest.java b/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/FilteringRequest.java index 2adabbb837..d6f3a58afb 100644 --- a/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/FilteringRequest.java +++ b/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/FilteringRequest.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.junitcore; /* @@ -27,28 +45,21 @@ /** * Moved nested class from {@link JUnitCoreWrapper}. */ -final class FilteringRequest - extends Request -{ +final class FilteringRequest extends Request { private Runner filteredRunner; - FilteringRequest( Request req, Filter filter ) - { - try - { + FilteringRequest(Request req, Filter filter) { + try { Runner runner = req.getRunner(); - filter.apply( runner ); + filter.apply(runner); filteredRunner = runner; - } - catch ( NoTestsRemainException e ) - { + } catch (NoTestsRemainException e) { filteredRunner = null; } } @Override - public Runner getRunner() - { + public Runner getRunner() { return filteredRunner; } } diff --git a/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/JUnitCore.java b/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/JUnitCore.java index a48e1a68e2..c22ccc4615 100644 --- a/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/JUnitCore.java +++ b/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/JUnitCore.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.junitcore; /* @@ -19,8 +37,8 @@ * under the License. */ -import org.apache.maven.surefire.common.junit4.Notifier; import org.apache.maven.surefire.api.testset.TestSetFailedException; +import org.apache.maven.surefire.common.junit4.Notifier; import org.junit.runner.Result; import org.junit.runner.Runner; import org.junit.runner.notification.RunListener; @@ -34,46 +52,33 @@ * @since 2.19 * @see JUnit issue 1186 */ -class JUnitCore -{ +class JUnitCore { private final Notifier notifier; - JUnitCore( Notifier notifier ) - { + JUnitCore(Notifier notifier) { this.notifier = notifier; } - Result run( Runner runner ) - throws TestSetFailedException - { + Result run(Runner runner) throws TestSetFailedException { Result result = new Result(); RunListener listener = result.createListener(); - notifier.addFirstListener( listener ); - try - { - notifier.fireTestRunStarted( runner.getDescription() ); - runner.run( notifier ); - } - catch ( Throwable e ) - { - afterException( e ); - } - finally - { - notifier.fireTestRunFinished( result ); - notifier.removeListener( listener ); + notifier.addFirstListener(listener); + try { + notifier.fireTestRunStarted(runner.getDescription()); + runner.run(notifier); + } catch (Throwable e) { + afterException(e); + } finally { + notifier.fireTestRunFinished(result); + notifier.removeListener(listener); afterFinished(); } return result; } - protected void afterException( Throwable e ) - throws TestSetFailedException - { - throw new TestSetFailedException( e ); + protected void afterException(Throwable e) throws TestSetFailedException { + throw new TestSetFailedException(e); } - protected void afterFinished() - { - } + protected void afterFinished() {} } diff --git a/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/JUnitCoreParameters.java b/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/JUnitCoreParameters.java index adc97eb445..5e9136468a 100644 --- a/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/JUnitCoreParameters.java +++ b/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/JUnitCoreParameters.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.junitcore; /* @@ -28,8 +46,7 @@ /** * @author Kristian Rosenvold */ -public final class JUnitCoreParameters -{ +public final class JUnitCoreParameters { public static final String PARALLEL_KEY = ProviderParameterNames.PARALLEL_PROP; public static final String PERCORETHREADCOUNT_KEY = "perCoreThreadCount"; @@ -70,50 +87,46 @@ public final class JUnitCoreParameters private final boolean parallelOptimization; - public JUnitCoreParameters( Map properties ) - { - parallel = property( properties, PARALLEL_KEY, "none" ).toLowerCase(); - perCoreThreadCount = property( properties, PERCORETHREADCOUNT_KEY, true ); - threadCount = property( properties, THREADCOUNT_KEY, 0 ); - threadCountMethods = property( properties, THREADCOUNTMETHODS_KEY, 0 ); - threadCountClasses = property( properties, THREADCOUNTCLASSES_KEY, 0 ); - threadCountSuites = property( properties, THREADCOUNTSUITES_KEY, 0 ); - useUnlimitedThreads = property( properties, USEUNLIMITEDTHREADS_KEY, false ); - parallelTestsTimeoutInSeconds = Math.max( property( properties, PARALLEL_TIMEOUT_KEY, 0d ), 0 ); - parallelTestsTimeoutForcedInSeconds = Math.max( property( properties, PARALLEL_TIMEOUTFORCED_KEY, 0d ), 0 ); - parallelOptimization = property( properties, PARALLEL_OPTIMIZE_KEY, true ); - } - - private static Collection lowerCase( String... elements ) - { + public JUnitCoreParameters(Map properties) { + parallel = property(properties, PARALLEL_KEY, "none").toLowerCase(); + perCoreThreadCount = property(properties, PERCORETHREADCOUNT_KEY, true); + threadCount = property(properties, THREADCOUNT_KEY, 0); + threadCountMethods = property(properties, THREADCOUNTMETHODS_KEY, 0); + threadCountClasses = property(properties, THREADCOUNTCLASSES_KEY, 0); + threadCountSuites = property(properties, THREADCOUNTSUITES_KEY, 0); + useUnlimitedThreads = property(properties, USEUNLIMITEDTHREADS_KEY, false); + parallelTestsTimeoutInSeconds = Math.max(property(properties, PARALLEL_TIMEOUT_KEY, 0d), 0); + parallelTestsTimeoutForcedInSeconds = Math.max(property(properties, PARALLEL_TIMEOUTFORCED_KEY, 0d), 0); + parallelOptimization = property(properties, PARALLEL_OPTIMIZE_KEY, true); + } + + private static Collection lowerCase(String... elements) { ArrayList lowerCase = new ArrayList<>(); - for ( String element : elements ) - { - lowerCase.add( element.toLowerCase() ); + for (String element : elements) { + lowerCase.add(element.toLowerCase()); } return lowerCase; } - private boolean isAllParallel() - { - return "all".equals( parallel ); + private boolean isAllParallel() { + return "all".equals(parallel); } - public boolean isParallelMethods() - { - return isAllParallel() || lowerCase( "both", "methods", "suitesAndMethods", "classesAndMethods" ).contains( - parallel ); + public boolean isParallelMethods() { + return isAllParallel() + || lowerCase("both", "methods", "suitesAndMethods", "classesAndMethods") + .contains(parallel); } - public boolean isParallelClasses() - { - return isAllParallel() || lowerCase( "both", "classes", "suitesAndClasses", "classesAndMethods" ).contains( - parallel ); + public boolean isParallelClasses() { + return isAllParallel() + || lowerCase("both", "classes", "suitesAndClasses", "classesAndMethods") + .contains(parallel); } - public boolean isParallelSuites() - { - return isAllParallel() || lowerCase( "suites", "suitesAndClasses", "suitesAndMethods" ).contains( parallel ); + public boolean isParallelSuites() { + return isAllParallel() + || lowerCase("suites", "suitesAndClasses", "suitesAndMethods").contains(parallel); } /** @@ -121,93 +134,77 @@ public boolean isParallelSuites() * @return {@code true} if classes and methods are both parallel */ @Deprecated - @SuppressWarnings( "unused" ) - public boolean isParallelBoth() - { + @SuppressWarnings("unused") + public boolean isParallelBoth() { return isParallelMethods() && isParallelClasses(); } - public boolean isPerCoreThreadCount() - { + public boolean isPerCoreThreadCount() { return perCoreThreadCount; } - public int getThreadCount() - { + public int getThreadCount() { return threadCount; } - public int getThreadCountMethods() - { + public int getThreadCountMethods() { return threadCountMethods; } - public int getThreadCountClasses() - { + public int getThreadCountClasses() { return threadCountClasses; } - public int getThreadCountSuites() - { + public int getThreadCountSuites() { return threadCountSuites; } - public boolean isUseUnlimitedThreads() - { + public boolean isUseUnlimitedThreads() { return useUnlimitedThreads; } - public double getParallelTestsTimeoutInSeconds() - { + public double getParallelTestsTimeoutInSeconds() { return parallelTestsTimeoutInSeconds; } - public double getParallelTestsTimeoutForcedInSeconds() - { + public double getParallelTestsTimeoutForcedInSeconds() { return parallelTestsTimeoutForcedInSeconds; } - public boolean isNoThreading() - { + public boolean isNoThreading() { return !isParallelismSelected(); } - public boolean isParallelismSelected() - { + public boolean isParallelismSelected() { return isParallelSuites() || isParallelClasses() || isParallelMethods(); } - public boolean isParallelOptimization() - { + public boolean isParallelOptimization() { return parallelOptimization; } @Override - public String toString() - { + public String toString() { return "parallel='" + parallel + '\'' + ", perCoreThreadCount=" + perCoreThreadCount + ", threadCount=" - + threadCount + ", useUnlimitedThreads=" + useUnlimitedThreads + ", threadCountSuites=" + threadCountSuites - + ", threadCountClasses=" + threadCountClasses + ", threadCountMethods=" + threadCountMethods - + ", parallelOptimization=" + parallelOptimization; + + threadCount + ", useUnlimitedThreads=" + useUnlimitedThreads + ", threadCountSuites=" + + threadCountSuites + + ", threadCountClasses=" + threadCountClasses + ", threadCountMethods=" + threadCountMethods + + ", parallelOptimization=" + parallelOptimization; } - private static boolean property( Map properties, String key, boolean fallback ) - { - return properties.containsKey( key ) ? Boolean.valueOf( properties.get( key ) ) : fallback; + private static boolean property(Map properties, String key, boolean fallback) { + return properties.containsKey(key) ? Boolean.valueOf(properties.get(key)) : fallback; } - private static String property( Map properties, String key, String fallback ) - { - return properties.containsKey( key ) ? properties.get( key ) : fallback; + private static String property(Map properties, String key, String fallback) { + return properties.containsKey(key) ? properties.get(key) : fallback; } - private static int property( Map properties, String key, int fallback ) - { - return properties.containsKey( key ) ? Integer.valueOf( properties.get( key ) ) : fallback; + private static int property(Map properties, String key, int fallback) { + return properties.containsKey(key) ? Integer.valueOf(properties.get(key)) : fallback; } - private static double property( Map properties, String key, double fallback ) - { - return properties.containsKey( key ) ? Double.valueOf( properties.get( key ) ) : fallback; + private static double property(Map properties, String key, double fallback) { + return properties.containsKey(key) ? Double.valueOf(properties.get(key)) : fallback; } } diff --git a/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/JUnitCoreProvider.java b/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/JUnitCoreProvider.java index 7ed483426f..a02657b527 100644 --- a/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/JUnitCoreProvider.java +++ b/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/JUnitCoreProvider.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.junitcore; /* @@ -59,10 +77,8 @@ /** * @author Kristian Rosenvold */ -@SuppressWarnings( { "UnusedDeclaration" } ) -public class JUnitCoreProvider - extends AbstractProvider -{ +@SuppressWarnings({"UnusedDeclaration"}) +public class JUnitCoreProvider extends AbstractProvider { private final ClassLoader testClassLoader; private final JUnitCoreParameters jUnitCoreParameters; @@ -87,211 +103,174 @@ public class JUnitCoreProvider private TestsToRun testsToRun; - public JUnitCoreProvider( ProviderParameters bootParams ) - { + public JUnitCoreProvider(ProviderParameters bootParams) { // don't start a thread in CommandReader while we are in in-plugin process commandsReader = bootParams.isInsideFork() ? bootParams.getCommandReader() : null; providerParameters = bootParams; testClassLoader = bootParams.getTestClassLoader(); scanResult = bootParams.getScanResult(); runOrderCalculator = bootParams.getRunOrderCalculator(); - jUnitCoreParameters = new JUnitCoreParameters( bootParams.getProviderProperties() ); - scannerFilter = new JUnit48TestChecker( testClassLoader ); + jUnitCoreParameters = new JUnitCoreParameters(bootParams.getProviderProperties()); + scannerFilter = new JUnit48TestChecker(testClassLoader); testResolver = bootParams.getTestRequest().getTestListResolver(); rerunFailingTestsCount = bootParams.getTestRequest().getRerunFailingTestsCount(); - customRunListeners = bootParams.getProviderProperties().get( "listener" ); - jUnit48Reflector = new JUnit48Reflector( testClassLoader ); + customRunListeners = bootParams.getProviderProperties().get("listener"); + jUnit48Reflector = new JUnit48Reflector(testClassLoader); } @Override - public Iterable> getSuites() - { + public Iterable> getSuites() { testsToRun = scanClassPath(); return testsToRun; } - private boolean isSingleThreaded() - { + private boolean isSingleThreaded() { return jUnitCoreParameters.isNoThreading(); } @Override - public RunResult invoke( Object forkTestSet ) - throws TestSetFailedException - { + public RunResult invoke(Object forkTestSet) throws TestSetFailedException { ReporterFactory reporterFactory = providerParameters.getReporterFactory(); - JUnit4RunListener listener = createRunListener( reporterFactory ); - listener.setRunMode( NORMAL_RUN ); + JUnit4RunListener listener = createRunListener(reporterFactory); + listener.setRunMode(NORMAL_RUN); ConsoleLogger logger = listener.getConsoleLogger(); - Notifier notifier = new Notifier( listener, getSkipAfterFailureCount() ); + Notifier notifier = new Notifier(listener, getSkipAfterFailureCount()); // startCapture() called in createRunListener() in prior to setTestsToRun() Filter filter = jUnit48Reflector.isJUnit48Available() ? createJUnit48Filter() : null; - if ( testsToRun == null ) - { - setTestsToRun( forkTestSet ); + if (testsToRun == null) { + setTestsToRun(forkTestSet); } // Add test failure listener JUnitTestFailureListener testFailureListener = new JUnitTestFailureListener(); - notifier.addListener( testFailureListener ); + notifier.addListener(testFailureListener); - if ( isFailFast() && commandsReader != null ) - { - registerPleaseStopJUnitListener( notifier ); + if (isFailFast() && commandsReader != null) { + registerPleaseStopJUnitListener(notifier); } final RunResult runResult; - try - { - JUnitCoreWrapper core = new JUnitCoreWrapper( notifier, jUnitCoreParameters, logger ); + try { + JUnitCoreWrapper core = new JUnitCoreWrapper(notifier, jUnitCoreParameters, logger); - if ( commandsReader != null ) - { - registerShutdownListener( testsToRun ); + if (commandsReader != null) { + registerShutdownListener(testsToRun); commandsReader.awaitStarted(); } - notifier.asFailFast( isFailFast() ); - core.execute( testsToRun, createCustomListeners( customRunListeners ), filter ); - notifier.asFailFast( false ); + notifier.asFailFast(isFailFast()); + core.execute(testsToRun, createCustomListeners(customRunListeners), filter); + notifier.asFailFast(false); // Rerun failing tests if rerunFailingTestsCount is larger than 0 - if ( isRerunFailingTests() ) - { - listener.setRunMode( RERUN_TEST_AFTER_FAILURE ); + if (isRerunFailingTests()) { + listener.setRunMode(RERUN_TEST_AFTER_FAILURE); Notifier rerunNotifier = pureNotifier(); - notifier.copyListenersTo( rerunNotifier ); - JUnitCoreWrapper rerunCore = new JUnitCoreWrapper( rerunNotifier, jUnitCoreParameters, logger ); - for ( int i = 0; i < rerunFailingTestsCount && !testFailureListener.getAllFailures().isEmpty(); i++ ) - { - Set failures = generateFailingTestDescriptions( testFailureListener.getAllFailures() ); + notifier.copyListenersTo(rerunNotifier); + JUnitCoreWrapper rerunCore = new JUnitCoreWrapper(rerunNotifier, jUnitCoreParameters, logger); + for (int i = 0; + i < rerunFailingTestsCount + && !testFailureListener.getAllFailures().isEmpty(); + i++) { + Set failures = generateFailingTestDescriptions(testFailureListener.getAllFailures()); testFailureListener.reset(); - FilterFactory filterFactory = new FilterFactory( testClassLoader ); - Filter failureDescriptionFilter = filterFactory.createMatchAnyDescriptionFilter( failures ); - rerunCore.execute( testsToRun, failureDescriptionFilter ); + FilterFactory filterFactory = new FilterFactory(testClassLoader); + Filter failureDescriptionFilter = filterFactory.createMatchAnyDescriptionFilter(failures); + rerunCore.execute(testsToRun, failureDescriptionFilter); } } - } - finally - { + } finally { runResult = reporterFactory.close(); notifier.removeListeners(); } return runResult; } - private void setTestsToRun( Object forkTestSet ) - throws TestSetFailedException - { - if ( forkTestSet instanceof TestsToRun ) - { + private void setTestsToRun(Object forkTestSet) throws TestSetFailedException { + if (forkTestSet instanceof TestsToRun) { testsToRun = (TestsToRun) forkTestSet; - } - else if ( forkTestSet instanceof Class ) - { + } else if (forkTestSet instanceof Class) { Class theClass = (Class) forkTestSet; - testsToRun = fromClass( theClass ); - } - else - { + testsToRun = fromClass(theClass); + } else { testsToRun = scanClassPath(); } } - private boolean isRerunFailingTests() - { + private boolean isRerunFailingTests() { return rerunFailingTestsCount > 0; } - private boolean isFailFast() - { + private boolean isFailFast() { return providerParameters.getSkipAfterFailureCount() > 0; } - private int getSkipAfterFailureCount() - { + private int getSkipAfterFailureCount() { return isFailFast() ? providerParameters.getSkipAfterFailureCount() : 0; } - private void registerShutdownListener( final TestsToRun testsToRun ) - { - commandsReader.addShutdownListener( new CommandListener() - { + private void registerShutdownListener(final TestsToRun testsToRun) { + commandsReader.addShutdownListener(new CommandListener() { @Override - public void update( Command command ) - { + public void update(Command command) { testsToRun.markTestSetFinished(); } - } ); + }); } - private void registerPleaseStopJUnitListener( final Notifier stoppable ) - { - commandsReader.addSkipNextTestsListener( new CommandListener() - { + private void registerPleaseStopJUnitListener(final Notifier stoppable) { + commandsReader.addSkipNextTestsListener(new CommandListener() { @Override - public void update( Command command ) - { + public void update(Command command) { stoppable.pleaseStop(); } - } ); + }); } - private JUnit4RunListener createRunListener( ReporterFactory reporterFactory ) - { + private JUnit4RunListener createRunListener(ReporterFactory reporterFactory) { final JUnit4RunListener listener; - if ( isSingleThreaded() ) - { - listener = new NonConcurrentRunListener( reporterFactory.createTestReportListener() ); - } - else - { + if (isSingleThreaded()) { + listener = new NonConcurrentRunListener(reporterFactory.createTestReportListener()); + } else { Map testSetMap = new ConcurrentHashMap<>(); boolean parallelClasses = isParallelTypes(); boolean parallelBoth = isParallelMethodsAndTypes(); ConcurrentRunListener concurrentListener = - createInstance( testSetMap, reporterFactory, parallelClasses, parallelBoth ); - listener = new JUnitCoreRunListener( concurrentListener, testSetMap ); + createInstance(testSetMap, reporterFactory, parallelClasses, parallelBoth); + listener = new JUnitCoreRunListener(concurrentListener, testSetMap); } - startCapture( listener ); + startCapture(listener); return listener; } - private boolean isParallelMethodsAndTypes() - { + private boolean isParallelMethodsAndTypes() { return jUnitCoreParameters.isParallelMethods() && isParallelTypes(); } - private boolean isParallelTypes() - { + private boolean isParallelTypes() { return jUnitCoreParameters.isParallelClasses() || jUnitCoreParameters.isParallelSuites(); } - private Filter createJUnit48Filter() - { - final FilterFactory factory = new FilterFactory( testClassLoader ); + private Filter createJUnit48Filter() { + final FilterFactory factory = new FilterFactory(testClassLoader); Map props = providerParameters.getProviderProperties(); - Filter groupFilter = factory.canCreateGroupFilter( props ) ? factory.createGroupFilter( props ) : null; - TestListResolver methodFilter = optionallyWildcardFilter( testResolver ); + Filter groupFilter = factory.canCreateGroupFilter(props) ? factory.createGroupFilter(props) : null; + TestListResolver methodFilter = optionallyWildcardFilter(testResolver); boolean onlyGroups = methodFilter.isEmpty() || methodFilter.isWildcard(); - if ( onlyGroups ) - { + if (onlyGroups) { return groupFilter; - } - else - { - Filter jUnitMethodFilter = factory.createMethodFilter( methodFilter ); - return groupFilter == null ? jUnitMethodFilter : factory.and( groupFilter, jUnitMethodFilter ); + } else { + Filter jUnitMethodFilter = factory.createMethodFilter(methodFilter); + return groupFilter == null ? jUnitMethodFilter : factory.and(groupFilter, jUnitMethodFilter); } } - private TestsToRun scanClassPath() - { - TestsToRun scanned = scanResult.applyFilter( scannerFilter, testClassLoader ); - return runOrderCalculator.orderTestClasses( scanned ); + private TestsToRun scanClassPath() { + TestsToRun scanned = scanResult.applyFilter(scannerFilter, testClassLoader); + return runOrderCalculator.orderTestClasses(scanned); } } diff --git a/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/JUnitCoreRunListener.java b/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/JUnitCoreRunListener.java index f4fd0a961b..8ef9b3b19d 100644 --- a/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/JUnitCoreRunListener.java +++ b/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/JUnitCoreRunListener.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.junitcore; /* @@ -39,18 +57,15 @@ * * @see org.apache.maven.surefire.junitcore.ConcurrentRunListener for details about parallel running */ -final class JUnitCoreRunListener - extends JUnit4RunListener -{ +final class JUnitCoreRunListener extends JUnit4RunListener { private final Map classMethodCounts; /** * @param reporter the report manager to log testing events to * @param classMethodCounts A map of methods */ - JUnitCoreRunListener( ConcurrentRunListener reporter, Map classMethodCounts ) - { - super( reporter ); + JUnitCoreRunListener(ConcurrentRunListener reporter, Map classMethodCounts) { + super(reporter); this.classMethodCounts = classMethodCounts; } @@ -60,68 +75,49 @@ final class JUnitCoreRunListener * @see org.junit.runner.notification.RunListener#testRunStarted(org.junit.runner.Description) */ @Override - public void testRunStarted( Description description ) - throws Exception - { - fillTestCountMap( description ); - reporter.testSetStarting( null ); // Not entirely meaningful as we can see + public void testRunStarted(Description description) throws Exception { + fillTestCountMap(description); + reporter.testSetStarting(null); // Not entirely meaningful as we can see } @Override - public void testRunFinished( Result result ) - throws Exception - { - try - { - reporter.testSetCompleted( null ); - } - finally - { + public void testRunFinished(Result result) throws Exception { + try { + reporter.testSetCompleted(null); + } finally { classMethodCounts.clear(); } } - private void fillTestCountMap( Description testDesc ) - { - for ( Description child : testDesc.getChildren() ) - { - if ( !asTestLeaf( child ) ) - { - fillTestCountMap( child ); + private void fillTestCountMap(Description testDesc) { + for (Description child : testDesc.getChildren()) { + if (!asTestLeaf(child)) { + fillTestCountMap(child); } } } - private boolean asTestLeaf( Description description ) - { - if ( description.isTest() ) - { - final String testClassName = extractClassName( description.getDisplayName() ); - if ( testClassName != null ) - { + private boolean asTestLeaf(Description description) { + if (description.isTest()) { + final String testClassName = extractClassName(description.getDisplayName()); + if (testClassName != null) { final TestSet testSet; - if ( classMethodCounts.containsKey( testClassName ) ) - { - testSet = classMethodCounts.get( testClassName ); - } - else - { - testSet = new TestSet( testClassName, getRunMode(), classMethodIndexer ); - classMethodCounts.put( testClassName, testSet ); + if (classMethodCounts.containsKey(testClassName)) { + testSet = classMethodCounts.get(testClassName); + } else { + testSet = new TestSet(testClassName, getRunMode(), classMethodIndexer); + classMethodCounts.put(testClassName, testSet); } testSet.incrementTestMethodCount(); } return true; - } - else - { + } else { return false; } } @Override - protected StackTraceWriter createStackTraceWriter( Failure failure ) - { - return new JUnit4StackTraceWriter( failure ); + protected StackTraceWriter createStackTraceWriter(Failure failure) { + return new JUnit4StackTraceWriter(failure); } } diff --git a/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/JUnitCoreWrapper.java b/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/JUnitCoreWrapper.java index 3ae0b48e1f..26ae80b02e 100644 --- a/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/JUnitCoreWrapper.java +++ b/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/JUnitCoreWrapper.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.junitcore; /* @@ -19,6 +37,11 @@ * under the License. */ +import java.util.Collection; +import java.util.Collections; +import java.util.Iterator; +import java.util.Queue; + import org.apache.maven.plugin.surefire.log.api.ConsoleLogger; import org.apache.maven.surefire.api.testset.TestSetFailedException; import org.apache.maven.surefire.api.util.TestsToRun; @@ -34,11 +57,6 @@ import org.junit.runner.notification.RunListener; import org.junit.runner.notification.StoppedByUserException; -import java.util.Collection; -import java.util.Collections; -import java.util.Iterator; -import java.util.Queue; - import static org.apache.maven.surefire.common.junit4.JUnit4Reflector.createDescription; import static org.apache.maven.surefire.common.junit4.JUnit4Reflector.createIgnored; import static org.apache.maven.surefire.common.junit4.JUnit4RunListener.rethrowAnyTestMechanismFailures; @@ -50,162 +68,128 @@ * * @author Kristian Rosenvold */ -final class JUnitCoreWrapper -{ +final class JUnitCoreWrapper { private final Notifier notifier; private final JUnitCoreParameters jUnitCoreParameters; private final ConsoleLogger consoleStream; - JUnitCoreWrapper( Notifier notifier, JUnitCoreParameters jUnitCoreParameters, ConsoleLogger consoleStream ) - { + JUnitCoreWrapper(Notifier notifier, JUnitCoreParameters jUnitCoreParameters, ConsoleLogger consoleStream) { this.notifier = notifier; this.jUnitCoreParameters = jUnitCoreParameters; this.consoleStream = consoleStream; } - void execute( TestsToRun testsToRun, Filter filter ) - throws TestSetFailedException - { - execute( testsToRun, true, Collections.emptyList(), filter ); + void execute(TestsToRun testsToRun, Filter filter) throws TestSetFailedException { + execute(testsToRun, true, Collections.emptyList(), filter); } - void execute( TestsToRun testsToRun, Collection listeners, Filter filter ) - throws TestSetFailedException - { - execute( testsToRun, false, listeners, filter ); + void execute(TestsToRun testsToRun, Collection listeners, Filter filter) + throws TestSetFailedException { + execute(testsToRun, false, listeners, filter); } - private void execute( TestsToRun testsToRun, boolean useIterated, Collection listeners, Filter filter ) - throws TestSetFailedException - { - if ( testsToRun.allowEagerReading() ) - { - executeEager( testsToRun, filter, listeners ); - } - else - { - executeLazy( testsToRun, useIterated, filter, listeners ); + private void execute(TestsToRun testsToRun, boolean useIterated, Collection listeners, Filter filter) + throws TestSetFailedException { + if (testsToRun.allowEagerReading()) { + executeEager(testsToRun, filter, listeners); + } else { + executeLazy(testsToRun, useIterated, filter, listeners); } } - private JUnitCore createJUnitCore( Notifier notifier, Collection listeners ) - { + private JUnitCore createJUnitCore(Notifier notifier, Collection listeners) { JUnitCore junitCore = new JUnitCore(); // custom listeners added last - notifier.addListeners( listeners ); + notifier.addListeners(listeners); return junitCore; } - private void executeEager( TestsToRun testsToRun, Filter filter, Collection listeners ) - throws TestSetFailedException - { - JUnitCore junitCore = createJUnitCore( notifier, listeners ); + private void executeEager(TestsToRun testsToRun, Filter filter, Collection listeners) + throws TestSetFailedException { + JUnitCore junitCore = createJUnitCore(notifier, listeners); Class[] tests = testsToRun.getLocatedClasses(); Computer computer = createComputer(); - createRequestAndRun( filter, computer, junitCore.withReportedTests( tests ), tests ); + createRequestAndRun(filter, computer, junitCore.withReportedTests(tests), tests); } - private void executeLazy( TestsToRun testsToRun, boolean useIterated, Filter filter, - Collection listeners ) - throws TestSetFailedException - { - JUnitCore junitCore = createJUnitCore( notifier, listeners ); - for ( Iterator> it = useIterated ? testsToRun.iterated() : testsToRun.iterator(); it.hasNext(); ) - { + private void executeLazy( + TestsToRun testsToRun, boolean useIterated, Filter filter, Collection listeners) + throws TestSetFailedException { + JUnitCore junitCore = createJUnitCore(notifier, listeners); + for (Iterator> it = useIterated ? testsToRun.iterated() : testsToRun.iterator(); it.hasNext(); ) { Class clazz = it.next(); Computer computer = createComputer(); - createRequestAndRun( filter, computer, junitCore.withReportedTests( clazz ), clazz ); + createRequestAndRun(filter, computer, junitCore.withReportedTests(clazz), clazz); } } - private void createRequestAndRun( Filter filter, Computer computer, JUnitCore junitCore, Class... classesToRun ) - throws TestSetFailedException - { - Request req = classes( computer, classesToRun ); - if ( filter != null ) - { - req = new FilteringRequest( req, filter ); - if ( req.getRunner() == null ) - { + private void createRequestAndRun(Filter filter, Computer computer, JUnitCore junitCore, Class... classesToRun) + throws TestSetFailedException { + Request req = classes(computer, classesToRun); + if (filter != null) { + req = new FilteringRequest(req, filter); + if (req.getRunner() == null) { // nothing to run return; } } - Result run = junitCore.run( req.getRunner() ); - rethrowAnyTestMechanismFailures( run ); + Result run = junitCore.run(req.getRunner()); + rethrowAnyTestMechanismFailures(run); - if ( computer instanceof ParallelComputer ) - { - String timeoutMessage = ( (ParallelComputer) computer ).describeElapsedTimeout(); - if ( !timeoutMessage.isEmpty() ) - { - throw new TestSetFailedException( timeoutMessage ); + if (computer instanceof ParallelComputer) { + String timeoutMessage = ((ParallelComputer) computer).describeElapsedTimeout(); + if (!timeoutMessage.isEmpty()) { + throw new TestSetFailedException(timeoutMessage); } } } - private Computer createComputer() - { + private Computer createComputer() { return jUnitCoreParameters.isNoThreading() - ? serial() - : new ParallelComputerBuilder( consoleStream, jUnitCoreParameters ).buildComputer(); + ? serial() + : new ParallelComputerBuilder(consoleStream, jUnitCoreParameters).buildComputer(); } - private final class JUnitCore - extends org.apache.maven.surefire.junitcore.JUnitCore - { - JUnitCore() - { - super( JUnitCoreWrapper.this.notifier ); + private final class JUnitCore extends org.apache.maven.surefire.junitcore.JUnitCore { + JUnitCore() { + super(JUnitCoreWrapper.this.notifier); } - JUnitCore withReportedTests( Class... tests ) - { + JUnitCore withReportedTests(Class... tests) { Queue stoppedTests = JUnitCoreWrapper.this.notifier.getRemainingTestClasses(); - if ( stoppedTests != null ) - { - for ( Class test : tests ) - { - stoppedTests.add( test.getName() ); + if (stoppedTests != null) { + for (Class test : tests) { + stoppedTests.add(test.getName()); } } return this; } @Override - @SuppressWarnings( "checkstyle:innerassignment" ) - protected void afterException( Throwable e ) - throws TestSetFailedException - { - if ( JUnitCoreWrapper.this.notifier.isFailFast() && e instanceof StoppedByUserException ) - { + @SuppressWarnings("checkstyle:innerassignment") + protected void afterException(Throwable e) throws TestSetFailedException { + if (JUnitCoreWrapper.this.notifier.isFailFast() && e instanceof StoppedByUserException) { Queue stoppedTests = JUnitCoreWrapper.this.notifier.getRemainingTestClasses(); - if ( stoppedTests != null ) - { + if (stoppedTests != null) { String reason = e.getClass().getName(); - Ignore reasonForSkippedTest = createIgnored( reason ); - for ( String clazz; ( clazz = stoppedTests.poll() ) != null; ) - { - Description skippedTest = createDescription( clazz, reasonForSkippedTest ); - JUnitCoreWrapper.this.notifier.fireTestIgnored( skippedTest ); + Ignore reasonForSkippedTest = createIgnored(reason); + for (String clazz; (clazz = stoppedTests.poll()) != null; ) { + Description skippedTest = createDescription(clazz, reasonForSkippedTest); + JUnitCoreWrapper.this.notifier.fireTestIgnored(skippedTest); } } - } - else - { - super.afterException( e ); + } else { + super.afterException(e); } } @Override - protected void afterFinished() - { + protected void afterFinished() { Queue stoppedTests = JUnitCoreWrapper.this.notifier.getRemainingTestClasses(); - if ( stoppedTests != null ) - { + if (stoppedTests != null) { stoppedTests.clear(); } } diff --git a/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/LogicalStream.java b/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/LogicalStream.java index a7bcc6d3da..8b40982646 100644 --- a/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/LogicalStream.java +++ b/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/LogicalStream.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.junitcore; /* @@ -29,20 +47,16 @@ * A stream-like object that preserves ordering between stdout/stderr */ @Deprecated // remove this class after StatelessXmlReporter is capable of parallel test sets processing -final class LogicalStream -{ +final class LogicalStream { private final Queue output = new ConcurrentLinkedQueue<>(); - synchronized void write( TestOutputReportEntry reportEntry ) - { - output.add( reportEntry ); + synchronized void write(TestOutputReportEntry reportEntry) { + output.add(reportEntry); } - void writeDetails( TestOutputReceiver outputReceiver ) - { - for ( TestOutputReportEntry entry = output.poll(); entry != null; entry = output.poll() ) - { - outputReceiver.writeTestOutput( entry ); + void writeDetails(TestOutputReceiver outputReceiver) { + for (TestOutputReportEntry entry = output.poll(); entry != null; entry = output.poll()) { + outputReceiver.writeTestOutput(entry); } } } diff --git a/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/MethodsParallelRunListener.java b/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/MethodsParallelRunListener.java index 822fb80f98..2afb3b29e6 100644 --- a/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/MethodsParallelRunListener.java +++ b/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/MethodsParallelRunListener.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.junitcore; /* @@ -19,37 +37,30 @@ * under the License. */ -import org.apache.maven.surefire.api.report.ReporterFactory; - import java.util.Map; +import org.apache.maven.surefire.api.report.ReporterFactory; + /** * @author Kristian Rosenvold */ @Deprecated // remove this class after StatelessXmlReporter is capable of parallel test sets processing -final class MethodsParallelRunListener - extends ConcurrentRunListener -{ +final class MethodsParallelRunListener extends ConcurrentRunListener { private volatile TestSet lastStarted; private final Object lock = new Object(); - MethodsParallelRunListener( Map classMethodCounts, ReporterFactory reporterFactory, - boolean reportImmediately ) - { - super( reporterFactory, reportImmediately, classMethodCounts ); + MethodsParallelRunListener( + Map classMethodCounts, ReporterFactory reporterFactory, boolean reportImmediately) { + super(reporterFactory, reportImmediately, classMethodCounts); } @Override - protected void checkIfTestSetCanBeReported( TestSet testSetForTest ) - { - synchronized ( lock ) - { - if ( testSetForTest != lastStarted ) - { - if ( lastStarted != null ) - { - lastStarted.setAllScheduled( getRunListener() ); + protected void checkIfTestSetCanBeReported(TestSet testSetForTest) { + synchronized (lock) { + if (testSetForTest != lastStarted) { + if (lastStarted != null) { + lastStarted.setAllScheduled(getRunListener()); } lastStarted = testSetForTest; } diff --git a/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/NonConcurrentRunListener.java b/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/NonConcurrentRunListener.java index 445407f23f..34755fda67 100644 --- a/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/NonConcurrentRunListener.java +++ b/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/NonConcurrentRunListener.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.junitcore; /* @@ -19,21 +37,21 @@ * under the License. */ +import java.util.Collections; +import java.util.Map; + +import org.apache.maven.surefire.api.report.SimpleReportEntry; import org.apache.maven.surefire.api.report.TestOutputReportEntry; import org.apache.maven.surefire.api.report.TestReportListener; +import org.apache.maven.surefire.api.report.TestSetReportEntry; import org.apache.maven.surefire.api.util.internal.ClassMethod; import org.apache.maven.surefire.common.junit4.JUnit4RunListener; -import org.apache.maven.surefire.api.report.SimpleReportEntry; -import org.apache.maven.surefire.api.report.TestSetReportEntry; import org.junit.runner.Description; import org.junit.runner.Result; import org.junit.runner.notification.Failure; -import java.util.Collections; -import java.util.Map; - -import static org.apache.maven.surefire.common.junit4.JUnit4ProviderUtil.toClassMethod; import static org.apache.maven.surefire.api.util.internal.ObjectUtils.systemProps; +import static org.apache.maven.surefire.common.junit4.JUnit4ProviderUtil.toClassMethod; /** * A class to be used when there is no JUnit parallelism (methods or/and class). This allows to workaround JUnit @@ -42,70 +60,54 @@ * forkCount greater than one. */ @Deprecated // remove this class after StatelessXmlReporter is capable of parallel test sets processing -class NonConcurrentRunListener - extends JUnit4RunListener -{ +class NonConcurrentRunListener extends JUnit4RunListener { private Description currentTestSetDescription; private Description lastFinishedDescription; - NonConcurrentRunListener( TestReportListener reporter ) - { - super( reporter ); + NonConcurrentRunListener(TestReportListener reporter) { + super(reporter); } - private TestSetReportEntry createReportEntryForTestSet( Description description, Map systemProps ) - { - ClassMethod classMethod = toClassMethod( description ); + private TestSetReportEntry createReportEntryForTestSet(Description description, Map systemProps) { + ClassMethod classMethod = toClassMethod(description); String className = classMethod.getClazz(); String methodName = classMethod.getMethod(); - long testRunId = classMethodIndexer.indexClassMethod( className, methodName ); - return new SimpleReportEntry( getRunMode(), testRunId, className, null, null, null, systemProps ); + long testRunId = classMethodIndexer.indexClassMethod(className, methodName); + return new SimpleReportEntry(getRunMode(), testRunId, className, null, null, null, systemProps); } - private TestSetReportEntry createTestSetReportEntryStarted( Description description ) - { - return createReportEntryForTestSet( description, Collections.emptyMap() ); + private TestSetReportEntry createTestSetReportEntryStarted(Description description) { + return createReportEntryForTestSet(description, Collections.emptyMap()); } - private TestSetReportEntry createTestSetReportEntryFinished( Description description ) - { - return createReportEntryForTestSet( description, systemProps() ); + private TestSetReportEntry createTestSetReportEntryFinished(Description description) { + return createReportEntryForTestSet(description, systemProps()); } @Override - public void testStarted( Description description ) - throws Exception - { - finishLastTestSetIfNecessary( description ); - super.testStarted( description ); + public void testStarted(Description description) throws Exception { + finishLastTestSetIfNecessary(description); + super.testStarted(description); } - private void finishLastTestSetIfNecessary( Description description ) - { - if ( describesNewTestSet( description ) ) - { + private void finishLastTestSetIfNecessary(Description description) { + if (describesNewTestSet(description)) { currentTestSetDescription = description; - if ( lastFinishedDescription != null ) - { - reporter.testSetCompleted( createTestSetReportEntryFinished( lastFinishedDescription ) ); + if (lastFinishedDescription != null) { + reporter.testSetCompleted(createTestSetReportEntryFinished(lastFinishedDescription)); lastFinishedDescription = null; } - reporter.testSetStarting( createTestSetReportEntryStarted( description ) ); + reporter.testSetStarting(createTestSetReportEntryStarted(description)); } } - private boolean describesNewTestSet( Description description ) - { - if ( currentTestSetDescription != null ) - { - if ( null != description.getTestClass() ) - { - return !description.getTestClass().equals( currentTestSetDescription.getTestClass() ); - } - else if ( description.isSuite() ) - { - return description.getChildren().equals( currentTestSetDescription.getChildren() ); + private boolean describesNewTestSet(Description description) { + if (currentTestSetDescription != null) { + if (null != description.getTestClass()) { + return !description.getTestClass().equals(currentTestSetDescription.getTestClass()); + } else if (description.isSuite()) { + return description.getChildren().equals(currentTestSetDescription.getChildren()); } return false; @@ -115,55 +117,42 @@ else if ( description.isSuite() ) } @Override - public void testFinished( Description description ) - throws Exception - { - super.testFinished( description ); + public void testFinished(Description description) throws Exception { + super.testFinished(description); lastFinishedDescription = description; } @Override - public void testIgnored( Description description ) - throws Exception - { - finishLastTestSetIfNecessary( description ); + public void testIgnored(Description description) throws Exception { + finishLastTestSetIfNecessary(description); - super.testIgnored( description ); + super.testIgnored(description); lastFinishedDescription = description; } @Override - public void testFailure( Failure failure ) - throws Exception - { - finishLastTestSetIfNecessary( failure.getDescription() ); + public void testFailure(Failure failure) throws Exception { + finishLastTestSetIfNecessary(failure.getDescription()); - super.testFailure( failure ); + super.testFailure(failure); lastFinishedDescription = failure.getDescription(); } @Override - public void testAssumptionFailure( Failure failure ) - { - finishLastTestSetIfNecessary( failure.getDescription() ); + public void testAssumptionFailure(Failure failure) { + finishLastTestSetIfNecessary(failure.getDescription()); - super.testAssumptionFailure( failure ); + super.testAssumptionFailure(failure); lastFinishedDescription = failure.getDescription(); } @Override - public void testRunStarted( Description description ) - throws Exception - { - } + public void testRunStarted(Description description) throws Exception {} @Override - public void testRunFinished( Result result ) - throws Exception - { - if ( lastFinishedDescription != null ) - { - reporter.testSetCompleted( createTestSetReportEntryFinished( lastFinishedDescription ) ); + public void testRunFinished(Result result) throws Exception { + if (lastFinishedDescription != null) { + reporter.testSetCompleted(createTestSetReportEntryFinished(lastFinishedDescription)); lastFinishedDescription = null; } } diff --git a/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/SynchronousRunner.java b/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/SynchronousRunner.java index ebcbe8d85d..998e062c2f 100644 --- a/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/SynchronousRunner.java +++ b/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/SynchronousRunner.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.junitcore; /* @@ -28,17 +46,12 @@ * @author Kristian Rosenvold */ @Deprecated -class SynchronousRunner - implements RunnerScheduler -{ +class SynchronousRunner implements RunnerScheduler { @Override - public void schedule( final Runnable childStatement ) - { + public void schedule(final Runnable childStatement) { childStatement.run(); } @Override - public void finished() - { - } + public void finished() {} } diff --git a/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/TestMethod.java b/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/TestMethod.java index 142bd32b61..6cdb724d85 100644 --- a/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/TestMethod.java +++ b/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/TestMethod.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.junitcore; /* @@ -19,15 +37,15 @@ * under the License. */ +import java.util.concurrent.atomic.AtomicReference; + import org.apache.maven.surefire.api.report.CategorizedReportEntry; -import org.apache.maven.surefire.api.report.TestOutputReceiver; import org.apache.maven.surefire.api.report.ConsoleOutputReceiverForCurrentThread; import org.apache.maven.surefire.api.report.ReportEntry; +import org.apache.maven.surefire.api.report.TestOutputReceiver; import org.apache.maven.surefire.api.report.TestOutputReportEntry; import org.apache.maven.surefire.api.report.TestReportListener; -import java.util.concurrent.atomic.AtomicReference; - /** * Represents the test-state of a single test method that is run. *
    @@ -35,9 +53,7 @@ * without any actual parallel access */ @Deprecated // remove this class after StatelessXmlReporter is capable of parallel test sets processing -class TestMethod - implements TestOutputReceiver -{ +class TestMethod implements TestOutputReceiver { private static final InheritableThreadLocal TEST_METHOD = new InheritableThreadLocal<>(); private final AtomicReference output = new AtomicReference<>(); @@ -58,129 +74,106 @@ class TestMethod private volatile ReportEntry testAssumption; - TestMethod( ReportEntry description, TestSet testSet ) - { + TestMethod(ReportEntry description, TestSet testSet) { this.description = description; this.testSet = testSet; startTime = System.currentTimeMillis(); } - void testFinished() - { + void testFinished() { setEndTime(); } - void testIgnored( ReportEntry description ) - { + void testIgnored(ReportEntry description) { testIgnored = description; setEndTime(); } - void testFailure( ReportEntry failure ) - { + void testFailure(ReportEntry failure) { this.testFailure = failure; setEndTime(); } - void testError( ReportEntry failure ) - { + void testError(ReportEntry failure) { this.testError = failure; setEndTime(); } - void testAssumption( ReportEntry failure ) - { + void testAssumption(ReportEntry failure) { this.testAssumption = failure; setEndTime(); } - private void setEndTime() - { + private void setEndTime() { this.endTime = System.currentTimeMillis(); } - int getElapsed() - { - return endTime > 0 ? (int) ( endTime - startTime ) : 0; + int getElapsed() { + return endTime > 0 ? (int) (endTime - startTime) : 0; } - long getStartTime() - { + long getStartTime() { return startTime; } - long getEndTime() - { + long getEndTime() { return endTime; } - void replay( TestReportListener reporter ) - { - if ( testIgnored != null ) - { - reporter.testSkipped( createReportEntry( testIgnored ) ); - } - else - { - ReportEntry descriptionReport = createReportEntry( description ); - reporter.testStarting( descriptionReport ); + void replay(TestReportListener reporter) { + if (testIgnored != null) { + reporter.testSkipped(createReportEntry(testIgnored)); + } else { + ReportEntry descriptionReport = createReportEntry(description); + reporter.testStarting(descriptionReport); LogicalStream ls = output.get(); - if ( ls != null ) - { - ls.writeDetails( reporter ); + if (ls != null) { + ls.writeDetails(reporter); } - if ( testFailure != null ) - { - reporter.testFailed( createReportEntry( testFailure ) ); - } - else if ( testError != null ) - { - reporter.testError( createReportEntry( testError ) ); - } - else if ( testAssumption != null ) - { - reporter.testAssumptionFailure( createReportEntry( testAssumption ) ); - } - else - { - reporter.testSucceeded( descriptionReport ); + if (testFailure != null) { + reporter.testFailed(createReportEntry(testFailure)); + } else if (testError != null) { + reporter.testError(createReportEntry(testError)); + } else if (testAssumption != null) { + reporter.testAssumptionFailure(createReportEntry(testAssumption)); + } else { + reporter.testSucceeded(descriptionReport); } } } - private ReportEntry createReportEntry( ReportEntry reportEntry ) - { - return new CategorizedReportEntry( reportEntry.getRunMode(), reportEntry.getTestRunId(), - reportEntry.getSourceName(), reportEntry.getName(), reportEntry.getGroup(), - reportEntry.getStackTraceWriter(), getElapsed(), reportEntry.getMessage() ); + private ReportEntry createReportEntry(ReportEntry reportEntry) { + return new CategorizedReportEntry( + reportEntry.getRunMode(), + reportEntry.getTestRunId(), + reportEntry.getSourceName(), + reportEntry.getName(), + reportEntry.getGroup(), + reportEntry.getStackTraceWriter(), + getElapsed(), + reportEntry.getMessage()); } - void attachToThread() - { - TEST_METHOD.set( this ); - ConsoleOutputReceiverForCurrentThread.set( this ); + void attachToThread() { + TEST_METHOD.set(this); + ConsoleOutputReceiverForCurrentThread.set(this); } - void detachFromCurrentThread() - { + void detachFromCurrentThread() { TEST_METHOD.remove(); ConsoleOutputReceiverForCurrentThread.remove(); } - static TestMethod getThreadTestMethod() - { + static TestMethod getThreadTestMethod() { return TEST_METHOD.get(); } - LogicalStream getLogicalStream() - { + LogicalStream getLogicalStream() { LogicalStream ls = output.get(); - if ( ls == null ) - { + if (ls == null) { ls = new LogicalStream(); - if ( !output.compareAndSet( null, ls ) ) - { + if (!output.compareAndSet(null, ls)) { ls = output.get(); } } @@ -188,13 +181,11 @@ LogicalStream getLogicalStream() } @Override - public void writeTestOutput( TestOutputReportEntry reportEntry ) - { - getLogicalStream().write( reportEntry ); + public void writeTestOutput(TestOutputReportEntry reportEntry) { + getLogicalStream().write(reportEntry); } - TestSet getTestSet() - { + TestSet getTestSet() { return testSet; } } diff --git a/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/TestSet.java b/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/TestSet.java index f01c22d8ae..1e65841469 100644 --- a/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/TestSet.java +++ b/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/TestSet.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.junitcore; /* @@ -19,6 +37,13 @@ * under the License. */ +import java.util.Collection; +import java.util.Collections; +import java.util.Map; +import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; + import org.apache.maven.surefire.api.report.ReportEntry; import org.apache.maven.surefire.api.report.RunMode; import org.apache.maven.surefire.api.report.SimpleReportEntry; @@ -27,21 +52,13 @@ import org.apache.maven.surefire.api.report.TestSetReportEntry; import org.apache.maven.surefire.report.ClassMethodIndexer; -import java.util.Collection; -import java.util.Collections; -import java.util.Map; -import java.util.concurrent.ConcurrentLinkedQueue; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicInteger; - import static org.apache.maven.surefire.api.util.internal.ObjectUtils.systemProps; /** * * Represents the test-state of a testset that is run. */ @Deprecated // remove this class after StatelessXmlReporter is capable of parallel test sets processing -public class TestSet -{ +public class TestSet { private static final InheritableThreadLocal TEST_SET = new InheritableThreadLocal<>(); private final String testClassName; @@ -63,127 +80,111 @@ public class TestSet private volatile boolean allScheduled; - public TestSet( String testClassName, RunMode runMode, ClassMethodIndexer classMethodIndexer ) - { + public TestSet(String testClassName, RunMode runMode, ClassMethodIndexer classMethodIndexer) { this.testClassName = testClassName; this.runMode = runMode; this.classMethodIndexer = classMethodIndexer; } - final RunMode getRunMode() - { + final RunMode getRunMode() { return runMode; } - final ClassMethodIndexer getClassMethodIndexer() - { + final ClassMethodIndexer getClassMethodIndexer() { return classMethodIndexer; } - public void replay( TestReportListener target ) - { - if ( played.compareAndSet( false, true ) ) - { - try - { + public void replay(TestReportListener target) { + if (played.compareAndSet(false, true)) { + try { TestSetReportEntry report = createReportEntryStarted(); - target.testSetStarting( report ); + target.testSetStarting(report); long startTime = 0; long endTime = 0; - for ( TestMethod testMethod : testMethods ) - { - if ( startTime == 0 || testMethod.getStartTime() < startTime ) - { + for (TestMethod testMethod : testMethods) { + if (startTime == 0 || testMethod.getStartTime() < startTime) { startTime = testMethod.getStartTime(); } - if ( endTime == 0 || testMethod.getEndTime() > endTime ) - { + if (endTime == 0 || testMethod.getEndTime() > endTime) { endTime = testMethod.getEndTime(); } - testMethod.replay( target ); + testMethod.replay(target); } - int elapsed = (int) ( endTime - startTime ); + int elapsed = (int) (endTime - startTime); - report = createReportEntryCompleted( elapsed ); + report = createReportEntryCompleted(elapsed); - target.testSetCompleted( report ); - } - catch ( Exception e ) - { - throw new RuntimeException( e ); + target.testSetCompleted(report); + } catch (Exception e) { + throw new RuntimeException(e); } } } - public TestMethod createThreadAttachedTestMethod( ReportEntry description ) - { - TestMethod testMethod = new TestMethod( description, this ); - addTestMethod( testMethod ); + public TestMethod createThreadAttachedTestMethod(ReportEntry description) { + TestMethod testMethod = new TestMethod(description, this); + addTestMethod(testMethod); testMethod.attachToThread(); return testMethod; } - private TestSetReportEntry createReportEntryStarted() - { - return createReportEntry( null, Collections.emptyMap() ); + private TestSetReportEntry createReportEntryStarted() { + return createReportEntry(null, Collections.emptyMap()); } - private TestSetReportEntry createReportEntryCompleted( int elapsed ) - { - return createReportEntry( elapsed, systemProps() ); + private TestSetReportEntry createReportEntryCompleted(int elapsed) { + return createReportEntry(elapsed, systemProps()); } - private TestSetReportEntry createReportEntry( Integer elapsed, Map systemProps ) - { - return new SimpleReportEntry( runMode, classMethodIndexer.indexClass( testClassName ), testClassName, null, - testClassName, null, null, elapsed, systemProps ); + private TestSetReportEntry createReportEntry(Integer elapsed, Map systemProps) { + return new SimpleReportEntry( + runMode, + classMethodIndexer.indexClass(testClassName), + testClassName, + null, + testClassName, + null, + null, + elapsed, + systemProps); } - public void incrementTestMethodCount() - { + public void incrementTestMethodCount() { numberOfTests.incrementAndGet(); } - private void addTestMethod( TestMethod testMethod ) - { - testMethods.add( testMethod ); + private void addTestMethod(TestMethod testMethod) { + testMethods.add(testMethod); } - public void incrementFinishedTests( TestReportListener reporterManager, boolean reportImmediately ) - { + public void incrementFinishedTests(TestReportListener reporterManager, boolean reportImmediately) { numberOfCompletedChildren.incrementAndGet(); - if ( allScheduled && isAllTestsDone() && reportImmediately ) - { - replay( reporterManager ); + if (allScheduled && isAllTestsDone() && reportImmediately) { + replay(reporterManager); } } - public void setAllScheduled( TestReportListener reporterManager ) - { + public void setAllScheduled(TestReportListener reporterManager) { allScheduled = true; - if ( isAllTestsDone() ) - { - replay( reporterManager ); + if (isAllTestsDone()) { + replay(reporterManager); } } - private boolean isAllTestsDone() - { + private boolean isAllTestsDone() { return numberOfTests.get() == numberOfCompletedChildren.get(); } - public void attachToThread() - { - TEST_SET.set( this ); + public void attachToThread() { + TEST_SET.set(this); } - public static TestSet getThreadTestSet() - { + public static TestSet getThreadTestSet() { return TEST_SET.get(); } } diff --git a/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/pc/AbstractThreadPoolStrategy.java b/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/pc/AbstractThreadPoolStrategy.java index b226141860..d79628f262 100644 --- a/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/pc/AbstractThreadPoolStrategy.java +++ b/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/pc/AbstractThreadPoolStrategy.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.junitcore.pc; /* @@ -19,14 +37,14 @@ * under the License. */ -import org.apache.maven.plugin.surefire.log.api.ConsoleLogger; - import java.util.Collection; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; +import org.apache.maven.plugin.surefire.log.api.ConsoleLogger; + /** * Abstract parallel scheduling strategy in private package. * The remaining abstract methods have to be implemented differently @@ -38,75 +56,58 @@ * @see NonSharedThreadPoolStrategy * @since 2.16 */ -abstract class AbstractThreadPoolStrategy - extends SchedulingStrategy -{ +abstract class AbstractThreadPoolStrategy extends SchedulingStrategy { private final ExecutorService threadPool; private final Collection> futureResults; private volatile boolean isDestroyed; - AbstractThreadPoolStrategy( ConsoleLogger logger, ExecutorService threadPool ) - { - this( logger, threadPool, null ); + AbstractThreadPoolStrategy(ConsoleLogger logger, ExecutorService threadPool) { + this(logger, threadPool, null); } - AbstractThreadPoolStrategy( ConsoleLogger logger, ExecutorService threadPool, Collection> futureResults ) - { - super( logger ); + AbstractThreadPoolStrategy(ConsoleLogger logger, ExecutorService threadPool, Collection> futureResults) { + super(logger); this.threadPool = threadPool; this.futureResults = futureResults; } - protected final ExecutorService getThreadPool() - { + protected final ExecutorService getThreadPool() { return threadPool; } - protected final Collection> getFutureResults() - { + protected final Collection> getFutureResults() { return futureResults; } @Override - public void schedule( Runnable task ) - { - if ( canSchedule() ) - { - Future futureResult = threadPool.submit( task ); - if ( futureResults != null ) - { - futureResults.add( futureResult ); + public void schedule(Runnable task) { + if (canSchedule()) { + Future futureResult = threadPool.submit(task); + if (futureResults != null) { + futureResults.add(futureResult); } } } @Override - protected boolean stop() - { + protected boolean stop() { boolean wasRunning = disable(); - if ( threadPool.isShutdown() ) - { + if (threadPool.isShutdown()) { wasRunning = false; - } - else - { + } else { threadPool.shutdown(); } return wasRunning; } @Override - protected boolean stopNow() - { + protected boolean stopNow() { boolean wasRunning = disable(); - if ( threadPool.isShutdown() ) - { + if (threadPool.isShutdown()) { wasRunning = false; - } - else - { + } else { threadPool.shutdownNow(); } return wasRunning; @@ -116,31 +117,25 @@ protected boolean stopNow() * @see Scheduler.ShutdownHandler */ @Override - protected void setDefaultShutdownHandler( Scheduler.ShutdownHandler handler ) - { - if ( threadPool instanceof ThreadPoolExecutor ) - { + protected void setDefaultShutdownHandler(Scheduler.ShutdownHandler handler) { + if (threadPool instanceof ThreadPoolExecutor) { ThreadPoolExecutor pool = (ThreadPoolExecutor) threadPool; - handler.setRejectedExecutionHandler( pool.getRejectedExecutionHandler() ); - pool.setRejectedExecutionHandler( handler ); + handler.setRejectedExecutionHandler(pool.getRejectedExecutionHandler()); + pool.setRejectedExecutionHandler(handler); } } @Override - public boolean destroy() - { - try - { - if ( !isDestroyed )//just an optimization + public boolean destroy() { + try { + if (!isDestroyed) // just an optimization { disable(); threadPool.shutdown(); - this.isDestroyed |= threadPool.awaitTermination( Long.MAX_VALUE, TimeUnit.NANOSECONDS ); + this.isDestroyed |= threadPool.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS); } return isDestroyed; - } - catch ( InterruptedException e ) - { + } catch (InterruptedException e) { return false; } } diff --git a/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/pc/Balancer.java b/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/pc/Balancer.java index ec93dba94e..21ba3ccf50 100644 --- a/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/pc/Balancer.java +++ b/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/pc/Balancer.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.junitcore.pc; /* @@ -30,8 +48,7 @@ * @author Tibor Digana (tibor17) * @since 2.16 */ -public interface Balancer -{ +public interface Balancer { /** * Acquires a permit from this balancer, blocking until one is available. diff --git a/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/pc/BalancerFactory.java b/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/pc/BalancerFactory.java index 82a9a463b2..0a8e0724af 100644 --- a/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/pc/BalancerFactory.java +++ b/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/pc/BalancerFactory.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.junitcore.pc; /* @@ -24,19 +42,15 @@ * @see Balancer * @since 2.16 */ -public class BalancerFactory -{ - private BalancerFactory() - { - } +public class BalancerFactory { + private BalancerFactory() {} /** * Infinite permits. * @return Balancer wih infinite permits */ - public static Balancer createInfinitePermitsBalancer() - { - return balancer( 0, false ); + public static Balancer createInfinitePermitsBalancer() { + return balancer(0, false); } /** @@ -46,9 +60,8 @@ public static Balancer createInfinitePermitsBalancer() * @param concurrency number of permits to acquire when maintaining concurrency on tests * @return Balancer with given number of permits */ - public static Balancer createBalancer( int concurrency ) - { - return balancer( concurrency, false ); + public static Balancer createBalancer(int concurrency) { + return balancer(concurrency, false); } /** @@ -58,14 +71,12 @@ public static Balancer createBalancer( int concurrency ) * @param concurrency number of permits to acquire when maintaining concurrency on tests * @return Balancer with given number of permits */ - public static Balancer createBalancerWithFairness( int concurrency ) - { - return balancer( concurrency, true ); + public static Balancer createBalancerWithFairness(int concurrency) { + return balancer(concurrency, true); } - private static Balancer balancer( int concurrency, boolean fairness ) - { + private static Balancer balancer(int concurrency, boolean fairness) { boolean shouldBalance = concurrency > 0 && concurrency < Integer.MAX_VALUE; - return shouldBalance ? new ThreadResourcesBalancer( concurrency, fairness ) : new NullBalancer(); + return shouldBalance ? new ThreadResourcesBalancer(concurrency, fairness) : new NullBalancer(); } -} \ No newline at end of file +} diff --git a/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/pc/Concurrency.java b/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/pc/Concurrency.java index c05af7f95b..72b7372473 100644 --- a/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/pc/Concurrency.java +++ b/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/pc/Concurrency.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.junitcore.pc; /* @@ -23,7 +41,6 @@ * @author tibor17 (Tibor Digana) * @since 2.17 */ -final class Concurrency -{ +final class Concurrency { int suites, classes, methods, capacity; -} \ No newline at end of file +} diff --git a/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/pc/Destroyable.java b/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/pc/Destroyable.java index af30831c87..e1cb368719 100644 --- a/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/pc/Destroyable.java +++ b/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/pc/Destroyable.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.junitcore.pc; /* @@ -26,8 +44,7 @@ * @see ParallelComputerBuilder * @since 2.18 */ -public interface Destroyable -{ +public interface Destroyable { /** * Calling {@link java.util.concurrent.ThreadPoolExecutor#shutdown()} * and {@link java.util.concurrent.ThreadPoolExecutor#awaitTermination(long, java.util.concurrent.TimeUnit)}. @@ -35,4 +52,4 @@ public interface Destroyable * @return {@code true} if not interrupted in current thread */ boolean destroy(); -} \ No newline at end of file +} diff --git a/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/pc/ExecutionStatus.java b/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/pc/ExecutionStatus.java index 07c21c9551..1e77d7d75c 100644 --- a/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/pc/ExecutionStatus.java +++ b/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/pc/ExecutionStatus.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.junitcore.pc; /* @@ -27,8 +45,7 @@ * @see ParallelComputer * @since 2.18 */ -enum ExecutionStatus -{ +enum ExecutionStatus { STARTED, FINISHED, TIMEOUT diff --git a/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/pc/InvokerStrategy.java b/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/pc/InvokerStrategy.java index 55091dfe46..1ea693d8dc 100644 --- a/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/pc/InvokerStrategy.java +++ b/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/pc/InvokerStrategy.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.junitcore.pc; /* @@ -19,11 +37,11 @@ * under the License. */ -import org.apache.maven.plugin.surefire.log.api.ConsoleLogger; - import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; +import org.apache.maven.plugin.surefire.log.api.ConsoleLogger; + /** * The sequentially executing strategy in private package. * @@ -31,69 +49,54 @@ * @see SchedulingStrategy * @since 2.16 */ -final class InvokerStrategy - extends SchedulingStrategy -{ +final class InvokerStrategy extends SchedulingStrategy { private final Queue activeThreads = new ConcurrentLinkedQueue<>(); - protected InvokerStrategy( ConsoleLogger logger ) - { - super( logger ); + protected InvokerStrategy(ConsoleLogger logger) { + super(logger); } @Override - public void schedule( Runnable task ) - { - if ( canSchedule() ) - { + public void schedule(Runnable task) { + if (canSchedule()) { final Thread currentThread = Thread.currentThread(); - try - { - activeThreads.add( currentThread ); + try { + activeThreads.add(currentThread); task.run(); - } - finally - { - activeThreads.remove( currentThread ); + } finally { + activeThreads.remove(currentThread); } } } @Override - protected boolean stop() - { + protected boolean stop() { return disable(); } @Override - protected boolean stopNow() - { + protected boolean stopNow() { final boolean stopped = disable(); - for ( Thread activeThread = activeThreads.poll(); activeThread != null; activeThread = activeThreads.poll() ) - { + for (Thread activeThread = activeThreads.poll(); activeThread != null; activeThread = activeThreads.poll()) { activeThread.interrupt(); } return stopped; } @Override - public boolean hasSharedThreadPool() - { + public boolean hasSharedThreadPool() { return false; } @Override - public boolean finished() - throws InterruptedException - { + public boolean finished() throws InterruptedException { return disable(); } @Override - public boolean destroy() - { + public boolean destroy() { return stop(); } } diff --git a/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/pc/NonSharedThreadPoolStrategy.java b/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/pc/NonSharedThreadPoolStrategy.java index eee8df5cba..a982c8270d 100644 --- a/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/pc/NonSharedThreadPoolStrategy.java +++ b/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/pc/NonSharedThreadPoolStrategy.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.junitcore.pc; /* @@ -19,11 +37,11 @@ * under the License. */ -import org.apache.maven.plugin.surefire.log.api.ConsoleLogger; - import java.util.concurrent.ExecutorService; import java.util.concurrent.TimeUnit; +import org.apache.maven.plugin.surefire.log.api.ConsoleLogger; + /** * Parallel strategy for non-shared thread pool in private package. * @@ -31,27 +49,21 @@ * @see AbstractThreadPoolStrategy * @since 2.16 */ -final class NonSharedThreadPoolStrategy - extends AbstractThreadPoolStrategy -{ - NonSharedThreadPoolStrategy( ConsoleLogger logger, ExecutorService threadPool ) - { - super( logger, threadPool ); +final class NonSharedThreadPoolStrategy extends AbstractThreadPoolStrategy { + NonSharedThreadPoolStrategy(ConsoleLogger logger, ExecutorService threadPool) { + super(logger, threadPool); } @Override - public boolean hasSharedThreadPool() - { + public boolean hasSharedThreadPool() { return false; } @Override - public boolean finished() - throws InterruptedException - { + public boolean finished() throws InterruptedException { boolean wasRunning = disable(); getThreadPool().shutdown(); - getThreadPool().awaitTermination( Long.MAX_VALUE, TimeUnit.NANOSECONDS ); + getThreadPool().awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS); return wasRunning; } } diff --git a/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/pc/NullBalancer.java b/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/pc/NullBalancer.java index a80e8c506a..d9ea9e5fed 100644 --- a/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/pc/NullBalancer.java +++ b/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/pc/NullBalancer.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.junitcore.pc; /* @@ -26,22 +44,15 @@ * @see Balancer * @since 2.16 */ -final class NullBalancer - implements Balancer -{ +final class NullBalancer implements Balancer { @Override - public boolean acquirePermit() - { + public boolean acquirePermit() { return true; } @Override - public void releasePermit() - { - } + public void releasePermit() {} @Override - public void releaseAllPermits() - { - } -} \ No newline at end of file + public void releaseAllPermits() {} +} diff --git a/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/pc/ParallelComputer.java b/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/pc/ParallelComputer.java index 4d311c078c..5758e12093 100644 --- a/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/pc/ParallelComputer.java +++ b/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/pc/ParallelComputer.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.junitcore.pc; /* @@ -19,11 +37,6 @@ * under the License. */ -import org.apache.maven.surefire.api.testset.TestSetFailedException; -import org.apache.maven.surefire.api.util.internal.DaemonThreadFactory; -import org.junit.runner.Computer; -import org.junit.runner.Description; - import java.util.Collection; import java.util.TreeSet; import java.util.concurrent.Callable; @@ -33,6 +46,11 @@ import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ThreadFactory; +import org.apache.maven.surefire.api.testset.TestSetFailedException; +import org.apache.maven.surefire.api.util.internal.DaemonThreadFactory; +import org.junit.runner.Computer; +import org.junit.runner.Description; + import static java.util.concurrent.TimeUnit.NANOSECONDS; /** @@ -42,9 +60,7 @@ * @see ParallelComputerBuilder * @since 2.16 */ -public abstract class ParallelComputer - extends Computer -{ +public abstract class ParallelComputer extends Computer { private static final ThreadFactory DAEMON_THREAD_FACTORY = DaemonThreadFactory.newDaemonThreadFactory(); private static final double NANOS_IN_A_SECOND = 1E9; @@ -59,41 +75,34 @@ public abstract class ParallelComputer private ScheduledExecutorService shutdownScheduler; - public ParallelComputer( double timeoutInSeconds, double timeoutForcedInSeconds ) - { - this.timeoutNanos = secondsToNanos( timeoutInSeconds ); - this.timeoutForcedNanos = secondsToNanos( timeoutForcedInSeconds ); + public ParallelComputer(double timeoutInSeconds, double timeoutForcedInSeconds) { + this.timeoutNanos = secondsToNanos(timeoutInSeconds); + this.timeoutForcedNanos = secondsToNanos(timeoutForcedInSeconds); } - protected abstract ShutdownResult describeStopped( boolean shutdownNow ); + protected abstract ShutdownResult describeStopped(boolean shutdownNow); protected abstract boolean shutdownThreadPoolsAwaitingKilled(); - protected final void beforeRunQuietly() - { - shutdownStatus.setDescriptionsBeforeShutdown( hasTimeout() ? scheduleShutdown() : null ); - forcedShutdownStatus.setDescriptionsBeforeShutdown( hasTimeoutForced() ? scheduleForcedShutdown() : null ); + protected final void beforeRunQuietly() { + shutdownStatus.setDescriptionsBeforeShutdown(hasTimeout() ? scheduleShutdown() : null); + forcedShutdownStatus.setDescriptionsBeforeShutdown(hasTimeoutForced() ? scheduleForcedShutdown() : null); } - protected final boolean afterRunQuietly() - { + protected final boolean afterRunQuietly() { shutdownStatus.tryFinish(); forcedShutdownStatus.tryFinish(); boolean notInterrupted = true; - if ( shutdownScheduler != null ) - { + if (shutdownScheduler != null) { shutdownScheduler.shutdownNow(); /** * Clear interrupted status of the (main) Thread. * Could be previously interrupted by {@link InvokerStrategy} after triggering immediate shutdown. */ Thread.interrupted(); - try - { - shutdownScheduler.awaitTermination( Long.MAX_VALUE, NANOSECONDS ); - } - catch ( InterruptedException e ) - { + try { + shutdownScheduler.awaitTermination(Long.MAX_VALUE, NANOSECONDS); + } catch (InterruptedException e) { notInterrupted = false; } } @@ -101,170 +110,129 @@ protected final boolean afterRunQuietly() return notInterrupted; } - public String describeElapsedTimeout() - throws TestSetFailedException - { + public String describeElapsedTimeout() throws TestSetFailedException { final StringBuilder msg = new StringBuilder(); final boolean isShutdownTimeout = shutdownStatus.isTimeoutElapsed(); final boolean isForcedShutdownTimeout = forcedShutdownStatus.isTimeoutElapsed(); - if ( isShutdownTimeout || isForcedShutdownTimeout ) - { - msg.append( "The test run has finished abruptly after timeout of " ); - msg.append( nanosToSeconds( minTimeout( timeoutNanos, timeoutForcedNanos ) ) ); - msg.append( " seconds.\n" ); - - try - { + if (isShutdownTimeout || isForcedShutdownTimeout) { + msg.append("The test run has finished abruptly after timeout of "); + msg.append(nanosToSeconds(minTimeout(timeoutNanos, timeoutForcedNanos))); + msg.append(" seconds.\n"); + + try { final TreeSet executedTests = new TreeSet<>(); final TreeSet incompleteTests = new TreeSet<>(); - if ( isShutdownTimeout ) - { - printShutdownHook( executedTests, incompleteTests, shutdownStatus.getDescriptionsBeforeShutdown() ); + if (isShutdownTimeout) { + printShutdownHook(executedTests, incompleteTests, shutdownStatus.getDescriptionsBeforeShutdown()); } - if ( isForcedShutdownTimeout ) - { - printShutdownHook( executedTests, incompleteTests, - forcedShutdownStatus.getDescriptionsBeforeShutdown() ); + if (isForcedShutdownTimeout) { + printShutdownHook( + executedTests, incompleteTests, forcedShutdownStatus.getDescriptionsBeforeShutdown()); } - if ( !executedTests.isEmpty() ) - { - msg.append( "These tests were executed in prior to the shutdown operation:\n" ); - for ( String executedTest : executedTests ) - { - msg.append( executedTest ).append( '\n' ); + if (!executedTests.isEmpty()) { + msg.append("These tests were executed in prior to the shutdown operation:\n"); + for (String executedTest : executedTests) { + msg.append(executedTest).append('\n'); } } - if ( !incompleteTests.isEmpty() ) - { - msg.append( "These tests are incomplete:\n" ); - for ( String incompleteTest : incompleteTests ) - { - msg.append( incompleteTest ).append( '\n' ); + if (!incompleteTests.isEmpty()) { + msg.append("These tests are incomplete:\n"); + for (String incompleteTest : incompleteTests) { + msg.append(incompleteTest).append('\n'); } } - } - catch ( InterruptedException e ) - { - throw new TestSetFailedException( "Timed termination was interrupted.", e ); - } - catch ( ExecutionException e ) - { - throw new TestSetFailedException( e.getLocalizedMessage(), e.getCause() ); + } catch (InterruptedException e) { + throw new TestSetFailedException("Timed termination was interrupted.", e); + } catch (ExecutionException e) { + throw new TestSetFailedException(e.getLocalizedMessage(), e.getCause()); } } return msg.toString(); } - private Future scheduleShutdown() - { - return getShutdownScheduler().schedule( createShutdownTask(), timeoutNanos, NANOSECONDS ); + private Future scheduleShutdown() { + return getShutdownScheduler().schedule(createShutdownTask(), timeoutNanos, NANOSECONDS); } - private Future scheduleForcedShutdown() - { - return getShutdownScheduler().schedule( createForcedShutdownTask(), timeoutForcedNanos, NANOSECONDS ); + private Future scheduleForcedShutdown() { + return getShutdownScheduler().schedule(createForcedShutdownTask(), timeoutForcedNanos, NANOSECONDS); } - private ScheduledExecutorService getShutdownScheduler() - { - if ( shutdownScheduler == null ) - { - shutdownScheduler = Executors.newScheduledThreadPool( 2, DAEMON_THREAD_FACTORY ); + private ScheduledExecutorService getShutdownScheduler() { + if (shutdownScheduler == null) { + shutdownScheduler = Executors.newScheduledThreadPool(2, DAEMON_THREAD_FACTORY); } return shutdownScheduler; } - private Callable createShutdownTask() - { - return new Callable() - { + private Callable createShutdownTask() { + return new Callable() { @Override - public ShutdownResult call() - throws Exception - { + public ShutdownResult call() throws Exception { boolean stampedStatusWithTimeout = ParallelComputer.this.shutdownStatus.tryTimeout(); - return stampedStatusWithTimeout ? ParallelComputer.this.describeStopped( false ) : null; + return stampedStatusWithTimeout ? ParallelComputer.this.describeStopped(false) : null; } }; } - private Callable createForcedShutdownTask() - { - return new Callable() - { + private Callable createForcedShutdownTask() { + return new Callable() { @Override - public ShutdownResult call() - throws Exception - { + public ShutdownResult call() throws Exception { boolean stampedStatusWithTimeout = ParallelComputer.this.forcedShutdownStatus.tryTimeout(); - return stampedStatusWithTimeout ? ParallelComputer.this.describeStopped( true ) : null; + return stampedStatusWithTimeout ? ParallelComputer.this.describeStopped(true) : null; } }; } - private double nanosToSeconds( long nanos ) - { + private double nanosToSeconds(long nanos) { return (double) nanos / NANOS_IN_A_SECOND; } - private boolean hasTimeout() - { + private boolean hasTimeout() { return timeoutNanos > 0; } - private boolean hasTimeoutForced() - { + private boolean hasTimeoutForced() { return timeoutForcedNanos > 0; } - private static long secondsToNanos( double seconds ) - { + private static long secondsToNanos(double seconds) { double nanos = seconds > 0 ? seconds * NANOS_IN_A_SECOND : 0; - return Double.isInfinite( nanos ) || nanos >= Long.MAX_VALUE ? 0 : (long) nanos; + return Double.isInfinite(nanos) || nanos >= Long.MAX_VALUE ? 0 : (long) nanos; } - private static long minTimeout( long timeout1, long timeout2 ) - { - if ( timeout1 == 0 ) - { + private static long minTimeout(long timeout1, long timeout2) { + if (timeout1 == 0) { return timeout2; - } - else if ( timeout2 == 0 ) - { + } else if (timeout2 == 0) { return timeout1; - } - else - { - return Math.min( timeout1, timeout2 ); + } else { + return Math.min(timeout1, timeout2); } } - private static void printShutdownHook( Collection executedTests, Collection incompleteTests, - Future testsBeforeShutdown ) - throws ExecutionException, InterruptedException - { - if ( testsBeforeShutdown != null ) - { + private static void printShutdownHook( + Collection executedTests, + Collection incompleteTests, + Future testsBeforeShutdown) + throws ExecutionException, InterruptedException { + if (testsBeforeShutdown != null) { final ShutdownResult shutdownResult = testsBeforeShutdown.get(); - if ( shutdownResult != null ) - { - for ( final Description test : shutdownResult.getTriggeredTests() ) - { - if ( test != null && test.getDisplayName() != null ) - { - executedTests.add( test.getDisplayName() ); + if (shutdownResult != null) { + for (final Description test : shutdownResult.getTriggeredTests()) { + if (test != null && test.getDisplayName() != null) { + executedTests.add(test.getDisplayName()); } } - for ( final Description test : shutdownResult.getIncompleteTests() ) - { - if ( test != null && test.getDisplayName() != null ) - { - incompleteTests.add( test.getDisplayName() ); + for (final Description test : shutdownResult.getIncompleteTests()) { + if (test != null && test.getDisplayName() != null) { + incompleteTests.add(test.getDisplayName()); } } } diff --git a/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/pc/ParallelComputerBuilder.java b/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/pc/ParallelComputerBuilder.java index f9d178abef..043f6737f7 100755 --- a/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/pc/ParallelComputerBuilder.java +++ b/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/pc/ParallelComputerBuilder.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.junitcore.pc; /* @@ -35,9 +53,9 @@ import java.util.concurrent.ThreadFactory; import org.apache.maven.plugin.surefire.log.api.ConsoleLogger; -import org.apache.maven.surefire.junitcore.JUnitCoreParameters; import org.apache.maven.surefire.api.testset.TestSetFailedException; import org.apache.maven.surefire.api.util.internal.DaemonThreadFactory; +import org.apache.maven.surefire.junitcore.JUnitCoreParameters; import org.junit.internal.runners.ErrorReportingRunner; import org.junit.runner.Description; import org.junit.runner.Runner; @@ -56,7 +74,7 @@ import static org.apache.maven.surefire.junitcore.pc.Type.METHODS; import static org.apache.maven.surefire.junitcore.pc.Type.SUITES; -@SuppressWarnings( { "javadoc", "checkstyle:javadoctype" } ) +@SuppressWarnings({"javadoc", "checkstyle:javadoctype"}) /* * Executing suites, classes and methods with defined concurrency. In this example the threads which completed * the suites and classes can be reused in parallel methods. @@ -81,17 +99,16 @@ * @author Tibor Digana (tibor17) * @since 2.16 */ -public final class ParallelComputerBuilder -{ +public final class ParallelComputerBuilder { private static final ThreadFactory DAEMON_THREAD_FACTORY = DaemonThreadFactory.newDaemonThreadFactory(); private static final Class JCIP_NOT_THREAD_SAFE = loadNotThreadSafeAnnotations(); - private static final Set NULL_SINGLETON = Collections.singleton( null ); + private static final Set NULL_SINGLETON = Collections.singleton(null); static final int TOTAL_POOL_SIZE_UNDEFINED = 0; - private final Map parallelGroups = new EnumMap<>( Type.class ); + private final Map parallelGroups = new EnumMap<>(Type.class); private final ConsoleLogger logger; @@ -110,37 +127,32 @@ public final class ParallelComputerBuilder * Can be used only in unit tests. * Do NOT call this constructor in production. */ - ParallelComputerBuilder( ConsoleLogger logger ) - { + ParallelComputerBuilder(ConsoleLogger logger) { this.logger = logger; runningInTests = true; useSeparatePools(); - parallelGroups.put( SUITES, 0 ); - parallelGroups.put( CLASSES, 0 ); - parallelGroups.put( METHODS, 0 ); + parallelGroups.put(SUITES, 0); + parallelGroups.put(CLASSES, 0); + parallelGroups.put(METHODS, 0); } - public ParallelComputerBuilder( ConsoleLogger logger, JUnitCoreParameters parameters ) - { - this( logger ); + public ParallelComputerBuilder(ConsoleLogger logger, JUnitCoreParameters parameters) { + this(logger); runningInTests = false; this.parameters = parameters; } - public ParallelComputer buildComputer() - { + public ParallelComputer buildComputer() { return new PC(); } - ParallelComputerBuilder useSeparatePools() - { + ParallelComputerBuilder useSeparatePools() { totalPoolSize = TOTAL_POOL_SIZE_UNDEFINED; useSeparatePools = true; return this; } - ParallelComputerBuilder useOnePool() - { + ParallelComputerBuilder useOnePool() { totalPoolSize = TOTAL_POOL_SIZE_UNDEFINED; useSeparatePools = false; return this; @@ -152,108 +164,86 @@ ParallelComputerBuilder useOnePool() * limited. * @throws IllegalArgumentException If totalPoolSize is < 1. */ - ParallelComputerBuilder useOnePool( int totalPoolSize ) - { - if ( totalPoolSize < 1 ) - { - throw new IllegalArgumentException( "Size of common pool is less than 1." ); + ParallelComputerBuilder useOnePool(int totalPoolSize) { + if (totalPoolSize < 1) { + throw new IllegalArgumentException("Size of common pool is less than 1."); } this.totalPoolSize = totalPoolSize; useSeparatePools = false; return this; } - boolean isOptimized() - { + boolean isOptimized() { return optimize; } - ParallelComputerBuilder optimize( boolean optimize ) - { + ParallelComputerBuilder optimize(boolean optimize) { this.optimize = optimize; return this; } - ParallelComputerBuilder parallelSuites() - { - return parallel( SUITES ); + ParallelComputerBuilder parallelSuites() { + return parallel(SUITES); } - ParallelComputerBuilder parallelSuites( int nThreads ) - { - return parallel( nThreads, SUITES ); + ParallelComputerBuilder parallelSuites(int nThreads) { + return parallel(nThreads, SUITES); } - ParallelComputerBuilder parallelClasses() - { - return parallel( CLASSES ); + ParallelComputerBuilder parallelClasses() { + return parallel(CLASSES); } - ParallelComputerBuilder parallelClasses( int nThreads ) - { - return parallel( nThreads, CLASSES ); + ParallelComputerBuilder parallelClasses(int nThreads) { + return parallel(nThreads, CLASSES); } - ParallelComputerBuilder parallelMethods() - { - return parallel( METHODS ); + ParallelComputerBuilder parallelMethods() { + return parallel(METHODS); } - ParallelComputerBuilder parallelMethods( int nThreads ) - { - return parallel( nThreads, METHODS ); + ParallelComputerBuilder parallelMethods(int nThreads) { + return parallel(nThreads, METHODS); } - private ParallelComputerBuilder parallel( int nThreads, Type parallelType ) - { - if ( nThreads < 0 ) - { - throw new IllegalArgumentException( "negative nThreads " + nThreads ); + private ParallelComputerBuilder parallel(int nThreads, Type parallelType) { + if (nThreads < 0) { + throw new IllegalArgumentException("negative nThreads " + nThreads); } - if ( parallelType == null ) - { - throw new IllegalArgumentException( "null parallelType" ); + if (parallelType == null) { + throw new IllegalArgumentException("null parallelType"); } - parallelGroups.put( parallelType, nThreads ); + parallelGroups.put(parallelType, nThreads); return this; } - private ParallelComputerBuilder parallel( Type parallelType ) - { - return parallel( Integer.MAX_VALUE, parallelType ); + private ParallelComputerBuilder parallel(Type parallelType) { + return parallel(Integer.MAX_VALUE, parallelType); } - private double parallelTestsTimeoutInSeconds() - { + private double parallelTestsTimeoutInSeconds() { return parameters == null ? 0d : parameters.getParallelTestsTimeoutInSeconds(); } - private double parallelTestsTimeoutForcedInSeconds() - { + private double parallelTestsTimeoutForcedInSeconds() { return parameters == null ? 0d : parameters.getParallelTestsTimeoutForcedInSeconds(); } - @SuppressWarnings( "unchecked" ) - private static Class loadNotThreadSafeAnnotations() - { - try - { - Class c = Class.forName( "net.jcip.annotations.NotThreadSafe" ); + @SuppressWarnings("unchecked") + private static Class loadNotThreadSafeAnnotations() { + try { + Class c = Class.forName("net.jcip.annotations.NotThreadSafe"); return c.isAnnotation() ? (Class) c : null; - } - catch ( ClassNotFoundException e ) - { + } catch (ClassNotFoundException e) { return null; } } - final class PC - extends ParallelComputer - { + final class PC extends ParallelComputer { private final SingleThreadScheduler notThreadSafeTests = - new SingleThreadScheduler( ParallelComputerBuilder.this.logger ); + new SingleThreadScheduler(ParallelComputerBuilder.this.logger); private final Collection suites = new LinkedHashSet<>(); @@ -275,455 +265,349 @@ final class PC private volatile Scheduler master; - private PC() - { - super( parallelTestsTimeoutInSeconds(), parallelTestsTimeoutForcedInSeconds() ); - allGroups = new EnumMap<>( ParallelComputerBuilder.this.parallelGroups ); + private PC() { + super(parallelTestsTimeoutInSeconds(), parallelTestsTimeoutForcedInSeconds()); + allGroups = new EnumMap<>(ParallelComputerBuilder.this.parallelGroups); poolCapacity = ParallelComputerBuilder.this.totalPoolSize; splitPool = ParallelComputerBuilder.this.useSeparatePools; } - Collection getSuites() - { + Collection getSuites() { return suites; } - Collection getNestedSuites() - { + Collection getNestedSuites() { return nestedSuites; } - Collection getClasses() - { + Collection getClasses() { return classes; } - Collection getNestedClasses() - { + Collection getNestedClasses() { return nestedClasses; } - Collection getNotParallelRunners() - { + Collection getNotParallelRunners() { return notParallelRunners; } - int getPoolCapacity() - { + int getPoolCapacity() { return poolCapacity; } - boolean isSplitPool() - { + boolean isSplitPool() { return splitPool; } @Override - protected ShutdownResult describeStopped( boolean shutdownNow ) - { - ShutdownResult shutdownResult = notThreadSafeTests.describeStopped( shutdownNow ); + protected ShutdownResult describeStopped(boolean shutdownNow) { + ShutdownResult shutdownResult = notThreadSafeTests.describeStopped(shutdownNow); final Scheduler m = master; - if ( m != null ) - { - ShutdownResult shutdownResultOfMaster = m.describeStopped( shutdownNow ); - shutdownResult.getTriggeredTests().addAll( shutdownResultOfMaster.getTriggeredTests() ); - shutdownResult.getIncompleteTests().addAll( shutdownResultOfMaster.getIncompleteTests() ); + if (m != null) { + ShutdownResult shutdownResultOfMaster = m.describeStopped(shutdownNow); + shutdownResult.getTriggeredTests().addAll(shutdownResultOfMaster.getTriggeredTests()); + shutdownResult.getIncompleteTests().addAll(shutdownResultOfMaster.getIncompleteTests()); } return shutdownResult; } @Override - protected boolean shutdownThreadPoolsAwaitingKilled() - { + protected boolean shutdownThreadPoolsAwaitingKilled() { boolean notInterrupted = notThreadSafeTests.shutdownThreadPoolsAwaitingKilled(); final Scheduler m = master; - if ( m != null ) - { + if (m != null) { notInterrupted &= m.shutdownThreadPoolsAwaitingKilled(); } return notInterrupted; } @Override - public Runner getSuite( RunnerBuilder builder, Class[] cls ) - throws InitializationError - { - try - { - super.getSuite( builder, cls ); + public Runner getSuite(RunnerBuilder builder, Class[] cls) throws InitializationError { + try { + super.getSuite(builder, cls); populateChildrenFromSuites(); - WrappedRunners suiteSuites = wrapRunners( suites ); - WrappedRunners suiteClasses = wrapRunners( classes ); + WrappedRunners suiteSuites = wrapRunners(suites); + WrappedRunners suiteClasses = wrapRunners(classes); long suitesCount = suites.size(); long classesCount = classes.size() + nestedClasses.size(); long methodsCount = suiteClasses.embeddedChildrenCount + nestedClassesChildren; - if ( !ParallelComputerBuilder.this.runningInTests ) - { - determineThreadCounts( suitesCount, classesCount, methodsCount ); + if (!ParallelComputerBuilder.this.runningInTests) { + determineThreadCounts(suitesCount, classesCount, methodsCount); } - return setSchedulers( suiteSuites.wrappingSuite, suiteClasses.wrappingSuite ); - } - catch ( TestSetFailedException e ) - { - throw new InitializationError( Collections.singletonList( e ) ); + return setSchedulers(suiteSuites.wrappingSuite, suiteClasses.wrappingSuite); + } catch (TestSetFailedException e) { + throw new InitializationError(Collections.singletonList(e)); } } @Override - protected Runner getRunner( RunnerBuilder builder, Class testClass ) - throws Throwable - { - Runner runner = super.getRunner( builder, testClass ); - if ( canSchedule( runner ) ) - { - if ( !isThreadSafe( runner ) ) - { - ( ( ParentRunner ) runner ).setScheduler( notThreadSafeTests.newRunnerScheduler() ); - notParallelRunners.add( runner ); - } - else if ( runner instanceof Suite ) - { - suites.add( (Suite) runner ); - } - else - { - classes.add( (ParentRunner) runner ); + protected Runner getRunner(RunnerBuilder builder, Class testClass) throws Throwable { + Runner runner = super.getRunner(builder, testClass); + if (canSchedule(runner)) { + if (!isThreadSafe(runner)) { + ((ParentRunner) runner).setScheduler(notThreadSafeTests.newRunnerScheduler()); + notParallelRunners.add(runner); + } else if (runner instanceof Suite) { + suites.add((Suite) runner); + } else { + classes.add((ParentRunner) runner); } - } - else - { - notParallelRunners.add( runner ); + } else { + notParallelRunners.add(runner); } return runner; } - private void determineThreadCounts( long suites, long classes, long methods ) - throws TestSetFailedException - { + private void determineThreadCounts(long suites, long classes, long methods) throws TestSetFailedException { RunnerCounter counts = - ParallelComputerBuilder.this.optimize ? new RunnerCounter( suites, classes, methods ) : null; - Concurrency concurrency = - resolveConcurrency( ParallelComputerBuilder.this.parameters, counts ); - allGroups.put( SUITES, concurrency.suites ); - allGroups.put( CLASSES, concurrency.classes ); - allGroups.put( METHODS, concurrency.methods ); + ParallelComputerBuilder.this.optimize ? new RunnerCounter(suites, classes, methods) : null; + Concurrency concurrency = resolveConcurrency(ParallelComputerBuilder.this.parameters, counts); + allGroups.put(SUITES, concurrency.suites); + allGroups.put(CLASSES, concurrency.classes); + allGroups.put(METHODS, concurrency.methods); poolCapacity = concurrency.capacity; splitPool &= concurrency.capacity <= 0; // fault if negative; should not happen } - private WrappedRunners wrapRunners( Collection runners ) - throws InitializationError - { + private WrappedRunners wrapRunners(Collection runners) throws InitializationError { // Do NOT use allGroups here. long childrenCounter = 0; ArrayList runs = new ArrayList<>(); - for ( T runner : runners ) - { - if ( runner != null ) - { - int children = countChildren( runner ); + for (T runner : runners) { + if (runner != null) { + int children = countChildren(runner); childrenCounter += children; - runs.add( runner ); + runs.add(runner); } } - return runs.isEmpty() ? new WrappedRunners() : new WrappedRunners( createSuite( runs ), childrenCounter ); + return runs.isEmpty() ? new WrappedRunners() : new WrappedRunners(createSuite(runs), childrenCounter); } - private int countChildren( Runner runner ) - { + private int countChildren(Runner runner) { Description description = runner.getDescription(); Collection children = description == null ? null : description.getChildren(); return children == null ? 0 : children.size(); } - private ExecutorService createPool( int poolSize ) - { + private ExecutorService createPool(int poolSize) { return poolSize < Integer.MAX_VALUE - ? Executors.newFixedThreadPool( poolSize, DAEMON_THREAD_FACTORY ) - : Executors.newCachedThreadPool( DAEMON_THREAD_FACTORY ); + ? Executors.newFixedThreadPool(poolSize, DAEMON_THREAD_FACTORY) + : Executors.newCachedThreadPool(DAEMON_THREAD_FACTORY); } - private Scheduler createMaster( ExecutorService pool, int poolSize ) - { + private Scheduler createMaster(ExecutorService pool, int poolSize) { // can be 0, 1, 2 or 3 final int finalRunnersCounter = countFinalRunners(); final SchedulingStrategy strategy; - if ( finalRunnersCounter <= 1 || poolSize <= 1 ) - { - strategy = new InvokerStrategy( ParallelComputerBuilder.this.logger ); - } - else if ( pool != null && poolSize == Integer.MAX_VALUE ) - { - strategy = new SharedThreadPoolStrategy( ParallelComputerBuilder.this.logger, pool ); + if (finalRunnersCounter <= 1 || poolSize <= 1) { + strategy = new InvokerStrategy(ParallelComputerBuilder.this.logger); + } else if (pool != null && poolSize == Integer.MAX_VALUE) { + strategy = new SharedThreadPoolStrategy(ParallelComputerBuilder.this.logger, pool); + } else { + strategy = createParallelStrategy(ParallelComputerBuilder.this.logger, finalRunnersCounter); } - else - { - strategy = createParallelStrategy( ParallelComputerBuilder.this.logger, finalRunnersCounter ); - } - return new Scheduler( ParallelComputerBuilder.this.logger, null, strategy ); + return new Scheduler(ParallelComputerBuilder.this.logger, null, strategy); } - private int countFinalRunners() - { + private int countFinalRunners() { int counter = notParallelRunners.isEmpty() ? 0 : 1; - if ( !suites.isEmpty() && allGroups.get( SUITES ) > 0 ) - { + if (!suites.isEmpty() && allGroups.get(SUITES) > 0) { ++counter; } - if ( !classes.isEmpty() && allGroups.get( CLASSES ) > 0 ) - { + if (!classes.isEmpty() && allGroups.get(CLASSES) > 0) { ++counter; } return counter; } - private void populateChildrenFromSuites() - { + private void populateChildrenFromSuites() { // Do NOT use allGroups here. Filter filter = new SuiteFilter(); - for ( Iterator it = suites.iterator(); it.hasNext(); ) - { + for (Iterator it = suites.iterator(); it.hasNext(); ) { ParentRunner suite = it.next(); - try - { - suite.filter( filter ); - } - catch ( NoTestsRemainException e ) - { + try { + suite.filter(filter); + } catch (NoTestsRemainException e) { it.remove(); } } } - private int totalPoolSize() - { - if ( poolCapacity == TOTAL_POOL_SIZE_UNDEFINED ) - { + private int totalPoolSize() { + if (poolCapacity == TOTAL_POOL_SIZE_UNDEFINED) { int total = 0; - for ( int nThreads : allGroups.values() ) - { + for (int nThreads : allGroups.values()) { total += nThreads; - if ( total < 0 ) - { + if (total < 0) { total = Integer.MAX_VALUE; break; } } return total; - } - else - { + } else { return poolCapacity; } } - private Runner setSchedulers( ParentRunner suiteSuites, ParentRunner suiteClasses ) - throws InitializationError - { - int parallelSuites = allGroups.get( SUITES ); - int parallelClasses = allGroups.get( CLASSES ); - int parallelMethods = allGroups.get( METHODS ); + private Runner setSchedulers(ParentRunner suiteSuites, ParentRunner suiteClasses) throws InitializationError { + int parallelSuites = allGroups.get(SUITES); + int parallelClasses = allGroups.get(CLASSES); + int parallelMethods = allGroups.get(METHODS); int poolSize = totalPoolSize(); - ExecutorService commonPool = splitPool || poolSize == 0 ? null : createPool( poolSize ); - master = createMaster( commonPool, poolSize ); + ExecutorService commonPool = splitPool || poolSize == 0 ? null : createPool(poolSize); + master = createMaster(commonPool, poolSize); - if ( suiteSuites != null ) - { + if (suiteSuites != null) { // a scheduler for parallel suites - if ( commonPool != null && parallelSuites > 0 ) - { - Balancer balancer = BalancerFactory.createBalancerWithFairness( parallelSuites ); - suiteSuites.setScheduler( createScheduler( null, commonPool, true, balancer ) ); - } - else - { - suiteSuites.setScheduler( createScheduler( parallelSuites ) ); + if (commonPool != null && parallelSuites > 0) { + Balancer balancer = BalancerFactory.createBalancerWithFairness(parallelSuites); + suiteSuites.setScheduler(createScheduler(null, commonPool, true, balancer)); + } else { + suiteSuites.setScheduler(createScheduler(parallelSuites)); } } // schedulers for parallel classes - ArrayList allSuites = new ArrayList<>( suites ); - allSuites.addAll( nestedSuites ); - if ( suiteClasses != null ) - { - allSuites.add( suiteClasses ); + ArrayList allSuites = new ArrayList<>(suites); + allSuites.addAll(nestedSuites); + if (suiteClasses != null) { + allSuites.add(suiteClasses); } - if ( !allSuites.isEmpty() ) - { - setSchedulers( allSuites, parallelClasses, commonPool ); + if (!allSuites.isEmpty()) { + setSchedulers(allSuites, parallelClasses, commonPool); } // schedulers for parallel methods - ArrayList allClasses = new ArrayList<>( classes ); - allClasses.addAll( nestedClasses ); - if ( !allClasses.isEmpty() ) - { - setSchedulers( allClasses, parallelMethods, commonPool ); + ArrayList allClasses = new ArrayList<>(classes); + allClasses.addAll(nestedClasses); + if (!allClasses.isEmpty()) { + setSchedulers(allClasses, parallelMethods, commonPool); } // resulting runner for Computer#getSuite() scheduled by master scheduler - ParentRunner all = createFinalRunner( removeNullRunners( - Arrays.asList( suiteSuites, suiteClasses, createSuite( notParallelRunners ) ) - ) ); - all.setScheduler( master ); + ParentRunner all = createFinalRunner(removeNullRunners( + Arrays.asList(suiteSuites, suiteClasses, createSuite(notParallelRunners)))); + all.setScheduler(master); return all; } - private ParentRunner createFinalRunner( List runners ) - throws InitializationError - { - return new Suite( null, runners ) - { + private ParentRunner createFinalRunner(List runners) throws InitializationError { + return new Suite(null, runners) { @Override - public void run( RunNotifier notifier ) - { - try - { + public void run(RunNotifier notifier) { + try { beforeRunQuietly(); - super.run( notifier ); - } - finally - { + super.run(notifier); + } finally { afterRunQuietly(); } } }; } - private void setSchedulers( Iterable runners, int poolSize, ExecutorService commonPool ) - { - if ( commonPool != null ) - { - Balancer concurrencyLimit = BalancerFactory.createBalancerWithFairness( poolSize ); + private void setSchedulers(Iterable runners, int poolSize, ExecutorService commonPool) { + if (commonPool != null) { + Balancer concurrencyLimit = BalancerFactory.createBalancerWithFairness(poolSize); boolean doParallel = poolSize > 0; - for ( ParentRunner runner : runners ) - { + for (ParentRunner runner : runners) { runner.setScheduler( - createScheduler( runner.getDescription(), commonPool, doParallel, concurrencyLimit ) ); + createScheduler(runner.getDescription(), commonPool, doParallel, concurrencyLimit)); } - } - else - { + } else { ExecutorService pool = null; - if ( poolSize == Integer.MAX_VALUE ) - { - pool = Executors.newCachedThreadPool( DAEMON_THREAD_FACTORY ); - } - else if ( poolSize > 0 ) - { - pool = Executors.newFixedThreadPool( poolSize, DAEMON_THREAD_FACTORY ); + if (poolSize == Integer.MAX_VALUE) { + pool = Executors.newCachedThreadPool(DAEMON_THREAD_FACTORY); + } else if (poolSize > 0) { + pool = Executors.newFixedThreadPool(poolSize, DAEMON_THREAD_FACTORY); } boolean doParallel = pool != null; - for ( ParentRunner runner : runners ) - { - runner.setScheduler( createScheduler( runner.getDescription(), pool, doParallel, - BalancerFactory.createInfinitePermitsBalancer() ) ); + for (ParentRunner runner : runners) { + runner.setScheduler(createScheduler( + runner.getDescription(), + pool, + doParallel, + BalancerFactory.createInfinitePermitsBalancer())); } } } - private Scheduler createScheduler( Description desc, ExecutorService pool, boolean doParallel, - Balancer concurrency ) - { - SchedulingStrategy strategy = - doParallel & pool != null - ? new SharedThreadPoolStrategy( ParallelComputerBuilder.this.logger, pool ) - : new InvokerStrategy( ParallelComputerBuilder.this.logger ); - return new Scheduler( ParallelComputerBuilder.this.logger, desc, master, strategy, concurrency ); + private Scheduler createScheduler( + Description desc, ExecutorService pool, boolean doParallel, Balancer concurrency) { + SchedulingStrategy strategy = doParallel & pool != null + ? new SharedThreadPoolStrategy(ParallelComputerBuilder.this.logger, pool) + : new InvokerStrategy(ParallelComputerBuilder.this.logger); + return new Scheduler(ParallelComputerBuilder.this.logger, desc, master, strategy, concurrency); } - private Scheduler createScheduler( int poolSize ) - { + private Scheduler createScheduler(int poolSize) { final SchedulingStrategy strategy; - if ( poolSize == Integer.MAX_VALUE ) - { - strategy = createParallelStrategyUnbounded( ParallelComputerBuilder.this.logger ); + if (poolSize == Integer.MAX_VALUE) { + strategy = createParallelStrategyUnbounded(ParallelComputerBuilder.this.logger); + } else if (poolSize == 0) { + strategy = new InvokerStrategy(ParallelComputerBuilder.this.logger); + } else { + strategy = createParallelStrategy(ParallelComputerBuilder.this.logger, poolSize); } - else if ( poolSize == 0 ) - { - strategy = new InvokerStrategy( ParallelComputerBuilder.this.logger ); - } - else - { - strategy = createParallelStrategy( ParallelComputerBuilder.this.logger, poolSize ); - } - return new Scheduler( ParallelComputerBuilder.this.logger, null, master, strategy ); + return new Scheduler(ParallelComputerBuilder.this.logger, null, master, strategy); } - private boolean canSchedule( Runner runner ) - { - return !( runner instanceof ErrorReportingRunner ) && runner instanceof ParentRunner; + private boolean canSchedule(Runner runner) { + return !(runner instanceof ErrorReportingRunner) && runner instanceof ParentRunner; } - private boolean isThreadSafe( Runner runner ) - { - return runner.getDescription().getAnnotation( JCIP_NOT_THREAD_SAFE ) == null; + private boolean isThreadSafe(Runner runner) { + return runner.getDescription().getAnnotation(JCIP_NOT_THREAD_SAFE) == null; } - private class SuiteFilter - extends Filter - { + private class SuiteFilter extends Filter { // Do NOT use allGroups in SuiteFilter. @Override - public boolean shouldRun( Description description ) - { + public boolean shouldRun(Description description) { return true; } @Override - public void apply( Object child ) - throws NoTestsRemainException - { - super.apply( child ); - if ( child instanceof ParentRunner ) - { - ParentRunner runner = ( ParentRunner ) child; - if ( !isThreadSafe( runner ) ) - { - runner.setScheduler( notThreadSafeTests.newRunnerScheduler() ); - } - else if ( child instanceof Suite ) - { - nestedSuites.add( (Suite) child ); - } - else - { + public void apply(Object child) throws NoTestsRemainException { + super.apply(child); + if (child instanceof ParentRunner) { + ParentRunner runner = (ParentRunner) child; + if (!isThreadSafe(runner)) { + runner.setScheduler(notThreadSafeTests.newRunnerScheduler()); + } else if (child instanceof Suite) { + nestedSuites.add((Suite) child); + } else { ParentRunner parentRunner = (ParentRunner) child; - nestedClasses.add( parentRunner ); - nestedClassesChildren += parentRunner.getDescription().getChildren().size(); + nestedClasses.add(parentRunner); + nestedClassesChildren += + parentRunner.getDescription().getChildren().size(); } } } @Override - public String describe() - { + public String describe() { return ""; } } } - private static Suite createSuite( Collection runners ) - throws InitializationError - { - final List onlyRunners = removeNullRunners( runners ); - return onlyRunners.isEmpty() ? null : new Suite( null, onlyRunners ) - { - }; + private static Suite createSuite(Collection runners) throws InitializationError { + final List onlyRunners = removeNullRunners(runners); + return onlyRunners.isEmpty() ? null : new Suite(null, onlyRunners) {}; } - private static List removeNullRunners( Collection runners ) - { - final List onlyRunners = new ArrayList<>( runners ); - onlyRunners.removeAll( NULL_SINGLETON ); + private static List removeNullRunners(Collection runners) { + final List onlyRunners = new ArrayList<>(runners); + onlyRunners.removeAll(NULL_SINGLETON); return onlyRunners; } } diff --git a/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/pc/ParallelComputerUtil.java b/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/pc/ParallelComputerUtil.java index 26fc7143e0..72a15c15c5 100644 --- a/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/pc/ParallelComputerUtil.java +++ b/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/pc/ParallelComputerUtil.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.junitcore.pc; /* @@ -19,14 +37,14 @@ * under the License. */ -import org.apache.maven.surefire.junitcore.JUnitCoreParameters; -import org.apache.maven.surefire.api.testset.TestSetFailedException; -import org.junit.runner.Description; - import java.util.Arrays; import java.util.Collection; import java.util.Iterator; +import org.apache.maven.surefire.api.testset.TestSetFailedException; +import org.apache.maven.surefire.junitcore.JUnitCoreParameters; +import org.junit.runner.Description; + /** * An algorithm which configures {@link ParallelComputer} with allocated thread resources by given * {@link org.apache.maven.surefire.junitcore.JUnitCoreParameters}. @@ -37,90 +55,68 @@ * @see org.apache.maven.surefire.junitcore.pc.ParallelComputerBuilder * @since 2.16 */ -final class ParallelComputerUtil -{ - private static final Collection UNUSED_DESCRIPTIONS = - Arrays.asList( null, Description.createSuiteDescription( "null" ), Description.TEST_MECHANISM, - Description.EMPTY ); +final class ParallelComputerUtil { + private static final Collection UNUSED_DESCRIPTIONS = Arrays.asList( + null, Description.createSuiteDescription("null"), Description.TEST_MECHANISM, Description.EMPTY); private static int availableProcessors = Runtime.getRuntime().availableProcessors(); - private ParallelComputerUtil() - { - throw new IllegalStateException( "Suppresses calling constructor, ensuring non-instantiability." ); + private ParallelComputerUtil() { + throw new IllegalStateException("Suppresses calling constructor, ensuring non-instantiability."); } /* - * For testing purposes. - */ - static void overrideAvailableProcessors( int availableProcessors ) - { + * For testing purposes. + */ + static void overrideAvailableProcessors(int availableProcessors) { ParallelComputerUtil.availableProcessors = availableProcessors; } /* - * For testing purposes. - */ - static void setDefaultAvailableProcessors() - { + * For testing purposes. + */ + static void setDefaultAvailableProcessors() { ParallelComputerUtil.availableProcessors = Runtime.getRuntime().availableProcessors(); } - static Concurrency resolveConcurrency( JUnitCoreParameters params, RunnerCounter counts ) - throws TestSetFailedException - { - if ( !params.isParallelismSelected() ) - { - throw new TestSetFailedException( "Unspecified parameter '" + JUnitCoreParameters.PARALLEL_KEY + "'." ); + static Concurrency resolveConcurrency(JUnitCoreParameters params, RunnerCounter counts) + throws TestSetFailedException { + if (!params.isParallelismSelected()) { + throw new TestSetFailedException("Unspecified parameter '" + JUnitCoreParameters.PARALLEL_KEY + "'."); } - if ( !params.isUseUnlimitedThreads() && !hasThreadCount( params ) && !hasThreadCounts( params ) ) - { - throw new TestSetFailedException( "Unspecified thread-count(s). " - + "See the parameters " - + JUnitCoreParameters.USEUNLIMITEDTHREADS_KEY + ", " - + JUnitCoreParameters.THREADCOUNT_KEY + ", " - + JUnitCoreParameters.THREADCOUNTSUITES_KEY + ", " - + JUnitCoreParameters.THREADCOUNTCLASSES_KEY + ", " - + JUnitCoreParameters.THREADCOUNTMETHODS_KEY + "." ); + if (!params.isUseUnlimitedThreads() && !hasThreadCount(params) && !hasThreadCounts(params)) { + throw new TestSetFailedException("Unspecified thread-count(s). " + + "See the parameters " + + JUnitCoreParameters.USEUNLIMITEDTHREADS_KEY + ", " + + JUnitCoreParameters.THREADCOUNT_KEY + ", " + + JUnitCoreParameters.THREADCOUNTSUITES_KEY + ", " + + JUnitCoreParameters.THREADCOUNTCLASSES_KEY + ", " + + JUnitCoreParameters.THREADCOUNTMETHODS_KEY + "."); } - if ( params.isUseUnlimitedThreads() ) - { - return concurrencyForUnlimitedThreads( params ); - } - else if ( hasThreadCount( params ) ) - { - if ( hasThreadCounts( params ) ) - { - return isLeafUnspecified( params ) - ? concurrencyFromAllThreadCountsButUnspecifiedLeafCount( params, counts ) - : concurrencyFromAllThreadCounts( params ); - } - else - { - return estimateConcurrency( params, counts ); + if (params.isUseUnlimitedThreads()) { + return concurrencyForUnlimitedThreads(params); + } else if (hasThreadCount(params)) { + if (hasThreadCounts(params)) { + return isLeafUnspecified(params) + ? concurrencyFromAllThreadCountsButUnspecifiedLeafCount(params, counts) + : concurrencyFromAllThreadCounts(params); + } else { + return estimateConcurrency(params, counts); } - } - else - { - return concurrencyFromThreadCounts( params ); + } else { + return concurrencyFromThreadCounts(params); } } - static boolean isUnusedDescription( Description examined ) - { - if ( UNUSED_DESCRIPTIONS.contains( examined ) ) - { + static boolean isUnusedDescription(Description examined) { + if (UNUSED_DESCRIPTIONS.contains(examined)) { return true; - } - else - { + } else { // UNUSED_DESCRIPTIONS ensures that "examined" cannot be null - for ( Description unused : UNUSED_DESCRIPTIONS ) - { - if ( unused != null && unused.getDisplayName().equals( examined.getDisplayName() ) ) - { + for (Description unused : UNUSED_DESCRIPTIONS) { + if (unused != null && unused.getDisplayName().equals(examined.getDisplayName())) { return true; } } @@ -128,188 +124,156 @@ static boolean isUnusedDescription( Description examined ) } } - static void removeUnusedDescriptions( Collection examined ) - { - for ( Iterator it = examined.iterator(); it.hasNext(); ) - { - if ( isUnusedDescription( it.next() ) ) - { + static void removeUnusedDescriptions(Collection examined) { + for (Iterator it = examined.iterator(); it.hasNext(); ) { + if (isUnusedDescription(it.next())) { it.remove(); } } } - private static Concurrency concurrencyForUnlimitedThreads( JUnitCoreParameters params ) - { + private static Concurrency concurrencyForUnlimitedThreads(JUnitCoreParameters params) { Concurrency concurrency = new Concurrency(); - concurrency.suites = params.isParallelSuites() ? threadCountSuites( params ) : 0; - concurrency.classes = params.isParallelClasses() ? threadCountClasses( params ) : 0; - concurrency.methods = params.isParallelMethods() ? threadCountMethods( params ) : 0; + concurrency.suites = params.isParallelSuites() ? threadCountSuites(params) : 0; + concurrency.classes = params.isParallelClasses() ? threadCountClasses(params) : 0; + concurrency.methods = params.isParallelMethods() ? threadCountMethods(params) : 0; concurrency.capacity = Integer.MAX_VALUE; return concurrency; } - private static Concurrency estimateConcurrency( JUnitCoreParameters params, RunnerCounter counts ) - { + private static Concurrency estimateConcurrency(JUnitCoreParameters params, RunnerCounter counts) { final Concurrency concurrency = new Concurrency(); - final int parallelEntities = countParallelEntities( params ); - concurrency.capacity = multiplyByCoreCount( params, params.getThreadCount() ); - if ( parallelEntities == 1 || counts == null || counts.classes == 0 ) - { + final int parallelEntities = countParallelEntities(params); + concurrency.capacity = multiplyByCoreCount(params, params.getThreadCount()); + if (parallelEntities == 1 || counts == null || counts.classes == 0) { // Estimate parallel thread counts. double ratio = 1d / parallelEntities; - int threads = multiplyByCoreCount( params, ratio * params.getThreadCount() ); - concurrency.suites = params.isParallelSuites() ? minSuites( threads, counts ) : 0; - concurrency.classes = params.isParallelClasses() ? minClasses( threads, counts ) : 0; - concurrency.methods = params.isParallelMethods() ? minMethods( threads, counts ) : 0; - if ( parallelEntities == 1 ) - { + int threads = multiplyByCoreCount(params, ratio * params.getThreadCount()); + concurrency.suites = params.isParallelSuites() ? minSuites(threads, counts) : 0; + concurrency.classes = params.isParallelClasses() ? minClasses(threads, counts) : 0; + concurrency.methods = params.isParallelMethods() ? minMethods(threads, counts) : 0; + if (parallelEntities == 1) { concurrency.capacity = 0; + } else { + adjustLeaf(params, concurrency); } - else - { - adjustLeaf( params, concurrency ); - } - } - else - { + } else { // Try to allocate suites+classes+methods within threadCount, - concurrency.suites = params.isParallelSuites() ? toNonNegative( counts.suites ) : 0; - concurrency.classes = params.isParallelClasses() ? toNonNegative( counts.classes ) : 0; + concurrency.suites = params.isParallelSuites() ? toNonNegative(counts.suites) : 0; + concurrency.classes = params.isParallelClasses() ? toNonNegative(counts.classes) : 0; concurrency.methods = - params.isParallelMethods() ? toNonNegative( Math.ceil( counts.methods / (double) counts.classes ) ) : 0; - double sum = toNonNegative( concurrency.suites + concurrency.classes + concurrency.methods ); - if ( concurrency.capacity < sum && sum != 0 ) - { + params.isParallelMethods() ? toNonNegative(Math.ceil(counts.methods / (double) counts.classes)) : 0; + double sum = toNonNegative(concurrency.suites + concurrency.classes + concurrency.methods); + if (concurrency.capacity < sum && sum != 0) { // otherwise allocate them using the weighting factor < 1. double weight = concurrency.capacity / sum; concurrency.suites *= weight; concurrency.classes *= weight; concurrency.methods *= weight; } - adjustLeaf( params, concurrency ); + adjustLeaf(params, concurrency); } return concurrency; } - private static Concurrency concurrencyFromAllThreadCountsButUnspecifiedLeafCount( JUnitCoreParameters params, - RunnerCounter counts ) - { + private static Concurrency concurrencyFromAllThreadCountsButUnspecifiedLeafCount( + JUnitCoreParameters params, RunnerCounter counts) { Concurrency concurrency = new Concurrency(); concurrency.suites = params.isParallelSuites() ? params.getThreadCountSuites() : 0; - concurrency.suites = params.isParallelSuites() ? multiplyByCoreCount( params, concurrency.suites ) : 0; + concurrency.suites = params.isParallelSuites() ? multiplyByCoreCount(params, concurrency.suites) : 0; concurrency.classes = params.isParallelClasses() ? params.getThreadCountClasses() : 0; - concurrency.classes = params.isParallelClasses() ? multiplyByCoreCount( params, concurrency.classes ) : 0; + concurrency.classes = params.isParallelClasses() ? multiplyByCoreCount(params, concurrency.classes) : 0; concurrency.methods = params.isParallelMethods() ? params.getThreadCountMethods() : 0; - concurrency.methods = params.isParallelMethods() ? multiplyByCoreCount( params, concurrency.methods ) : 0; - concurrency.capacity = multiplyByCoreCount( params, params.getThreadCount() ); + concurrency.methods = params.isParallelMethods() ? multiplyByCoreCount(params, concurrency.methods) : 0; + concurrency.capacity = multiplyByCoreCount(params, params.getThreadCount()); - if ( counts != null ) - { - concurrency.suites = toNonNegative( Math.min( concurrency.suites, counts.suites ) ); - concurrency.classes = toNonNegative( Math.min( concurrency.classes, counts.classes ) ); + if (counts != null) { + concurrency.suites = toNonNegative(Math.min(concurrency.suites, counts.suites)); + concurrency.classes = toNonNegative(Math.min(concurrency.classes, counts.classes)); } - setLeafInfinite( params, concurrency ); + setLeafInfinite(params, concurrency); return concurrency; } - private static Concurrency concurrencyFromAllThreadCounts( JUnitCoreParameters params ) - { + private static Concurrency concurrencyFromAllThreadCounts(JUnitCoreParameters params) { Concurrency concurrency = new Concurrency(); concurrency.suites = params.isParallelSuites() ? params.getThreadCountSuites() : 0; concurrency.classes = params.isParallelClasses() ? params.getThreadCountClasses() : 0; concurrency.methods = params.isParallelMethods() ? params.getThreadCountMethods() : 0; concurrency.capacity = params.getThreadCount(); - double all = sumThreadCounts( concurrency ); + double all = sumThreadCounts(concurrency); - concurrency.suites = params.isParallelSuites() ? multiplyByCoreCount( params, concurrency.capacity * ( - concurrency.suites / all ) ) : 0; + concurrency.suites = params.isParallelSuites() + ? multiplyByCoreCount(params, concurrency.capacity * (concurrency.suites / all)) + : 0; - concurrency.classes = params.isParallelClasses() ? multiplyByCoreCount( params, concurrency.capacity * ( - concurrency.classes / all ) ) : 0; + concurrency.classes = params.isParallelClasses() + ? multiplyByCoreCount(params, concurrency.capacity * (concurrency.classes / all)) + : 0; - concurrency.methods = params.isParallelMethods() ? multiplyByCoreCount( params, concurrency.capacity * ( - concurrency.methods / all ) ) : 0; + concurrency.methods = params.isParallelMethods() + ? multiplyByCoreCount(params, concurrency.capacity * (concurrency.methods / all)) + : 0; - concurrency.capacity = multiplyByCoreCount( params, concurrency.capacity ); - adjustPrecisionInLeaf( params, concurrency ); + concurrency.capacity = multiplyByCoreCount(params, concurrency.capacity); + adjustPrecisionInLeaf(params, concurrency); return concurrency; } - private static Concurrency concurrencyFromThreadCounts( JUnitCoreParameters params ) - { + private static Concurrency concurrencyFromThreadCounts(JUnitCoreParameters params) { Concurrency concurrency = new Concurrency(); - concurrency.suites = params.isParallelSuites() ? threadCountSuites( params ) : 0; - concurrency.classes = params.isParallelClasses() ? threadCountClasses( params ) : 0; - concurrency.methods = params.isParallelMethods() ? threadCountMethods( params ) : 0; - concurrency.capacity = toNonNegative( sumThreadCounts( concurrency ) ); + concurrency.suites = params.isParallelSuites() ? threadCountSuites(params) : 0; + concurrency.classes = params.isParallelClasses() ? threadCountClasses(params) : 0; + concurrency.methods = params.isParallelMethods() ? threadCountMethods(params) : 0; + concurrency.capacity = toNonNegative(sumThreadCounts(concurrency)); return concurrency; } - private static int countParallelEntities( JUnitCoreParameters params ) - { + private static int countParallelEntities(JUnitCoreParameters params) { int count = 0; - if ( params.isParallelSuites() ) - { + if (params.isParallelSuites()) { count++; } - if ( params.isParallelClasses() ) - { + if (params.isParallelClasses()) { count++; } - if ( params.isParallelMethods() ) - { + if (params.isParallelMethods()) { count++; } return count; } - private static void adjustPrecisionInLeaf( JUnitCoreParameters params, Concurrency concurrency ) - { - if ( params.isParallelMethods() ) - { + private static void adjustPrecisionInLeaf(JUnitCoreParameters params, Concurrency concurrency) { + if (params.isParallelMethods()) { concurrency.methods = concurrency.capacity - concurrency.suites - concurrency.classes; - } - else if ( params.isParallelClasses() ) - { + } else if (params.isParallelClasses()) { concurrency.classes = concurrency.capacity - concurrency.suites; } } - private static void adjustLeaf( JUnitCoreParameters params, Concurrency concurrency ) - { - if ( params.isParallelMethods() ) - { + private static void adjustLeaf(JUnitCoreParameters params, Concurrency concurrency) { + if (params.isParallelMethods()) { concurrency.methods = Integer.MAX_VALUE; - } - else if ( params.isParallelClasses() ) - { + } else if (params.isParallelClasses()) { concurrency.classes = Integer.MAX_VALUE; } } - private static void setLeafInfinite( JUnitCoreParameters params, Concurrency concurrency ) - { - if ( params.isParallelMethods() ) - { + private static void setLeafInfinite(JUnitCoreParameters params, Concurrency concurrency) { + if (params.isParallelMethods()) { concurrency.methods = Integer.MAX_VALUE; - } - else if ( params.isParallelClasses() ) - { + } else if (params.isParallelClasses()) { concurrency.classes = Integer.MAX_VALUE; - } - else if ( params.isParallelSuites() ) - { + } else if (params.isParallelSuites()) { concurrency.suites = Integer.MAX_VALUE; } } - private static boolean isLeafUnspecified( JUnitCoreParameters params ) - { + private static boolean isLeafUnspecified(JUnitCoreParameters params) { int maskOfParallel = params.isParallelSuites() ? 4 : 0; maskOfParallel |= params.isParallelClasses() ? 2 : 0; maskOfParallel |= params.isParallelMethods() ? 1 : 0; @@ -320,78 +284,67 @@ private static boolean isLeafUnspecified( JUnitCoreParameters params ) maskOfConcurrency &= maskOfParallel; - int leaf = Integer.lowestOneBit( maskOfParallel ); + int leaf = Integer.lowestOneBit(maskOfParallel); return maskOfConcurrency == maskOfParallel - leaf; } - private static double sumThreadCounts( Concurrency concurrency ) - { + private static double sumThreadCounts(Concurrency concurrency) { double sum = concurrency.suites; sum += concurrency.classes; sum += concurrency.methods; return sum; } - private static boolean hasThreadCounts( JUnitCoreParameters jUnitCoreParameters ) - { - return ( jUnitCoreParameters.isParallelSuites() && jUnitCoreParameters.getThreadCountSuites() > 0 ) - || ( jUnitCoreParameters.isParallelClasses() && jUnitCoreParameters.getThreadCountClasses() > 0 ) - || ( jUnitCoreParameters.isParallelMethods() && jUnitCoreParameters.getThreadCountMethods() > 0 ); + private static boolean hasThreadCounts(JUnitCoreParameters jUnitCoreParameters) { + return (jUnitCoreParameters.isParallelSuites() && jUnitCoreParameters.getThreadCountSuites() > 0) + || (jUnitCoreParameters.isParallelClasses() && jUnitCoreParameters.getThreadCountClasses() > 0) + || (jUnitCoreParameters.isParallelMethods() && jUnitCoreParameters.getThreadCountMethods() > 0); } - private static boolean hasThreadCount( JUnitCoreParameters jUnitCoreParameters ) - { + private static boolean hasThreadCount(JUnitCoreParameters jUnitCoreParameters) { return jUnitCoreParameters.getThreadCount() > 0; } - private static int threadCountMethods( JUnitCoreParameters jUnitCoreParameters ) - { - return multiplyByCoreCount( jUnitCoreParameters, jUnitCoreParameters.getThreadCountMethods() ); + private static int threadCountMethods(JUnitCoreParameters jUnitCoreParameters) { + return multiplyByCoreCount(jUnitCoreParameters, jUnitCoreParameters.getThreadCountMethods()); } - private static int threadCountClasses( JUnitCoreParameters jUnitCoreParameters ) - { - return multiplyByCoreCount( jUnitCoreParameters, jUnitCoreParameters.getThreadCountClasses() ); + private static int threadCountClasses(JUnitCoreParameters jUnitCoreParameters) { + return multiplyByCoreCount(jUnitCoreParameters, jUnitCoreParameters.getThreadCountClasses()); } - private static int threadCountSuites( JUnitCoreParameters jUnitCoreParameters ) - { - return multiplyByCoreCount( jUnitCoreParameters, jUnitCoreParameters.getThreadCountSuites() ); + private static int threadCountSuites(JUnitCoreParameters jUnitCoreParameters) { + return multiplyByCoreCount(jUnitCoreParameters, jUnitCoreParameters.getThreadCountSuites()); } - private static int multiplyByCoreCount( JUnitCoreParameters jUnitCoreParameters, double threadsPerCore ) - { - double numberOfThreads = - jUnitCoreParameters.isPerCoreThreadCount() ? threadsPerCore * (double) availableProcessors : threadsPerCore; + private static int multiplyByCoreCount(JUnitCoreParameters jUnitCoreParameters, double threadsPerCore) { + double numberOfThreads = jUnitCoreParameters.isPerCoreThreadCount() + ? threadsPerCore * (double) availableProcessors + : threadsPerCore; - return numberOfThreads > 0 ? toNonNegative( numberOfThreads ) : Integer.MAX_VALUE; + return numberOfThreads > 0 ? toNonNegative(numberOfThreads) : Integer.MAX_VALUE; } - private static int minSuites( int threads, RunnerCounter counts ) - { + private static int minSuites(int threads, RunnerCounter counts) { long count = counts == null ? Integer.MAX_VALUE : counts.suites; - return Math.min( threads, toNonNegative( count ) ); + return Math.min(threads, toNonNegative(count)); } - private static int minClasses( int threads, RunnerCounter counts ) - { + private static int minClasses(int threads, RunnerCounter counts) { long count = counts == null ? Integer.MAX_VALUE : counts.classes; - return Math.min( threads, toNonNegative( count ) ); + return Math.min(threads, toNonNegative(count)); } - private static int minMethods( int threads, RunnerCounter counts ) - { + private static int minMethods(int threads, RunnerCounter counts) { long count = counts == null ? Integer.MAX_VALUE : counts.methods; - return Math.min( threads, toNonNegative( count ) ); + return Math.min(threads, toNonNegative(count)); } - private static int toNonNegative( long num ) - { - return (int) Math.min( num > 0 ? num : 0, Integer.MAX_VALUE ); + private static int toNonNegative(long num) { + return (int) Math.min(num > 0 ? num : 0, Integer.MAX_VALUE); } - private static int toNonNegative( double num ) - { - return (int) Math.min( num > 0 ? num : 0, Integer.MAX_VALUE ); + private static int toNonNegative(double num) { + return (int) Math.min(num > 0 ? num : 0, Integer.MAX_VALUE); } } diff --git a/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/pc/RunnerCounter.java b/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/pc/RunnerCounter.java index 26f5fa0f11..c20795ee83 100644 --- a/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/pc/RunnerCounter.java +++ b/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/pc/RunnerCounter.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.junitcore.pc; /* @@ -26,18 +44,16 @@ * @see ParallelComputerBuilder * @since 2.17 */ -final class RunnerCounter -{ +final class RunnerCounter { final long suites; final long classes; final long methods; - RunnerCounter( long suites, long classes, long methods ) - { + RunnerCounter(long suites, long classes, long methods) { this.suites = suites; this.classes = classes; this.methods = methods; } -} \ No newline at end of file +} diff --git a/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/pc/Scheduler.java b/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/pc/Scheduler.java index 61222a29fa..78ffcd29f5 100644 --- a/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/pc/Scheduler.java +++ b/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/pc/Scheduler.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.junitcore.pc; /* @@ -19,10 +37,6 @@ * under the License. */ -import org.apache.maven.plugin.surefire.log.api.ConsoleLogger; -import org.junit.runner.Description; -import org.junit.runners.model.RunnerScheduler; - import java.util.Collection; import java.util.Set; import java.util.concurrent.ConcurrentLinkedQueue; @@ -31,6 +45,10 @@ import java.util.concurrent.RejectedExecutionHandler; import java.util.concurrent.ThreadPoolExecutor; +import org.apache.maven.plugin.surefire.log.api.ConsoleLogger; +import org.junit.runner.Description; +import org.junit.runners.model.RunnerScheduler; + /** * Schedules tests, controls thread resources, awaiting tests and other schedulers finished, and * a master scheduler can shutdown slaves. @@ -43,9 +61,7 @@ * @author Tibor Digana (tibor17) * @since 2.16 */ -public class Scheduler - implements RunnerScheduler -{ +public class Scheduler implements RunnerScheduler { private final Balancer balancer; private final SchedulingStrategy strategy; @@ -74,9 +90,8 @@ public class Scheduler * @param description JUnit description of class * @param strategy scheduling strategy */ - public Scheduler( ConsoleLogger logger, Description description, SchedulingStrategy strategy ) - { - this( logger, description, strategy, -1 ); + public Scheduler(ConsoleLogger logger, Description description, SchedulingStrategy strategy) { + this(logger, description, strategy, -1); } /** @@ -92,9 +107,8 @@ public Scheduler( ConsoleLogger logger, Description description, SchedulingStrat * @param concurrency determines maximum concurrent children scheduled a time via {@link #schedule(Runnable)} * @throws NullPointerException if null strategy */ - public Scheduler( ConsoleLogger logger, Description description, SchedulingStrategy strategy, int concurrency ) - { - this( logger, description, strategy, BalancerFactory.createBalancer( concurrency ) ); + public Scheduler(ConsoleLogger logger, Description description, SchedulingStrategy strategy, int concurrency) { + this(logger, description, strategy, BalancerFactory.createBalancer(concurrency)); } /** @@ -112,9 +126,8 @@ public Scheduler( ConsoleLogger logger, Description description, SchedulingStrat * @param balancer determines maximum concurrent children scheduled a time via {@link #schedule(Runnable)} * @throws NullPointerException if null strategy or balancer */ - public Scheduler( ConsoleLogger logger, Description description, SchedulingStrategy strategy, Balancer balancer ) - { - strategy.setDefaultShutdownHandler( newShutdownHandler() ); + public Scheduler(ConsoleLogger logger, Description description, SchedulingStrategy strategy, Balancer balancer) { + strategy.setDefaultShutdownHandler(newShutdownHandler()); this.logger = logger; this.description = description; this.strategy = strategy; @@ -133,12 +146,15 @@ public Scheduler( ConsoleLogger logger, Description description, SchedulingStrat * @param balancer determines maximum concurrent children scheduled a time via {@link #schedule(Runnable)} * @throws NullPointerException if null masterScheduler, strategy or balancer */ - public Scheduler( ConsoleLogger logger, Description description, Scheduler masterScheduler, - SchedulingStrategy strategy, Balancer balancer ) - { - this( logger, description, strategy, balancer ); - strategy.setDefaultShutdownHandler( newShutdownHandler() ); - masterScheduler.register( this ); + public Scheduler( + ConsoleLogger logger, + Description description, + Scheduler masterScheduler, + SchedulingStrategy strategy, + Balancer balancer) { + this(logger, description, strategy, balancer); + strategy.setDefaultShutdownHandler(newShutdownHandler()); + masterScheduler.register(this); } /** @@ -153,12 +169,15 @@ public Scheduler( ConsoleLogger logger, Description description, Scheduler maste * @see #Scheduler(ConsoleLogger, org.junit.runner.Description, SchedulingStrategy) * @see #Scheduler(ConsoleLogger, org.junit.runner.Description, SchedulingStrategy, int) */ - public Scheduler( ConsoleLogger logger, Description description, Scheduler masterScheduler, - SchedulingStrategy strategy, int concurrency ) - { - this( logger, description, strategy, concurrency ); - strategy.setDefaultShutdownHandler( newShutdownHandler() ); - masterScheduler.register( this ); + public Scheduler( + ConsoleLogger logger, + Description description, + Scheduler masterScheduler, + SchedulingStrategy strategy, + int concurrency) { + this(logger, description, strategy, concurrency); + strategy.setDefaultShutdownHandler(newShutdownHandler()); + masterScheduler.register(this); } /** @@ -172,17 +191,14 @@ public Scheduler( ConsoleLogger logger, Description description, Scheduler maste * @param masterScheduler parent scheduler * @param strategy scheduling strategy */ - public Scheduler( ConsoleLogger logger, Description description, Scheduler masterScheduler, - SchedulingStrategy strategy ) - { - this( logger, description, masterScheduler, strategy, 0 ); + public Scheduler( + ConsoleLogger logger, Description description, Scheduler masterScheduler, SchedulingStrategy strategy) { + this(logger, description, masterScheduler, strategy, 0); } - private void setController( Controller masterController ) - { - if ( masterController == null ) - { - throw new NullPointerException( "null ExecutionController" ); + private void setController(Controller masterController) { + if (masterController == null) { + throw new NullPointerException("null ExecutionController"); } this.masterController = masterController; } @@ -191,17 +207,14 @@ private void setController( Controller masterController ) * @param slave a slave scheduler to register * @return {@code true} if successfully registered the slave. */ - private boolean register( Scheduler slave ) - { + private boolean register(Scheduler slave) { boolean canRegister = slave != null && slave != this; - if ( canRegister ) - { - Controller controller = new Controller( slave ); - canRegister = !slaves.contains( controller ); - if ( canRegister ) - { - slaves.add( controller ); - slave.setController( controller ); + if (canRegister) { + Controller controller = new Controller(slave); + canRegister = !slaves.contains(controller); + if (canRegister) { + slaves.add(controller); + slave.setController(controller); } } return canRegister; @@ -210,19 +223,16 @@ private boolean register( Scheduler slave ) /** * @return {@code true} if new tasks can be scheduled. */ - private boolean canSchedule() - { - return !shutdown && ( masterController == null || masterController.canSchedule() ); + private boolean canSchedule() { + return !shutdown && (masterController == null || masterController.canSchedule()); } - protected void logQuietly( Throwable t ) - { - logger.error( t ); + protected void logQuietly(Throwable t) { + logger.error(t); } - protected void logQuietly( String msg ) - { - logger.warning( msg ); + protected void logQuietly(String msg) { + logger.warning(msg); } /** @@ -235,12 +245,11 @@ protected void logQuietly( String msg ) * @param stopNow if {@code true} interrupts waiting test methods * @return collection of descriptions started before shutting down */ - protected ShutdownResult describeStopped( boolean stopNow ) - { + protected ShutdownResult describeStopped(boolean stopNow) { Collection executedTests = new ConcurrentLinkedQueue<>(); Collection incompleteTests = new ConcurrentLinkedQueue<>(); - stop( executedTests, incompleteTests, false, stopNow ); - return new ShutdownResult( executedTests, incompleteTests ); + stop(executedTests, incompleteTests, false, stopNow); + return new ShutdownResult(executedTests, incompleteTests); } /** @@ -259,152 +268,104 @@ protected ShutdownResult describeStopped( boolean stopNow ) * {@link java.util.concurrent.Future#cancel(boolean) Future#cancel(true)} or * {@link Thread#interrupt()}. */ - private void stop( Collection executedTests, Collection incompleteTests, - boolean tryCancelFutures, boolean stopNow ) - { + private void stop( + Collection executedTests, + Collection incompleteTests, + boolean tryCancelFutures, + boolean stopNow) { shutdown = true; - try - { - if ( started && !ParallelComputerUtil.isUnusedDescription( description ) ) - { - if ( executedTests != null ) - { - executedTests.add( description ); + try { + if (started && !ParallelComputerUtil.isUnusedDescription(description)) { + if (executedTests != null) { + executedTests.add(description); } - if ( incompleteTests != null && !finished ) - { - incompleteTests.add( description ); + if (incompleteTests != null && !finished) { + incompleteTests.add(description); } } - for ( Controller slave : slaves ) - { - slave.stop( executedTests, incompleteTests, tryCancelFutures, stopNow ); + for (Controller slave : slaves) { + slave.stop(executedTests, incompleteTests, tryCancelFutures, stopNow); } - } - finally - { - try - { + } finally { + try { balancer.releaseAllPermits(); - } - finally - { - if ( stopNow ) - { + } finally { + if (stopNow) { strategy.stopNow(); - } - else if ( tryCancelFutures ) - { + } else if (tryCancelFutures) { strategy.stop(); - } - else - { + } else { strategy.disable(); } } } } - protected boolean shutdownThreadPoolsAwaitingKilled() - { - if ( masterController == null ) - { - stop( null, null, true, false ); + protected boolean shutdownThreadPoolsAwaitingKilled() { + if (masterController == null) { + stop(null, null, true, false); boolean isNotInterrupted = true; - if ( strategy != null ) - { + if (strategy != null) { isNotInterrupted = strategy.destroy(); } - for ( Controller slave : slaves ) - { + for (Controller slave : slaves) { isNotInterrupted &= slave.destroy(); } return isNotInterrupted; - } - else - { - throw new UnsupportedOperationException( "cannot call this method if this is not a master scheduler" ); + } else { + throw new UnsupportedOperationException("cannot call this method if this is not a master scheduler"); } } - protected void beforeExecute() - { - } + protected void beforeExecute() {} - protected void afterExecute() - { - } + protected void afterExecute() {} @Override - public void schedule( Runnable childStatement ) - { - if ( childStatement == null ) - { - logQuietly( "cannot schedule null" ); - } - else if ( canSchedule() && strategy.canSchedule() ) - { - try - { + public void schedule(Runnable childStatement) { + if (childStatement == null) { + logQuietly("cannot schedule null"); + } else if (canSchedule() && strategy.canSchedule()) { + try { boolean isNotInterrupted = balancer.acquirePermit(); - if ( isNotInterrupted && !shutdown ) - { - Runnable task = wrapTask( childStatement ); - strategy.schedule( task ); + if (isNotInterrupted && !shutdown) { + Runnable task = wrapTask(childStatement); + strategy.schedule(task); started = true; } - } - catch ( RejectedExecutionException e ) - { - stop( null, null, true, false ); - } - catch ( Throwable t ) - { + } catch (RejectedExecutionException e) { + stop(null, null, true, false); + } catch (Throwable t) { balancer.releasePermit(); - logQuietly( t ); + logQuietly(t); } } } @Override - public void finished() - { - try - { + public void finished() { + try { strategy.finished(); - } - catch ( InterruptedException e ) - { - logQuietly( e ); - } - finally - { + } catch (InterruptedException e) { + logQuietly(e); + } finally { finished = true; } } - private Runnable wrapTask( final Runnable task ) - { - return new Runnable() - { + private Runnable wrapTask(final Runnable task) { + return new Runnable() { @Override - public void run() - { - try - { + public void run() { + try { beforeExecute(); task.run(); - } - finally - { - try - { + } finally { + try { afterExecute(); - } - finally - { + } finally { balancer.releasePermit(); } } @@ -412,55 +373,50 @@ public void run() }; } - protected ShutdownHandler newShutdownHandler() - { + protected ShutdownHandler newShutdownHandler() { return new ShutdownHandler(); } /** * If this is a master scheduler, the slaves can stop scheduling by the master through the controller. */ - private final class Controller - { + private final class Controller { private final Scheduler slave; - private Controller( Scheduler slave ) - { + private Controller(Scheduler slave) { this.slave = slave; } /** * @return {@code true} if new children can be scheduled. */ - boolean canSchedule() - { + boolean canSchedule() { return Scheduler.this.canSchedule(); } - void stop( Collection executedTests, Collection incompleteTests, - boolean tryCancelFutures, boolean shutdownNow ) - { - slave.stop( executedTests, incompleteTests, tryCancelFutures, shutdownNow ); + void stop( + Collection executedTests, + Collection incompleteTests, + boolean tryCancelFutures, + boolean shutdownNow) { + slave.stop(executedTests, incompleteTests, tryCancelFutures, shutdownNow); } /** * @see org.apache.maven.surefire.junitcore.pc.Destroyable#destroy() */ - boolean destroy() - { + boolean destroy() { return slave.strategy.destroy(); } @Override - public int hashCode() - { + public int hashCode() { return slave.hashCode(); } @Override - public boolean equals( Object o ) - { - return o == this || ( o instanceof Controller ) && slave.equals( ( (Controller) o ).slave ); + public boolean equals(Object o) { + return o == this || (o instanceof Controller) && slave.equals(((Controller) o).slave); } } @@ -472,32 +428,25 @@ public boolean equals( Object o ) * {@link #describeStopped(boolean)}. The method {@link #describeStopped(boolean)} is again shutting down children * schedulers recursively as well. */ - public class ShutdownHandler - implements RejectedExecutionHandler - { + public class ShutdownHandler implements RejectedExecutionHandler { private volatile RejectedExecutionHandler poolHandler; - protected ShutdownHandler() - { + protected ShutdownHandler() { poolHandler = null; } - public void setRejectedExecutionHandler( RejectedExecutionHandler poolHandler ) - { + public void setRejectedExecutionHandler(RejectedExecutionHandler poolHandler) { this.poolHandler = poolHandler; } @Override - public void rejectedExecution( Runnable r, ThreadPoolExecutor executor ) - { - if ( executor.isShutdown() ) - { - Scheduler.this.stop( null, null, true, false ); + public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) { + if (executor.isShutdown()) { + Scheduler.this.stop(null, null, true, false); } final RejectedExecutionHandler poolHandler = this.poolHandler; - if ( poolHandler != null ) - { - poolHandler.rejectedExecution( r, executor ); + if (poolHandler != null) { + poolHandler.rejectedExecution(r, executor); } } } diff --git a/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/pc/SchedulingStrategies.java b/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/pc/SchedulingStrategies.java index b021d9e7b9..78ebcb5fa6 100644 --- a/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/pc/SchedulingStrategies.java +++ b/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/pc/SchedulingStrategies.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.junitcore.pc; /* @@ -19,30 +37,28 @@ * under the License. */ -import org.apache.maven.plugin.surefire.log.api.ConsoleLogger; -import org.apache.maven.surefire.api.util.internal.DaemonThreadFactory; - import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; +import org.apache.maven.plugin.surefire.log.api.ConsoleLogger; +import org.apache.maven.surefire.api.util.internal.DaemonThreadFactory; + /** * The factory of {@link SchedulingStrategy}. * * @author Tibor Digana (tibor17) * @since 2.16 */ -public class SchedulingStrategies -{ +public class SchedulingStrategies { private static final ThreadFactory DAEMON_THREAD_FACTORY = DaemonThreadFactory.newDaemonThreadFactory(); /** * @param logger current error logger * @return sequentially executing strategy */ - public static SchedulingStrategy createInvokerStrategy( ConsoleLogger logger ) - { - return new InvokerStrategy( logger ); + public static SchedulingStrategy createInvokerStrategy(ConsoleLogger logger) { + return new InvokerStrategy(logger); } /** @@ -50,19 +66,16 @@ public static SchedulingStrategy createInvokerStrategy( ConsoleLogger logger ) * @param nThreads fixed pool capacity * @return parallel scheduling strategy */ - public static SchedulingStrategy createParallelStrategy( ConsoleLogger logger, int nThreads ) - { - return new NonSharedThreadPoolStrategy( logger, - Executors.newFixedThreadPool( nThreads, DAEMON_THREAD_FACTORY ) ); + public static SchedulingStrategy createParallelStrategy(ConsoleLogger logger, int nThreads) { + return new NonSharedThreadPoolStrategy(logger, Executors.newFixedThreadPool(nThreads, DAEMON_THREAD_FACTORY)); } /** * @param logger current error logger * @return parallel scheduling strategy with unbounded capacity */ - public static SchedulingStrategy createParallelStrategyUnbounded( ConsoleLogger logger ) - { - return new NonSharedThreadPoolStrategy( logger, Executors.newCachedThreadPool( DAEMON_THREAD_FACTORY ) ); + public static SchedulingStrategy createParallelStrategyUnbounded(ConsoleLogger logger) { + return new NonSharedThreadPoolStrategy(logger, Executors.newCachedThreadPool(DAEMON_THREAD_FACTORY)); } /** @@ -78,12 +91,10 @@ public static SchedulingStrategy createParallelStrategyUnbounded( ConsoleLogger * @return parallel strategy with shared thread pool * @throws NullPointerException if threadPool is null */ - public static SchedulingStrategy createParallelSharedStrategy( ConsoleLogger logger, ExecutorService threadPool ) - { - if ( threadPool == null ) - { - throw new NullPointerException( "null threadPool in #createParallelSharedStrategy" ); + public static SchedulingStrategy createParallelSharedStrategy(ConsoleLogger logger, ExecutorService threadPool) { + if (threadPool == null) { + throw new NullPointerException("null threadPool in #createParallelSharedStrategy"); } - return new SharedThreadPoolStrategy( logger, threadPool ); + return new SharedThreadPoolStrategy(logger, threadPool); } } diff --git a/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/pc/SchedulingStrategy.java b/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/pc/SchedulingStrategy.java index 08e4a02cc7..2db52b4fec 100644 --- a/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/pc/SchedulingStrategy.java +++ b/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/pc/SchedulingStrategy.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.junitcore.pc; /* @@ -19,10 +37,10 @@ * under the License. */ -import org.apache.maven.plugin.surefire.log.api.ConsoleLogger; - import java.util.concurrent.atomic.AtomicBoolean; +import org.apache.maven.plugin.surefire.log.api.ConsoleLogger; + /** * Specifies the strategy of scheduling whether sequential, or parallel. * The strategy may use a thread pool shared with other strategies. @@ -35,16 +53,13 @@ * @author Tibor Digana (tibor17) * @since 2.16 */ -public abstract class SchedulingStrategy - implements Destroyable -{ +public abstract class SchedulingStrategy implements Destroyable { - private final AtomicBoolean canSchedule = new AtomicBoolean( true ); + private final AtomicBoolean canSchedule = new AtomicBoolean(true); private final ConsoleLogger logger; - protected SchedulingStrategy( ConsoleLogger logger ) - { + protected SchedulingStrategy(ConsoleLogger logger) { this.logger = logger; } @@ -58,7 +73,7 @@ protected SchedulingStrategy( ConsoleLogger logger ) * @see org.junit.runners.model.RunnerScheduler#schedule(Runnable) * @see java.util.concurrent.Executor#execute(Runnable) */ - protected abstract void schedule( Runnable task ); + protected abstract void schedule(Runnable task); /** * Waiting for scheduled tasks to finish. @@ -71,8 +86,7 @@ protected SchedulingStrategy( ConsoleLogger logger ) * for scheduled tasks to finish * @see org.junit.runners.model.RunnerScheduler#finished() */ - protected abstract boolean finished() - throws InterruptedException; + protected abstract boolean finished() throws InterruptedException; /** * Stops scheduling new tasks (e.g. by {@link java.util.concurrent.ExecutorService#shutdown()} @@ -97,8 +111,7 @@ protected abstract boolean finished() * pool was shutdown externally). * @see java.util.concurrent.ExecutorService#shutdownNow() */ - protected boolean stopNow() - { + protected boolean stopNow() { return stop(); } @@ -107,14 +120,11 @@ protected boolean stopNow() * The method {@link #canSchedule()} atomically returns {@code false}. * @return {@code true} if {@link #canSchedule()} has return {@code true} on the beginning of this method call. */ - protected boolean disable() - { - return canSchedule.getAndSet( false ); + protected boolean disable() { + return canSchedule.getAndSet(false); } - protected void setDefaultShutdownHandler( Scheduler.ShutdownHandler handler ) - { - } + protected void setDefaultShutdownHandler(Scheduler.ShutdownHandler handler) {} /** * @return {@code true} if a thread pool associated with this strategy @@ -125,13 +135,11 @@ protected void setDefaultShutdownHandler( Scheduler.ShutdownHandler handler ) /** * @return {@code true} unless stopped, finished or disabled. */ - protected boolean canSchedule() - { + protected boolean canSchedule() { return canSchedule.get(); } - protected void logQuietly( Throwable t ) - { - logger.error( t ); + protected void logQuietly(Throwable t) { + logger.error(t); } } diff --git a/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/pc/SharedThreadPoolStrategy.java b/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/pc/SharedThreadPoolStrategy.java index d3af15ce56..178d3eeb86 100644 --- a/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/pc/SharedThreadPoolStrategy.java +++ b/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/pc/SharedThreadPoolStrategy.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.junitcore.pc; /* @@ -19,14 +37,14 @@ * under the License. */ -import org.apache.maven.plugin.surefire.log.api.ConsoleLogger; - import java.util.concurrent.CancellationException; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; +import org.apache.maven.plugin.surefire.log.api.ConsoleLogger; + /** * Parallel strategy for shared thread pool in private package. * @@ -34,46 +52,31 @@ * @see AbstractThreadPoolStrategy * @since 2.16 */ -final class SharedThreadPoolStrategy - extends AbstractThreadPoolStrategy -{ - SharedThreadPoolStrategy( ConsoleLogger logger, ExecutorService threadPool ) - { - super( logger, threadPool, new ConcurrentLinkedQueue>() ); +final class SharedThreadPoolStrategy extends AbstractThreadPoolStrategy { + SharedThreadPoolStrategy(ConsoleLogger logger, ExecutorService threadPool) { + super(logger, threadPool, new ConcurrentLinkedQueue>()); } @Override - public boolean hasSharedThreadPool() - { + public boolean hasSharedThreadPool() { return true; } @Override - public boolean finished() - throws InterruptedException - { + public boolean finished() throws InterruptedException { boolean wasRunningAll = disable(); - for ( Future futureResult : getFutureResults() ) - { - try - { + for (Future futureResult : getFutureResults()) { + try { futureResult.get(); - } - catch ( InterruptedException e ) - { + } catch (InterruptedException e) { // after called external ExecutorService#shutdownNow() wasRunningAll = false; - } - catch ( ExecutionException e ) - { + } catch (ExecutionException e) { // JUnit core throws exception. - if ( e.getCause() != null ) - { - logQuietly( e.getCause() ); + if (e.getCause() != null) { + logQuietly(e.getCause()); } - } - catch ( CancellationException e ) - { + } catch (CancellationException e) { /** * Cancelled by {@link Future#cancel(boolean)} in {@link stop()} and {@link stopNow()}. */ @@ -83,23 +86,19 @@ public boolean finished() } @Override - protected boolean stop() - { - return stop( false ); + protected boolean stop() { + return stop(false); } @Override - protected boolean stopNow() - { - return stop( true ); + protected boolean stopNow() { + return stop(true); } - private boolean stop( boolean interrupt ) - { + private boolean stop(boolean interrupt) { final boolean wasRunning = disable(); - for ( Future futureResult : getFutureResults() ) - { - futureResult.cancel( interrupt ); + for (Future futureResult : getFutureResults()) { + futureResult.cancel(interrupt); } return wasRunning; } diff --git a/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/pc/ShutdownResult.java b/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/pc/ShutdownResult.java index ef95be8e2c..3a19ac2cee 100644 --- a/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/pc/ShutdownResult.java +++ b/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/pc/ShutdownResult.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.junitcore.pc; /* @@ -19,11 +37,11 @@ * under the License. */ -import org.junit.runner.Description; - import java.util.Collection; import java.util.Collections; +import org.junit.runner.Description; + /** * Populates collection {@code triggeredTests} of descriptions started before shutting down. * Populates collection {@code incompleteTests} which describes started tests but unfinished due to abrupt shutdown. @@ -33,25 +51,21 @@ * @see Scheduler * @since 2.18 */ -public final class ShutdownResult -{ +public final class ShutdownResult { private final Collection triggeredTests; private final Collection incompleteTests; - public ShutdownResult( Collection triggeredTests, Collection incompleteTests ) - { + public ShutdownResult(Collection triggeredTests, Collection incompleteTests) { this.triggeredTests = triggeredTests == null ? Collections.emptySet() : triggeredTests; this.incompleteTests = incompleteTests == null ? Collections.emptySet() : incompleteTests; } - public Collection getTriggeredTests() - { + public Collection getTriggeredTests() { return triggeredTests; } - public Collection getIncompleteTests() - { + public Collection getIncompleteTests() { return incompleteTests; } } diff --git a/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/pc/ShutdownStatus.java b/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/pc/ShutdownStatus.java index d805e93e3e..a4422eb3e4 100644 --- a/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/pc/ShutdownStatus.java +++ b/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/pc/ShutdownStatus.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.junitcore.pc; /* @@ -30,35 +48,28 @@ * @see ParallelComputer * @since 2.18 */ -final class ShutdownStatus -{ - private final AtomicReference status = - new AtomicReference<>( ExecutionStatus.STARTED ); +final class ShutdownStatus { + private final AtomicReference status = new AtomicReference<>(ExecutionStatus.STARTED); private Future descriptionsBeforeShutdown; - boolean tryFinish() - { - return status.compareAndSet( ExecutionStatus.STARTED, ExecutionStatus.FINISHED ); + boolean tryFinish() { + return status.compareAndSet(ExecutionStatus.STARTED, ExecutionStatus.FINISHED); } - boolean tryTimeout() - { - return status.compareAndSet( ExecutionStatus.STARTED, ExecutionStatus.TIMEOUT ); + boolean tryTimeout() { + return status.compareAndSet(ExecutionStatus.STARTED, ExecutionStatus.TIMEOUT); } - boolean isTimeoutElapsed() - { + boolean isTimeoutElapsed() { return status.get() == ExecutionStatus.TIMEOUT; } - Future getDescriptionsBeforeShutdown() - { + Future getDescriptionsBeforeShutdown() { return descriptionsBeforeShutdown; } - void setDescriptionsBeforeShutdown( Future descriptionsBeforeShutdown ) - { + void setDescriptionsBeforeShutdown(Future descriptionsBeforeShutdown) { this.descriptionsBeforeShutdown = descriptionsBeforeShutdown; } -} \ No newline at end of file +} diff --git a/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/pc/SingleThreadScheduler.java b/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/pc/SingleThreadScheduler.java index f4c92b468a..36f04bab93 100644 --- a/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/pc/SingleThreadScheduler.java +++ b/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/pc/SingleThreadScheduler.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.junitcore.pc; /* @@ -19,11 +37,6 @@ * under the License. */ -import org.apache.maven.plugin.surefire.log.api.ConsoleLogger; -import org.apache.maven.surefire.api.util.internal.DaemonThreadFactory; -import org.junit.runner.Description; -import org.junit.runners.model.RunnerScheduler; - import java.util.Collection; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.ExecutorService; @@ -32,6 +45,11 @@ import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; +import org.apache.maven.plugin.surefire.log.api.ConsoleLogger; +import org.apache.maven.surefire.api.util.internal.DaemonThreadFactory; +import org.junit.runner.Description; +import org.junit.runners.model.RunnerScheduler; + /** * Used to execute tests annotated with net.jcip.annotations.NotThreadSafe. *
    @@ -40,55 +58,48 @@ * @see ParallelComputerBuilder * @since 2.18 */ -final class SingleThreadScheduler -{ +final class SingleThreadScheduler { private final ConsoleLogger logger; private final ExecutorService pool = newPool(); private final Scheduler master; - private static ExecutorService newPool() - { - ThreadFactory tf = DaemonThreadFactory.newDaemonThreadFactory( "maven-surefire-plugin@NotThreadSafe" ); - return new ThreadPoolExecutor( 1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue(), tf ); + private static ExecutorService newPool() { + ThreadFactory tf = DaemonThreadFactory.newDaemonThreadFactory("maven-surefire-plugin@NotThreadSafe"); + return new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue(), tf); } - SingleThreadScheduler( ConsoleLogger logger ) - { + SingleThreadScheduler(ConsoleLogger logger) { this.logger = logger; - SchedulingStrategy strategy = SchedulingStrategies.createParallelSharedStrategy( logger, pool ); - master = new Scheduler( logger, null, strategy ); + SchedulingStrategy strategy = SchedulingStrategies.createParallelSharedStrategy(logger, pool); + master = new Scheduler(logger, null, strategy); } - RunnerScheduler newRunnerScheduler() - { - SchedulingStrategy strategy = SchedulingStrategies.createParallelSharedStrategy( logger, pool ); - return new Scheduler( logger, null, master, strategy ); + RunnerScheduler newRunnerScheduler() { + SchedulingStrategy strategy = SchedulingStrategies.createParallelSharedStrategy(logger, pool); + return new Scheduler(logger, null, master, strategy); } /** * @see Scheduler#describeStopped(boolean) */ - ShutdownResult describeStopped( boolean shutdownNow ) - { - ShutdownResult shutdownResult = master.describeStopped( shutdownNow ); - return new ShutdownResult( copyExisting( shutdownResult.getTriggeredTests() ), - copyExisting( shutdownResult.getIncompleteTests() ) ); + ShutdownResult describeStopped(boolean shutdownNow) { + ShutdownResult shutdownResult = master.describeStopped(shutdownNow); + return new ShutdownResult( + copyExisting(shutdownResult.getTriggeredTests()), copyExisting(shutdownResult.getIncompleteTests())); } /** * @see Scheduler#shutdownThreadPoolsAwaitingKilled() */ - boolean shutdownThreadPoolsAwaitingKilled() - { + boolean shutdownThreadPoolsAwaitingKilled() { return master.shutdownThreadPoolsAwaitingKilled(); } - private Collection copyExisting( Collection descriptions ) - { - Collection activeChildren = new ConcurrentLinkedQueue<>( descriptions ); - ParallelComputerUtil.removeUnusedDescriptions( activeChildren ); + private Collection copyExisting(Collection descriptions) { + Collection activeChildren = new ConcurrentLinkedQueue<>(descriptions); + ParallelComputerUtil.removeUnusedDescriptions(activeChildren); return activeChildren; } } diff --git a/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/pc/ThreadResourcesBalancer.java b/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/pc/ThreadResourcesBalancer.java index 837ee6118f..545beebb9e 100644 --- a/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/pc/ThreadResourcesBalancer.java +++ b/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/pc/ThreadResourcesBalancer.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.junitcore.pc; /* @@ -26,9 +44,7 @@ * @see Balancer * @since 2.16 */ -final class ThreadResourcesBalancer - implements Balancer -{ +final class ThreadResourcesBalancer implements Balancer { private final Semaphore balancer; private final int numPermits; @@ -40,9 +56,8 @@ final class ThreadResourcesBalancer * Must be >0 and < {@link Integer#MAX_VALUE}. * @see #ThreadResourcesBalancer(int, boolean) */ - ThreadResourcesBalancer( int numPermits ) - { - this( numPermits, false ); + ThreadResourcesBalancer(int numPermits) { + this(numPermits, false); } /** @@ -51,14 +66,11 @@ final class ThreadResourcesBalancer * @param fair {@code true} guarantees the waiting schedulers to wake up in order they acquired a permit * @throws IllegalArgumentException if numPermits is not positive number */ - ThreadResourcesBalancer( int numPermits, boolean fair ) - { - if ( numPermits <= 0 ) - { - throw new IllegalArgumentException( - String.format( "numPermits=%d should be positive number", numPermits ) ); + ThreadResourcesBalancer(int numPermits, boolean fair) { + if (numPermits <= 0) { + throw new IllegalArgumentException(String.format("numPermits=%d should be positive number", numPermits)); } - balancer = new Semaphore( numPermits, fair ); + balancer = new Semaphore(numPermits, fair); this.numPermits = numPermits; } @@ -69,15 +81,11 @@ final class ThreadResourcesBalancer * while waiting for a permit. */ @Override - public boolean acquirePermit() - { - try - { + public boolean acquirePermit() { + try { balancer.acquire(); return true; - } - catch ( InterruptedException e ) - { + } catch (InterruptedException e) { return false; } } @@ -86,14 +94,12 @@ public boolean acquirePermit() * Releases a permit, returning it to the balancer. */ @Override - public void releasePermit() - { + public void releasePermit() { balancer.release(); } @Override - public void releaseAllPermits() - { - balancer.release( numPermits ); + public void releaseAllPermits() { + balancer.release(numPermits); } } diff --git a/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/pc/Type.java b/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/pc/Type.java index 3f9685f9f6..4baef63b43 100644 --- a/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/pc/Type.java +++ b/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/pc/Type.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.junitcore.pc; /* @@ -23,9 +41,8 @@ * @author tibor17 (Tibor Digana) * @since 2.17 */ -enum Type -{ +enum Type { SUITES, CLASSES, METHODS -} \ No newline at end of file +} diff --git a/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/pc/WrappedRunners.java b/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/pc/WrappedRunners.java index 707cc35181..34410c8fba 100644 --- a/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/pc/WrappedRunners.java +++ b/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/pc/WrappedRunners.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.junitcore.pc; /* @@ -32,20 +50,17 @@ * @see ParallelComputerBuilder * @since 2.17 */ -final class WrappedRunners -{ +final class WrappedRunners { final ParentRunner wrappingSuite; final long embeddedChildrenCount; - WrappedRunners( ParentRunner wrappingSuite, long embeddedChildrenCount ) - { + WrappedRunners(ParentRunner wrappingSuite, long embeddedChildrenCount) { this.wrappingSuite = wrappingSuite; this.embeddedChildrenCount = embeddedChildrenCount; } - WrappedRunners() - { - this( null, 0 ); + WrappedRunners() { + this(null, 0); } } diff --git a/surefire-providers/surefire-junit47/src/test/java/org/apache/maven/surefire/junitcore/ConcurrentRunListenerTest.java b/surefire-providers/surefire-junit47/src/test/java/org/apache/maven/surefire/junitcore/ConcurrentRunListenerTest.java index 7605b55fa3..b366c4a398 100644 --- a/surefire-providers/surefire-junit47/src/test/java/org/apache/maven/surefire/junitcore/ConcurrentRunListenerTest.java +++ b/surefire-providers/surefire-junit47/src/test/java/org/apache/maven/surefire/junitcore/ConcurrentRunListenerTest.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.junitcore; /* @@ -39,275 +57,214 @@ /** * @author Kristian Rosenvold */ -public class ConcurrentRunListenerTest - extends TestCase -{ +public class ConcurrentRunListenerTest extends TestCase { // Tests are in order of increasing complexity - public void testNoErrorsCounting() - throws Exception - { - runClasses( 3, 0, 0, DummyAllOk.class ); + public void testNoErrorsCounting() throws Exception { + runClasses(3, 0, 0, DummyAllOk.class); } - public void testNoErrorsCounting2() - throws Exception - { - runClasses( 2, 0, 0, Dummy3.class ); + public void testNoErrorsCounting2() throws Exception { + runClasses(2, 0, 0, Dummy3.class); } - public void testOneIgnoreCounting() - throws Exception - { - runClasses( 3, 1, 0, DummyWithOneIgnore.class ); + public void testOneIgnoreCounting() throws Exception { + runClasses(3, 1, 0, DummyWithOneIgnore.class); } - public void testOneFailureCounting() - throws Exception - { - runClasses( 3, 0, 1, DummyWithFailure.class ); + public void testOneFailureCounting() throws Exception { + runClasses(3, 0, 1, DummyWithFailure.class); } - public void testWithErrorsCountingDemultiplexed() - throws Exception - { - runClasses( 6, 1, 1, DummyWithOneIgnore.class, DummyWithFailure.class ); + public void testWithErrorsCountingDemultiplexed() throws Exception { + runClasses(6, 1, 1, DummyWithOneIgnore.class, DummyWithFailure.class); } - public void testJunitResultCountingDemultiplexed() - throws Exception - { - runClasses( 8, 1, 1, DummyWithOneIgnore.class, DummyWithFailure.class, Dummy3.class ); + public void testJunitResultCountingDemultiplexed() throws Exception { + runClasses(8, 1, 1, DummyWithOneIgnore.class, DummyWithFailure.class, Dummy3.class); } - public void testJunitResultCountingJUnit3Demultiplexed() - throws Exception - { - runClasses( 3, 0, 0, Junit3Tc1.class, Junit3Tc2.class ); + public void testJunitResultCountingJUnit3Demultiplexed() throws Exception { + runClasses(3, 0, 0, Junit3Tc1.class, Junit3Tc2.class); } - public void testJunitResultCountingJUnit3OddTest() - throws Exception - { - runClasses( 2, 0, 0, Junit3OddTest1.class ); + public void testJunitResultCountingJUnit3OddTest() throws Exception { + runClasses(2, 0, 0, Junit3OddTest1.class); } - public void testJunit3WithNestedSuite() - throws TestSetFailedException - { - runClasses( 4, 0, 0, Junit3WithNestedSuite.class ); + public void testJunit3WithNestedSuite() throws TestSetFailedException { + runClasses(4, 0, 0, Junit3WithNestedSuite.class); } - public void testJunit3NestedSuite() - throws Exception - { - runClasses( 2, 0, 0, Junit3OddTest1.class ); + public void testJunit3NestedSuite() throws Exception { + runClasses(2, 0, 0, Junit3OddTest1.class); } - public void testSimpleOutput() - throws Exception - { + public void testSimpleOutput() throws Exception { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); - PrintStream collector = new PrintStream( byteArrayOutputStream ); + PrintStream collector = new PrintStream(byteArrayOutputStream); PrintStream orgOur = System.out; - System.setOut( collector ); + System.setOut(collector); - RunStatistics result = runClasses( Dummy3.class ); - assertReporter( result, 2, 0, 0, "msgs" ); + RunStatistics result = runClasses(Dummy3.class); + assertReporter(result, 2, 0, 0, "msgs"); - String foo = new String( byteArrayOutputStream.toByteArray() ); - assertNotNull( foo ); + String foo = new String(byteArrayOutputStream.toByteArray()); + assertNotNull(foo); - System.setOut( orgOur ); + System.setOut(orgOur); } - public void testOutputOrdering() - throws Exception - { + public void testOutputOrdering() throws Exception { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); - PrintStream collector = new PrintStream( byteArrayOutputStream ); + PrintStream collector = new PrintStream(byteArrayOutputStream); PrintStream orgOur = System.out; - System.setOut( collector ); + System.setOut(collector); - RunStatistics result = runClasses( DummyWithOneIgnore.class, DummyWithFailure.class, Dummy3.class ); - assertReporter( result, 8, 1, 1, "msgs" ); + RunStatistics result = runClasses(DummyWithOneIgnore.class, DummyWithFailure.class, Dummy3.class); + assertReporter(result, 8, 1, 1, "msgs"); - String foo = new String( byteArrayOutputStream.toByteArray() ); - assertNotNull( foo ); + String foo = new String(byteArrayOutputStream.toByteArray()); + assertNotNull(foo); - System.setOut( orgOur ); + System.setOut(orgOur); -// final List stringList = result.getEvents(); -// assertEquals( 23, stringList.size() ); + // final List stringList = result.getEvents(); + // assertEquals( 23, stringList.size() ); } - private void runClasses( int success, int ignored, int failure, Class... classes ) - throws TestSetFailedException - { + private void runClasses(int success, int ignored, int failure, Class... classes) throws TestSetFailedException { DefaultReporterFactory reporterFactory = createReporterFactory(); HashMap classMethodCounts = new HashMap<>(); - ConcurrentRunListener reporter = - new ClassesParallelRunListener( classMethodCounts, reporterFactory ); - JUnitCoreRunListener runListener = new JUnitCoreRunListener( reporter, classMethodCounts ); - RunStatistics result = runClasses( reporterFactory, runListener, classes ); - assertReporter( result, success, ignored, failure, "classes" ); + ConcurrentRunListener reporter = new ClassesParallelRunListener(classMethodCounts, reporterFactory); + JUnitCoreRunListener runListener = new JUnitCoreRunListener(reporter, classMethodCounts); + RunStatistics result = runClasses(reporterFactory, runListener, classes); + assertReporter(result, success, ignored, failure, "classes"); classMethodCounts.clear(); reporterFactory = createReporterFactory(); - reporter = new MethodsParallelRunListener( classMethodCounts, reporterFactory, true ); - runListener = new JUnitCoreRunListener( reporter, classMethodCounts ); - result = runClasses( reporterFactory, runListener, classes ); - assertReporter( result, success, ignored, failure, "methods" ); + reporter = new MethodsParallelRunListener(classMethodCounts, reporterFactory, true); + runListener = new JUnitCoreRunListener(reporter, classMethodCounts); + result = runClasses(reporterFactory, runListener, classes); + assertReporter(result, success, ignored, failure, "methods"); } - private RunStatistics runClasses( Class... classes ) - throws TestSetFailedException - { + private RunStatistics runClasses(Class... classes) throws TestSetFailedException { HashMap classMethodCounts = new HashMap<>(); final DefaultReporterFactory reporterManagerFactory = createReporterFactory(); org.junit.runner.notification.RunListener demultiplexingRunListener = - createRunListener( reporterManagerFactory, classMethodCounts ); + createRunListener(reporterManagerFactory, classMethodCounts); JUnitCore jUnitCore = new JUnitCore(); - jUnitCore.addListener( demultiplexingRunListener ); + jUnitCore.addListener(demultiplexingRunListener); Computer computer = new Computer(); - jUnitCore.run( computer, classes ); + jUnitCore.run(computer, classes); reporterManagerFactory.close(); return reporterManagerFactory.getGlobalRunStatistics(); } - private RunStatistics runClasses( DefaultReporterFactory reporterManagerFactory, - org.junit.runner.notification.RunListener demultiplexingRunListener, - Class... classes ) - throws TestSetFailedException - { + private RunStatistics runClasses( + DefaultReporterFactory reporterManagerFactory, + org.junit.runner.notification.RunListener demultiplexingRunListener, + Class... classes) + throws TestSetFailedException { JUnitCore jUnitCore = new JUnitCore(); - jUnitCore.addListener( demultiplexingRunListener ); + jUnitCore.addListener(demultiplexingRunListener); Computer computer = new Computer(); - jUnitCore.run( computer, classes ); + jUnitCore.run(computer, classes); return reporterManagerFactory.getGlobalRunStatistics(); } - private org.junit.runner.notification.RunListener createRunListener( ReporterFactory reporterFactory, - Map testSetMap ) - { - ConcurrentRunListener handler = new ClassesParallelRunListener( testSetMap, reporterFactory ); - return new JUnitCoreRunListener( handler, testSetMap ); + private org.junit.runner.notification.RunListener createRunListener( + ReporterFactory reporterFactory, Map testSetMap) { + ConcurrentRunListener handler = new ClassesParallelRunListener(testSetMap, reporterFactory); + return new JUnitCoreRunListener(handler, testSetMap); } /** * */ - public static class DummyWithOneIgnore - { + public static class DummyWithOneIgnore { @Test - public void testNotMuch() - { - } + public void testNotMuch() {} @Ignore @Test - public void testStub1() - { - } + public void testStub1() {} @Test - public void testStub2() - { - } + public void testStub2() {} } /** * */ - public static class DummyWithFailure - { + public static class DummyWithFailure { @Test - public void testBeforeFail() - { - } + public void testBeforeFail() {} @Test - public void testWillFail() - { - Assert.fail( "We will fail" ); + public void testWillFail() { + Assert.fail("We will fail"); } @Test - public void testAfterFail() - { - } + public void testAfterFail() {} } /** * */ - public static class DummyAllOk - { + public static class DummyAllOk { @Test - public void testNotMuchA() - { - } + public void testNotMuchA() {} @Test - public void testStub1A() - { - } + public void testStub1A() {} @Test - public void testStub2A() - { - } + public void testStub2A() {} } /** * */ - public static class Dummy3 - { + public static class Dummy3 { @Test - public void testNotMuchA() - { - System.out.println( "tNMA1" ); - System.err.println( "tNMA1err" ); + public void testNotMuchA() { + System.out.println("tNMA1"); + System.err.println("tNMA1err"); } @Test - public void testStub2A() - { - System.out.println( "tS2A" ); - System.err.println( "tS2AErr" ); + public void testStub2A() { + System.out.println("tS2A"); + System.err.println("tS2AErr"); } } /** * */ - public static class Junit3Tc1 - extends TestCase - { + public static class Junit3Tc1 extends TestCase { - public Junit3Tc1() - { - super( "testNotMuchJunit3TC1" ); + public Junit3Tc1() { + super("testNotMuchJunit3TC1"); } - public void testNotMuchJunit3TC1() - { - System.out.println( "Junit3TC1" ); + public void testNotMuchJunit3TC1() { + System.out.println("Junit3TC1"); } - - public static junit.framework.Test suite() - { + public static junit.framework.Test suite() { TestSuite suite = new TestSuite(); - suite.addTest( new Junit3Tc1() ); + suite.addTest(new Junit3Tc1()); return suite; } } @@ -315,29 +272,23 @@ public static junit.framework.Test suite() /** * */ - public static class Junit3Tc2 - extends TestCase - { - public Junit3Tc2( String testMethod ) - { - super( testMethod ); + public static class Junit3Tc2 extends TestCase { + public Junit3Tc2(String testMethod) { + super(testMethod); } - public void testNotMuchJunit3TC2() - { - System.out.println( "Junit3TC2" ); + public void testNotMuchJunit3TC2() { + System.out.println("Junit3TC2"); } - public void testStubJ3TC2A() - { - System.out.println( "testStubJ3TC2A" ); + public void testStubJ3TC2A() { + System.out.println("testStubJ3TC2A"); } - public static junit.framework.Test suite() - { + public static junit.framework.Test suite() { TestSuite suite = new TestSuite(); - suite.addTest( new Junit3Tc2( "testNotMuchJunit3TC2" ) ); - suite.addTest( new Junit3Tc2( "testStubJ3TC2A" ) ); + suite.addTest(new Junit3Tc2("testNotMuchJunit3TC2")); + suite.addTest(new Junit3Tc2("testStubJ3TC2A")); return suite; } } @@ -345,68 +296,53 @@ public static junit.framework.Test suite() /** * */ - public static class Junit3OddTest1 - extends TestCase - { - public static junit.framework.Test suite() - { + public static class Junit3OddTest1 extends TestCase { + public static junit.framework.Test suite() { TestSuite suite = new TestSuite(); - suite.addTest( new Junit3OddTest1( "testMe" ) ); - suite.addTest( new Junit3OddTest1( "testMe2" ) ); + suite.addTest(new Junit3OddTest1("testMe")); + suite.addTest(new Junit3OddTest1("testMe2")); return suite; } - public Junit3OddTest1( String name ) - { - super( name ); + public Junit3OddTest1(String name) { + super(name); } - public void testMe() - { - assertTrue( true ); + public void testMe() { + assertTrue(true); } } /** * */ - public static class Junit3WithNestedSuite - extends TestCase - { - public static junit.framework.Test suite() - { + public static class Junit3WithNestedSuite extends TestCase { + public static junit.framework.Test suite() { TestSuite suite = new TestSuite(); - suite.addTest( new Junit3WithNestedSuite( "testMe" ) ); - suite.addTest( new Junit3WithNestedSuite( "testMe2" ) ); - suite.addTestSuite( Junit3Tc2.class ); + suite.addTest(new Junit3WithNestedSuite("testMe")); + suite.addTest(new Junit3WithNestedSuite("testMe2")); + suite.addTestSuite(Junit3Tc2.class); return suite; } - public Junit3WithNestedSuite( String name ) - { - super( name ); + public Junit3WithNestedSuite(String name) { + super(name); } - public void testMe2() - { - assertTrue( true ); + public void testMe2() { + assertTrue(true); } } - - private DefaultReporterFactory createReporterFactory() - { + private DefaultReporterFactory createReporterFactory() { return JUnitCoreTester.defaultNoXml(); } - - private void assertReporter( RunStatistics result, int success, int ignored, int failure, String message ) - { - assertEquals( message, success, result.getCompletedCount() ); - assertEquals( message, ignored, result.getSkipped() ); + private void assertReporter(RunStatistics result, int success, int ignored, int failure, String message) { + assertEquals(message, success, result.getCompletedCount()); + assertEquals(message, ignored, result.getSkipped()); } - } diff --git a/surefire-providers/surefire-junit47/src/test/java/org/apache/maven/surefire/junitcore/ConfigurableParallelComputerTest.java b/surefire-providers/surefire-junit47/src/test/java/org/apache/maven/surefire/junitcore/ConfigurableParallelComputerTest.java index 6942010100..8fa977838c 100644 --- a/surefire-providers/surefire-junit47/src/test/java/org/apache/maven/surefire/junitcore/ConfigurableParallelComputerTest.java +++ b/surefire-providers/surefire-junit47/src/test/java/org/apache/maven/surefire/junitcore/ConfigurableParallelComputerTest.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.junitcore; /* @@ -35,208 +53,171 @@ * * @author Kristian Rosenvold */ -public class ConfigurableParallelComputerTest - extends TestCase -{ +public class ConfigurableParallelComputerTest extends TestCase { private static final int NUMTESTS = 1000; // I'm sorry about all the sout's in this test; but if you deadlock when building you will appreciate it. @Test - public void testAnythingYouWantToPlayWith() - throws Exception - { + public void testAnythingYouWantToPlayWith() throws Exception { Result result = new Result(); - Class[] realClasses = new Class[]{ Dummy.class, Dummy2.class }; + Class[] realClasses = new Class[] {Dummy.class, Dummy2.class}; - DiagnosticRunListener diagnosticRunListener = new DiagnosticRunListener( false, result.createListener() ); - JUnitCore jUnitCore = getJunitCore( diagnosticRunListener ); - ConfigurableParallelComputer computer = new ConfigurableParallelComputer( true, false ); - jUnitCore.run( computer, realClasses ); + DiagnosticRunListener diagnosticRunListener = new DiagnosticRunListener(false, result.createListener()); + JUnitCore jUnitCore = getJunitCore(diagnosticRunListener); + ConfigurableParallelComputer computer = new ConfigurableParallelComputer(true, false); + jUnitCore.run(computer, realClasses); computer.close(); - assertEquals( "All tests should succeed, right ?", 5, result.getRunCount() ); + assertEquals("All tests should succeed, right ?", 5, result.getRunCount()); } @Test - public void testOneMethod() - throws ExecutionException - { + public void testOneMethod() throws ExecutionException { JUnitCore jUnitCore = new JUnitCore(); - ConfigurableParallelComputer computer = new ConfigurableParallelComputer( false, true ); - jUnitCore.run( computer, new Class[]{ Dummy.class, Dummy.class, Dummy.class } ); + ConfigurableParallelComputer computer = new ConfigurableParallelComputer(false, true); + jUnitCore.run(computer, new Class[] {Dummy.class, Dummy.class, Dummy.class}); computer.close(); } @Test - public void testSerial() - throws Exception - { + public void testSerial() throws Exception { Result result = new Result(); Class[] realClasses = getClassList(); - JUnitCore jUnitCore = getJunitCore( result ); + JUnitCore jUnitCore = getJunitCore(result); Computer computer = new Computer(); - timedRun( NUMTESTS, result, realClasses, jUnitCore, computer ); + timedRun(NUMTESTS, result, realClasses, jUnitCore, computer); } - @Test - public void testFullTestRunPC() - throws Exception - { + public void testFullTestRunPC() throws Exception { Result result = new Result(); Class[] realClasses = getClassList(); - JUnitCore jUnitCore = getJunitCore( result ); - Computer computer = new ConfigurableParallelComputer( true, true ); - timedRun( NUMTESTS, result, realClasses, jUnitCore, computer ); + JUnitCore jUnitCore = getJunitCore(result); + Computer computer = new ConfigurableParallelComputer(true, true); + timedRun(NUMTESTS, result, realClasses, jUnitCore, computer); } @Test - public void testWithFailingAssertionCPC() - throws Exception - { - runWithFailingAssertion( new ConfigurableParallelComputer( false, true, 6, true ) ); - runWithFailingAssertion( new ConfigurableParallelComputer( true, false, 12, false ) ); - runWithFailingAssertion( new ConfigurableParallelComputer( true, true, 2, false ) ); + public void testWithFailingAssertionCPC() throws Exception { + runWithFailingAssertion(new ConfigurableParallelComputer(false, true, 6, true)); + runWithFailingAssertion(new ConfigurableParallelComputer(true, false, 12, false)); + runWithFailingAssertion(new ConfigurableParallelComputer(true, true, 2, false)); } @Test - public void testWithSlowTestJustAfew() - throws Exception - { + public void testWithSlowTestJustAfew() throws Exception { Result result = new Result(); - final Computer computer = new ConfigurableParallelComputer( false, true, 3, false ); - Class[] realClasses = getClassList( SlowTest.class, 5 ); // 300 ms in methods, 600 in classes + final Computer computer = new ConfigurableParallelComputer(false, true, 3, false); + Class[] realClasses = getClassList(SlowTest.class, 5); // 300 ms in methods, 600 in classes - JUnitCore jUnitCore = getJunitCore( result ); - runIt( realClasses, jUnitCore, computer ); + JUnitCore jUnitCore = getJunitCore(result); + runIt(realClasses, jUnitCore, computer); } - - private void runWithFailingAssertion( Computer computer ) - throws ExecutionException - { + private void runWithFailingAssertion(Computer computer) throws ExecutionException { Result result = new Result(); - Class[] realClasses = getClassList( FailingAssertions.class ); - JUnitCore jUnitCore = getJunitCore( result ); - runIt( realClasses, jUnitCore, computer ); - assertEquals( "No tests should fail, right ?", NUMTESTS, result.getFailures().size() ); - assertEquals( "All tests should succeed, right ?", 0, result.getIgnoreCount() ); - assertEquals( "All tests should succeed, right ?", NUMTESTS * 3, result.getRunCount() ); + Class[] realClasses = getClassList(FailingAssertions.class); + JUnitCore jUnitCore = getJunitCore(result); + runIt(realClasses, jUnitCore, computer); + assertEquals( + "No tests should fail, right ?", NUMTESTS, result.getFailures().size()); + assertEquals("All tests should succeed, right ?", 0, result.getIgnoreCount()); + assertEquals("All tests should succeed, right ?", NUMTESTS * 3, result.getRunCount()); } @Test - public void testWithFailure() - throws Exception - { - Computer computer = new ConfigurableParallelComputer( false, true, 4, true ); + public void testWithFailure() throws Exception { + Computer computer = new ConfigurableParallelComputer(false, true, 4, true); Result result = new Result(); - Class[] realClasses = getClassList( Failure.class ); - JUnitCore jUnitCore = getJunitCore( result ); - runIt( realClasses, jUnitCore, computer ); - assertEquals( "No tests should fail, right ?", NUMTESTS, result.getFailures().size() ); - assertEquals( "All tests should succeed, right ?", 0, result.getIgnoreCount() ); - assertEquals( "All tests should succeed, right ?", NUMTESTS * 3, result.getRunCount() ); + Class[] realClasses = getClassList(Failure.class); + JUnitCore jUnitCore = getJunitCore(result); + runIt(realClasses, jUnitCore, computer); + assertEquals( + "No tests should fail, right ?", NUMTESTS, result.getFailures().size()); + assertEquals("All tests should succeed, right ?", 0, result.getIgnoreCount()); + assertEquals("All tests should succeed, right ?", NUMTESTS * 3, result.getRunCount()); } @Test - public void testFixedThreadPool() - throws Exception - { + public void testFixedThreadPool() throws Exception { Result result = new Result(); Class[] realClasses = getClassList(); - JUnitCore jUnitCore = getJunitCore( result ); - ConfigurableParallelComputer computer = new ConfigurableParallelComputer( false, true, 2, false ); - timedRun( NUMTESTS, result, realClasses, jUnitCore, computer ); + JUnitCore jUnitCore = getJunitCore(result); + ConfigurableParallelComputer computer = new ConfigurableParallelComputer(false, true, 2, false); + timedRun(NUMTESTS, result, realClasses, jUnitCore, computer); } @Test - public void testClassesUnlimited() - throws Exception - { + public void testClassesUnlimited() throws Exception { Result result = new Result(); Class[] realClasses = getClassList(); - JUnitCore jUnitCore = getJunitCore( result ); - ConfigurableParallelComputer computer = new ConfigurableParallelComputer( true, false ); - timedRun( NUMTESTS, result, realClasses, jUnitCore, computer ); + JUnitCore jUnitCore = getJunitCore(result); + ConfigurableParallelComputer computer = new ConfigurableParallelComputer(true, false); + timedRun(NUMTESTS, result, realClasses, jUnitCore, computer); } @Test - public void testBothUnlimited() - throws Exception - { + public void testBothUnlimited() throws Exception { Result result = new Result(); Class[] realClasses = getClassList(); - DiagnosticRunListener diagnosticRunListener = new DiagnosticRunListener( false, result.createListener() ); - JUnitCore jUnitCore = getJunitCore( diagnosticRunListener ); - ConfigurableParallelComputer computer = new ConfigurableParallelComputer( true, true ); - timedRun( NUMTESTS, result, realClasses, jUnitCore, computer ); + DiagnosticRunListener diagnosticRunListener = new DiagnosticRunListener(false, result.createListener()); + JUnitCore jUnitCore = getJunitCore(diagnosticRunListener); + ConfigurableParallelComputer computer = new ConfigurableParallelComputer(true, true); + timedRun(NUMTESTS, result, realClasses, jUnitCore, computer); } - private JUnitCore getJunitCore( Result result ) - { + private JUnitCore getJunitCore(Result result) { RunListener listener = result.createListener(); JUnitCore jUnitCore = new JUnitCore(); - jUnitCore.addListener( listener ); + jUnitCore.addListener(listener); return jUnitCore; } - private JUnitCore getJunitCore( RunListener listener ) - { + private JUnitCore getJunitCore(RunListener listener) { JUnitCore jUnitCore = new JUnitCore(); - jUnitCore.addListener( listener ); + jUnitCore.addListener(listener); return jUnitCore; } - private long runIt( Class[] realClasses, JUnitCore jUnitCore, Computer computer ) - throws ExecutionException - { + private long runIt(Class[] realClasses, JUnitCore jUnitCore, Computer computer) throws ExecutionException { long start = System.currentTimeMillis(); - jUnitCore.run( computer, realClasses ); - if ( computer instanceof ConfigurableParallelComputer ) - { - ( (ConfigurableParallelComputer) computer ).close(); + jUnitCore.run(computer, realClasses); + if (computer instanceof ConfigurableParallelComputer) { + ((ConfigurableParallelComputer) computer).close(); } return System.currentTimeMillis() - start; } - private long timedRun( int numTests, Result result, Class[] realClasses, JUnitCore jUnitCore, Computer computer ) - throws ExecutionException - { - long time = runIt( realClasses, jUnitCore, computer ); - assertEquals( "No tests should fail, right ?", 0, result.getFailures().size() ); - assertEquals( "All tests should succeed, right ?", 0, result.getIgnoreCount() ); - assertEquals( "All tests should succeed, right ?", numTests * 3, result.getRunCount() ); + private long timedRun(int numTests, Result result, Class[] realClasses, JUnitCore jUnitCore, Computer computer) + throws ExecutionException { + long time = runIt(realClasses, jUnitCore, computer); + assertEquals("No tests should fail, right ?", 0, result.getFailures().size()); + assertEquals("All tests should succeed, right ?", 0, result.getIgnoreCount()); + assertEquals("All tests should succeed, right ?", numTests * 3, result.getRunCount()); return time; } - private Class[] getClassList() - { - return getClassList( Dummy.class, NUMTESTS ); + private Class[] getClassList() { + return getClassList(Dummy.class, NUMTESTS); } - private Class[] getClassList( Class testClass ) - { - return getClassList( testClass, NUMTESTS ); + private Class[] getClassList(Class testClass) { + return getClassList(testClass, NUMTESTS); } - private Class[] getClassList( Class testClass, int numItems ) - { + private Class[] getClassList(Class testClass, int numItems) { List> realClasses = new ArrayList<>(); - for ( int i = 0; i < numItems; i++ ) - { - realClasses.add( testClass ); + for (int i = 0; i < numItems; i++) { + realClasses.add(testClass); } - return realClasses.toArray( new Class[realClasses.size()] ); + return realClasses.toArray(new Class[realClasses.size()]); } - static void sleepReallyEvenOnWindows( long ms ) - throws InterruptedException - { + static void sleepReallyEvenOnWindows(long ms) throws InterruptedException { long endAt = System.currentTimeMillis() + ms; - Thread.sleep( ms ); - while ( endAt > System.currentTimeMillis() ) - { - Thread.sleep( ms / 10 ); + Thread.sleep(ms); + while (endAt > System.currentTimeMillis()) { + Thread.sleep(ms / 10); Thread.yield(); } } @@ -244,22 +225,17 @@ static void sleepReallyEvenOnWindows( long ms ) /** * */ - public static class Dummy - { + public static class Dummy { @Test - public void testNotMuch() - { - } + public void testNotMuch() {} @Test - public void testStub1() - { + public void testStub1() { // Add your code here } @Test - public void testStub2() - { + public void testStub2() { // Add your code here } } @@ -267,17 +243,12 @@ public void testStub2() /** * */ - public static class Dummy2 - { + public static class Dummy2 { @Test - public void testNotMuch() - { - - } + public void testNotMuch() {} @Test - public void testDummy2() - { + public void testDummy2() { // Add your code here } } @@ -285,73 +256,54 @@ public void testDummy2() /** * */ - public static class SlowTest - { + public static class SlowTest { final int scaling = 100; @Test - public void testNotMuch() - throws InterruptedException - { - sleepReallyEvenOnWindows( scaling ); + public void testNotMuch() throws InterruptedException { + sleepReallyEvenOnWindows(scaling); } @Test - public void testNotMuch2() - throws InterruptedException - { - sleepReallyEvenOnWindows( 3 * scaling ); + public void testNotMuch2() throws InterruptedException { + sleepReallyEvenOnWindows(3 * scaling); } @Test - public void testNotMuch3() - throws InterruptedException - { - sleepReallyEvenOnWindows( 2 * scaling ); + public void testNotMuch3() throws InterruptedException { + sleepReallyEvenOnWindows(2 * scaling); } } /** * */ - public static class FailingAssertions - { + public static class FailingAssertions { @Test - public void testNotMuch() - { - } + public void testNotMuch() {} @Test - public void testNotMuch2() - { - } + public void testNotMuch2() {} @Test - public void testWithFail() - { - fail( "We excpect this" ); + public void testWithFail() { + fail("We excpect this"); } } /** * */ - public static class Failure - { + public static class Failure { @Test - public void testNotMuch() - { - } + public void testNotMuch() {} @Test - public void testNotMuch2() - { - } + public void testNotMuch2() {} @Test - public void testWithException() - { - throw new RuntimeException( "We expect this" ); + public void testWithException() { + throw new RuntimeException("We expect this"); } } -} \ No newline at end of file +} diff --git a/surefire-providers/surefire-junit47/src/test/java/org/apache/maven/surefire/junitcore/DiagnosticRunListener.java b/surefire-providers/surefire-junit47/src/test/java/org/apache/maven/surefire/junitcore/DiagnosticRunListener.java index dbc082e8fe..972ecf1337 100644 --- a/surefire-providers/surefire-junit47/src/test/java/org/apache/maven/surefire/junitcore/DiagnosticRunListener.java +++ b/surefire-providers/surefire-junit47/src/test/java/org/apache/maven/surefire/junitcore/DiagnosticRunListener.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.junitcore; /* @@ -50,9 +68,7 @@ /** * @author Kristian Rosenvold, kristianAzeniorD0Tno */ -public class DiagnosticRunListener - extends RunListener -{ +public class DiagnosticRunListener extends RunListener { private final AtomicInteger numTestStarted = new AtomicInteger(); private final AtomicInteger numTestFailed = new AtomicInteger(); @@ -67,123 +83,94 @@ public class DiagnosticRunListener private final RunListener target; - - private void print( String event, Description description ) - { - if ( printToConsole ) - { - System.out.println( Thread.currentThread().toString() + ", event = " + event + ", " + description ); + private void print(String event, Description description) { + if (printToConsole) { + System.out.println(Thread.currentThread().toString() + ", event = " + event + ", " + description); } } - private void print( String event, Result description ) - { - if ( printToConsole ) - { - System.out.println( Thread.currentThread().toString() + ", event = " + event + ", " + description ); + private void print(String event, Result description) { + if (printToConsole) { + System.out.println(Thread.currentThread().toString() + ", event = " + event + ", " + description); } } - private void print( String event, Failure description ) - { - if ( printToConsole ) - { - System.out.println( Thread.currentThread().toString() + ", event = " + event + ", " + description ); + private void print(String event, Failure description) { + if (printToConsole) { + System.out.println(Thread.currentThread().toString() + ", event = " + event + ", " + description); } } - public DiagnosticRunListener( boolean printToConsole, RunListener target ) - { + public DiagnosticRunListener(boolean printToConsole, RunListener target) { this.printToConsole = printToConsole; this.target = target; } @Override - public void testRunStarted( Description description ) - throws Exception - { - print( "testRunStarted", description ); - if ( target != null ) - { - target.testRunStarted( description ); + public void testRunStarted(Description description) throws Exception { + print("testRunStarted", description); + if (target != null) { + target.testRunStarted(description); } } @Override - public void testRunFinished( Result result ) - throws Exception - { - print( "testRunFinished", result ); - if ( target != null ) - { - target.testRunFinished( result ); + public void testRunFinished(Result result) throws Exception { + print("testRunFinished", result); + if (target != null) { + target.testRunFinished(result); } } @Override - public void testStarted( Description description ) - throws Exception - { + public void testStarted(Description description) throws Exception { numTestStarted.incrementAndGet(); - print( "testStarted", description ); - if ( target != null ) - { - target.testStarted( description ); + print("testStarted", description); + if (target != null) { + target.testStarted(description); } } @Override - public void testFinished( Description description ) - throws Exception - { + public void testFinished(Description description) throws Exception { numTestFinished.incrementAndGet(); - print( "testFinished", description ); - if ( target != null ) - { - target.testFinished( description ); + print("testFinished", description); + if (target != null) { + target.testFinished(description); } } @Override - public void testFailure( Failure failure ) - throws Exception - { + public void testFailure(Failure failure) throws Exception { numTestFailed.incrementAndGet(); - print( "testFailure", failure ); - if ( target != null ) - { - target.testFailure( failure ); + print("testFailure", failure); + if (target != null) { + target.testFailure(failure); } } @Override - public void testAssumptionFailure( Failure failure ) - { + public void testAssumptionFailure(Failure failure) { numTestAssumptionsFailed.incrementAndGet(); - print( "testAssumptionFailure", failure ); - if ( target != null ) - { - target.testAssumptionFailure( failure ); + print("testAssumptionFailure", failure); + if (target != null) { + target.testAssumptionFailure(failure); } } @Override - public void testIgnored( Description description ) - throws Exception - { + public void testIgnored(Description description) throws Exception { numTestIgnored.incrementAndGet(); - print( "testIgnored", description ); - if ( target != null ) - { - target.testIgnored( description ); + print("testIgnored", description); + if (target != null) { + target.testIgnored(description); } } @Override - public String toString() - { + public String toString() { return "DiagnosticRunListener{" + "numTestIgnored=" + numTestIgnored + ", numTestStarted=" + numTestStarted - + ", numTestFailed=" + numTestFailed + ", numTestAssumptionsFailed=" + numTestAssumptionsFailed - + ", numTestFinished=" + numTestFinished + '}'; + + ", numTestFailed=" + numTestFailed + ", numTestAssumptionsFailed=" + numTestAssumptionsFailed + + ", numTestFinished=" + numTestFinished + '}'; } } diff --git a/surefire-providers/surefire-junit47/src/test/java/org/apache/maven/surefire/junitcore/JUnit47SuiteTest.java b/surefire-providers/surefire-junit47/src/test/java/org/apache/maven/surefire/junitcore/JUnit47SuiteTest.java index 02534eed7c..d1415ba6e9 100644 --- a/surefire-providers/surefire-junit47/src/test/java/org/apache/maven/surefire/junitcore/JUnit47SuiteTest.java +++ b/surefire-providers/surefire-junit47/src/test/java/org/apache/maven/surefire/junitcore/JUnit47SuiteTest.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.junitcore; /* @@ -34,25 +52,23 @@ * @author Tibor Digana (tibor17) * @since 2.16 */ -public class JUnit47SuiteTest extends TestCase -{ - public static Test suite() - { +public class JUnit47SuiteTest extends TestCase { + public static Test suite() { TestSuite suite = new TestSuite(); - suite.addTestSuite( ConcurrentRunListenerTest.class ); - suite.addTestSuite( ConfigurableParallelComputerTest.class ); - suite.addTestSuite( JUnitCoreRunListenerTest.class ); - suite.addTestSuite( MavenSurefireJUnit47RunnerTest.class ); - suite.addTestSuite( MavenSurefireJUnit48RunnerTest.class ); - suite.addTestSuite( TestMethodTest.class ); - suite.addTest( new JUnit4TestAdapter( Surefire746Test.class ) ); - suite.addTest( new JUnit4TestAdapter( Surefire813IncorrectResultTest.class ) ); - suite.addTest( new JUnit4TestAdapter( ParallelComputerUtilTest.class ) ); - suite.addTest( new JUnit4TestAdapter( ParallelComputerBuilderTest.class ) ); - suite.addTest( new JUnit4TestAdapter( SchedulingStrategiesTest.class ) ); - suite.addTest( new JUnit4TestAdapter( OptimizedParallelComputerTest.class ) ); - suite.addTest( new JUnit4TestAdapter( JUnit4Reflector481Test.class ) ); - suite.addTest( new JUnit4TestAdapter( JUnitCoreParametersTest.class ) ); + suite.addTestSuite(ConcurrentRunListenerTest.class); + suite.addTestSuite(ConfigurableParallelComputerTest.class); + suite.addTestSuite(JUnitCoreRunListenerTest.class); + suite.addTestSuite(MavenSurefireJUnit47RunnerTest.class); + suite.addTestSuite(MavenSurefireJUnit48RunnerTest.class); + suite.addTestSuite(TestMethodTest.class); + suite.addTest(new JUnit4TestAdapter(Surefire746Test.class)); + suite.addTest(new JUnit4TestAdapter(Surefire813IncorrectResultTest.class)); + suite.addTest(new JUnit4TestAdapter(ParallelComputerUtilTest.class)); + suite.addTest(new JUnit4TestAdapter(ParallelComputerBuilderTest.class)); + suite.addTest(new JUnit4TestAdapter(SchedulingStrategiesTest.class)); + suite.addTest(new JUnit4TestAdapter(OptimizedParallelComputerTest.class)); + suite.addTest(new JUnit4TestAdapter(JUnit4Reflector481Test.class)); + suite.addTest(new JUnit4TestAdapter(JUnitCoreParametersTest.class)); return suite; } } diff --git a/surefire-providers/surefire-junit47/src/test/java/org/apache/maven/surefire/junitcore/JUnit4Reflector481Test.java b/surefire-providers/surefire-junit47/src/test/java/org/apache/maven/surefire/junitcore/JUnit4Reflector481Test.java index 39b1662381..6bd5cab74a 100644 --- a/surefire-providers/surefire-junit47/src/test/java/org/apache/maven/surefire/junitcore/JUnit4Reflector481Test.java +++ b/surefire-providers/surefire-junit47/src/test/java/org/apache/maven/surefire/junitcore/JUnit4Reflector481Test.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.junitcore; /* @@ -22,9 +40,8 @@ import java.lang.annotation.Annotation; import java.lang.reflect.Method; -import org.apache.maven.surefire.common.junit4.JUnit4Reflector; import org.apache.maven.surefire.api.util.ReflectionUtils; - +import org.apache.maven.surefire.common.junit4.JUnit4Reflector; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.Description; @@ -39,52 +56,50 @@ * * @author Kristian Rosenvold */ -public class JUnit4Reflector481Test -{ +public class JUnit4Reflector481Test { private static final Class[] EMPTY_CLASS_ARRAY = new Class[0]; @Test - public void testGetAnnotatedIgnore() - { - final Method testSomething2 = ReflectionUtils.getMethod( IgnoreWithDescription.class, "testSomething2", - EMPTY_CLASS_ARRAY ); + public void testGetAnnotatedIgnore() { + final Method testSomething2 = + ReflectionUtils.getMethod(IgnoreWithDescription.class, "testSomething2", EMPTY_CLASS_ARRAY); final Annotation[] annotations = testSomething2.getAnnotations(); - Description desc = Description.createTestDescription( IgnoreWithDescription.class, "testSomething2", - annotations ); - Ignore annotatedIgnore = JUnit4Reflector.getAnnotatedIgnore( desc ); - assertNotNull( annotatedIgnore ); + Description desc = + Description.createTestDescription(IgnoreWithDescription.class, "testSomething2", annotations); + Ignore annotatedIgnore = JUnit4Reflector.getAnnotatedIgnore(desc); + assertNotNull(annotatedIgnore); assertEquals( "testSomething2" + "(org.apache.maven.surefire.junitcore.JUnit4Reflector481Test$IgnoreWithDescription)", - desc.getDisplayName() ); + desc.getDisplayName()); assertEquals( "testSomething2" + "(org.apache.maven.surefire.junitcore.JUnit4Reflector481Test$IgnoreWithDescription)", - desc.toString() ); - assertEquals( "org.apache.maven.surefire.junitcore.JUnit4Reflector481Test$IgnoreWithDescription", - desc.getClassName() ); - assertEquals( "testSomething2", desc.getMethodName() ); - assertEquals( 0, desc.getChildren().size() ); - assertEquals( 2, desc.getAnnotations().size() ); - assertSame( annotatedIgnore, desc.getAnnotation( Ignore.class ) ); - assertEquals( REASON, annotatedIgnore.value() ); + desc.toString()); + assertEquals( + "org.apache.maven.surefire.junitcore.JUnit4Reflector481Test$IgnoreWithDescription", + desc.getClassName()); + assertEquals("testSomething2", desc.getMethodName()); + assertEquals(0, desc.getChildren().size()); + assertEquals(2, desc.getAnnotations().size()); + assertSame(annotatedIgnore, desc.getAnnotation(Ignore.class)); + assertEquals(REASON, annotatedIgnore.value()); } @Test - public void testGetAnnotatedIgnoreWithoutClass() - { - final Method testSomething2 = ReflectionUtils.getMethod( IgnoreWithDescription.class, "testSomething2", - EMPTY_CLASS_ARRAY ); + public void testGetAnnotatedIgnoreWithoutClass() { + final Method testSomething2 = + ReflectionUtils.getMethod(IgnoreWithDescription.class, "testSomething2", EMPTY_CLASS_ARRAY); final Annotation[] annotations = testSomething2.getAnnotations(); - Description desc = Description.createSuiteDescription( "testSomething2", annotations ); - Ignore annotatedIgnore = JUnit4Reflector.getAnnotatedIgnore( desc ); - assertNotNull( annotatedIgnore ); - assertEquals( "testSomething2", desc.getDisplayName() ); - assertEquals( "testSomething2", desc.toString() ); - assertEquals( "testSomething2", desc.getClassName() ); - assertNull( desc.getMethodName() ); - assertEquals( 0, desc.getChildren().size() ); - assertEquals( 2, desc.getAnnotations().size() ); - assertSame( annotatedIgnore, desc.getAnnotation( Ignore.class ) ); - assertEquals( REASON, annotatedIgnore.value() ); + Description desc = Description.createSuiteDescription("testSomething2", annotations); + Ignore annotatedIgnore = JUnit4Reflector.getAnnotatedIgnore(desc); + assertNotNull(annotatedIgnore); + assertEquals("testSomething2", desc.getDisplayName()); + assertEquals("testSomething2", desc.toString()); + assertEquals("testSomething2", desc.getClassName()); + assertNull(desc.getMethodName()); + assertEquals(0, desc.getChildren().size()); + assertEquals(2, desc.getAnnotations().size()); + assertSame(annotatedIgnore, desc.getAnnotation(Ignore.class)); + assertEquals(REASON, annotatedIgnore.value()); } private static final String REASON = "Ignorance is bliss"; @@ -92,36 +107,31 @@ public void testGetAnnotatedIgnoreWithoutClass() /** * */ - public static class IgnoreWithDescription - { + public static class IgnoreWithDescription { @Test - @Ignore( REASON ) - public void testSomething2() - { - } + @Ignore(REASON) + public void testSomething2() {} } @Test - public void testCreatePureDescription() - { - Description description = JUnit4Reflector.createDescription( "exception" ); - assertEquals( "exception", description.getDisplayName() ); - assertEquals( "exception", description.toString() ); - assertEquals( 0, description.getChildren().size() ); + public void testCreatePureDescription() { + Description description = JUnit4Reflector.createDescription("exception"); + assertEquals("exception", description.getDisplayName()); + assertEquals("exception", description.toString()); + assertEquals(0, description.getChildren().size()); } @Test - public void testCreateDescription() - { - Ignore ignore = JUnit4Reflector.createIgnored( "error" ); - Description description = JUnit4Reflector.createDescription( "exception", ignore ); - assertEquals( "exception", description.getDisplayName() ); - assertEquals( "exception", description.toString() ); - assertEquals( "exception", description.getClassName() ); - assertEquals( 0, description.getChildren().size() ); - Ignore annotatedIgnore = JUnit4Reflector.getAnnotatedIgnore( description ); - assertNotNull( annotatedIgnore ); - assertEquals( "error", annotatedIgnore.value() ); + public void testCreateDescription() { + Ignore ignore = JUnit4Reflector.createIgnored("error"); + Description description = JUnit4Reflector.createDescription("exception", ignore); + assertEquals("exception", description.getDisplayName()); + assertEquals("exception", description.toString()); + assertEquals("exception", description.getClassName()); + assertEquals(0, description.getChildren().size()); + Ignore annotatedIgnore = JUnit4Reflector.getAnnotatedIgnore(description); + assertNotNull(annotatedIgnore); + assertEquals("error", annotatedIgnore.value()); } } diff --git a/surefire-providers/surefire-junit47/src/test/java/org/apache/maven/surefire/junitcore/JUnitCoreParametersTest.java b/surefire-providers/surefire-junit47/src/test/java/org/apache/maven/surefire/junitcore/JUnitCoreParametersTest.java index 0ca33b98f6..0149529d00 100644 --- a/surefire-providers/surefire-junit47/src/test/java/org/apache/maven/surefire/junitcore/JUnitCoreParametersTest.java +++ b/surefire-providers/surefire-junit47/src/test/java/org/apache/maven/surefire/junitcore/JUnitCoreParametersTest.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.junitcore; /* @@ -24,193 +42,167 @@ import org.junit.Test; +import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; -import static org.hamcrest.core.Is.is; /** * @author Kristian Rosenvold, kristian.rosenvold@gmail com */ -@SuppressWarnings( "checkstyle:magicnumber" ) -public class JUnitCoreParametersTest -{ +@SuppressWarnings("checkstyle:magicnumber") +public class JUnitCoreParametersTest { @Test - public void defaultParameters() - { - assertFalse( newTestSetDefault().isParallelismSelected() ); - assertTrue( newTestSetDefault().isPerCoreThreadCount() ); - assertThat( newTestSetDefault().getThreadCount(), is( 0 ) ); - assertThat( newTestSetDefault().getThreadCountMethods(), is( 0 ) ); - assertThat( newTestSetDefault().getThreadCountClasses(), is( 0 ) ); - assertThat( newTestSetDefault().getThreadCountSuites(), is( 0 ) ); - assertFalse( newTestSetDefault().isUseUnlimitedThreads() ); - assertThat( newTestSetDefault().getParallelTestsTimeoutInSeconds(), is( 0d ) ); - assertThat( newTestSetDefault().getParallelTestsTimeoutForcedInSeconds(), is( 0d ) ); - assertTrue( newTestSetDefault().isParallelOptimization() ); + public void defaultParameters() { + assertFalse(newTestSetDefault().isParallelismSelected()); + assertTrue(newTestSetDefault().isPerCoreThreadCount()); + assertThat(newTestSetDefault().getThreadCount(), is(0)); + assertThat(newTestSetDefault().getThreadCountMethods(), is(0)); + assertThat(newTestSetDefault().getThreadCountClasses(), is(0)); + assertThat(newTestSetDefault().getThreadCountSuites(), is(0)); + assertFalse(newTestSetDefault().isUseUnlimitedThreads()); + assertThat(newTestSetDefault().getParallelTestsTimeoutInSeconds(), is(0d)); + assertThat(newTestSetDefault().getParallelTestsTimeoutForcedInSeconds(), is(0d)); + assertTrue(newTestSetDefault().isParallelOptimization()); } @Test - public void optimizationParameter() - { - assertFalse( newTestSetOptimization( false ).isParallelOptimization() ); + public void optimizationParameter() { + assertFalse(newTestSetOptimization(false).isParallelOptimization()); } @Test - public void timeoutParameters() - { - JUnitCoreParameters parameters = newTestSetTimeouts( 5.5d, 11.1d ); - assertThat( parameters.getParallelTestsTimeoutInSeconds(), is( 5.5d ) ); - assertThat( parameters.getParallelTestsTimeoutForcedInSeconds(), is( 11.1d ) ); + public void timeoutParameters() { + JUnitCoreParameters parameters = newTestSetTimeouts(5.5d, 11.1d); + assertThat(parameters.getParallelTestsTimeoutInSeconds(), is(5.5d)); + assertThat(parameters.getParallelTestsTimeoutForcedInSeconds(), is(11.1d)); } @Test - public void isParallelMethod() - { - assertFalse( newTestSetClasses().isParallelMethods() ); - assertTrue( newTestSetMethods().isParallelMethods() ); - assertTrue( newTestSetBoth().isParallelMethods() ); + public void isParallelMethod() { + assertFalse(newTestSetClasses().isParallelMethods()); + assertTrue(newTestSetMethods().isParallelMethods()); + assertTrue(newTestSetBoth().isParallelMethods()); } @Test - public void isParallelClasses() - { - assertTrue( newTestSetClasses().isParallelClasses() ); - assertFalse( newTestSetMethods().isParallelClasses() ); - assertTrue( newTestSetBoth().isParallelClasses() ); + public void isParallelClasses() { + assertTrue(newTestSetClasses().isParallelClasses()); + assertFalse(newTestSetMethods().isParallelClasses()); + assertTrue(newTestSetBoth().isParallelClasses()); } @Test - public void isParallelBoth() - { - assertFalse( isParallelMethodsAndClasses( newTestSetClasses() ) ); - assertFalse( isParallelMethodsAndClasses( newTestSetMethods() ) ); - assertTrue( isParallelMethodsAndClasses( newTestSetBoth() ) ); + public void isParallelBoth() { + assertFalse(isParallelMethodsAndClasses(newTestSetClasses())); + assertFalse(isParallelMethodsAndClasses(newTestSetMethods())); + assertTrue(isParallelMethodsAndClasses(newTestSetBoth())); } @Test - public void isPerCoreThreadCount() - { - assertFalse( newTestSetClasses().isPerCoreThreadCount() ); - assertFalse( newTestSetMethods().isPerCoreThreadCount() ); - assertTrue( newTestSetBoth().isPerCoreThreadCount() ); + public void isPerCoreThreadCount() { + assertFalse(newTestSetClasses().isPerCoreThreadCount()); + assertFalse(newTestSetMethods().isPerCoreThreadCount()); + assertTrue(newTestSetBoth().isPerCoreThreadCount()); } @Test - public void getThreadCount() - { - assertFalse( newTestSetClasses().isPerCoreThreadCount() ); - assertFalse( newTestSetMethods().isPerCoreThreadCount() ); - assertTrue( newTestSetBoth().isPerCoreThreadCount() ); + public void getThreadCount() { + assertFalse(newTestSetClasses().isPerCoreThreadCount()); + assertFalse(newTestSetMethods().isPerCoreThreadCount()); + assertTrue(newTestSetBoth().isPerCoreThreadCount()); } @Test - public void isUseUnlimitedThreads() - { - assertFalse( newTestSetClasses().isUseUnlimitedThreads() ); - assertTrue( newTestSetMethods().isUseUnlimitedThreads() ); - assertFalse( newTestSetBoth().isUseUnlimitedThreads() ); + public void isUseUnlimitedThreads() { + assertFalse(newTestSetClasses().isUseUnlimitedThreads()); + assertTrue(newTestSetMethods().isUseUnlimitedThreads()); + assertFalse(newTestSetBoth().isUseUnlimitedThreads()); } @Test - public void isNoThreading() - { - assertFalse( newTestSetClasses().isNoThreading() ); - assertFalse( newTestSetMethods().isNoThreading() ); - assertFalse( newTestSetBoth().isNoThreading() ); + public void isNoThreading() { + assertFalse(newTestSetClasses().isNoThreading()); + assertFalse(newTestSetMethods().isNoThreading()); + assertFalse(newTestSetBoth().isNoThreading()); } @Test - public void isAnyParallelismSelected() - { - assertTrue( newTestSetClasses().isParallelismSelected() ); - assertTrue( newTestSetMethods().isParallelismSelected() ); - assertTrue( newTestSetBoth().isParallelismSelected() ); + public void isAnyParallelismSelected() { + assertTrue(newTestSetClasses().isParallelismSelected()); + assertTrue(newTestSetMethods().isParallelismSelected()); + assertTrue(newTestSetBoth().isParallelismSelected()); } - private Map newDefaultProperties() - { + private Map newDefaultProperties() { return new HashMap<>(); } - - private Map newPropertiesClasses() - { + private Map newPropertiesClasses() { Map props = new HashMap<>(); - props.put( JUnitCoreParameters.PARALLEL_KEY, "classes" ); - props.put( JUnitCoreParameters.PERCORETHREADCOUNT_KEY, "false" ); - props.put( JUnitCoreParameters.THREADCOUNT_KEY, "2" ); - props.put( JUnitCoreParameters.USEUNLIMITEDTHREADS_KEY, "false" ); + props.put(JUnitCoreParameters.PARALLEL_KEY, "classes"); + props.put(JUnitCoreParameters.PERCORETHREADCOUNT_KEY, "false"); + props.put(JUnitCoreParameters.THREADCOUNT_KEY, "2"); + props.put(JUnitCoreParameters.USEUNLIMITEDTHREADS_KEY, "false"); return props; } - private Map newPropertiesMethods() - { + private Map newPropertiesMethods() { Map props = new HashMap<>(); - props.put( JUnitCoreParameters.PARALLEL_KEY, "methods" ); - props.put( JUnitCoreParameters.PERCORETHREADCOUNT_KEY, "false" ); - props.put( JUnitCoreParameters.THREADCOUNT_KEY, "2" ); - props.put( JUnitCoreParameters.USEUNLIMITEDTHREADS_KEY, "true" ); + props.put(JUnitCoreParameters.PARALLEL_KEY, "methods"); + props.put(JUnitCoreParameters.PERCORETHREADCOUNT_KEY, "false"); + props.put(JUnitCoreParameters.THREADCOUNT_KEY, "2"); + props.put(JUnitCoreParameters.USEUNLIMITEDTHREADS_KEY, "true"); return props; } - private Map newPropertiesBoth() - { + private Map newPropertiesBoth() { Map props = new HashMap<>(); - props.put( JUnitCoreParameters.PARALLEL_KEY, "both" ); - props.put( JUnitCoreParameters.PERCORETHREADCOUNT_KEY, "true" ); - props.put( JUnitCoreParameters.THREADCOUNT_KEY, "7" ); - props.put( JUnitCoreParameters.USEUNLIMITEDTHREADS_KEY, "false" ); + props.put(JUnitCoreParameters.PARALLEL_KEY, "both"); + props.put(JUnitCoreParameters.PERCORETHREADCOUNT_KEY, "true"); + props.put(JUnitCoreParameters.THREADCOUNT_KEY, "7"); + props.put(JUnitCoreParameters.USEUNLIMITEDTHREADS_KEY, "false"); return props; } - private Map newPropertiesTimeouts( double timeout, double forcedTimeout ) - { + private Map newPropertiesTimeouts(double timeout, double forcedTimeout) { Map props = new HashMap<>(); - props.put( JUnitCoreParameters.PARALLEL_TIMEOUT_KEY, Double.toString( timeout ) ); - props.put( JUnitCoreParameters.PARALLEL_TIMEOUTFORCED_KEY, Double.toString( forcedTimeout ) ); + props.put(JUnitCoreParameters.PARALLEL_TIMEOUT_KEY, Double.toString(timeout)); + props.put(JUnitCoreParameters.PARALLEL_TIMEOUTFORCED_KEY, Double.toString(forcedTimeout)); return props; } - private Map newPropertiesOptimization( boolean optimize ) - { + private Map newPropertiesOptimization(boolean optimize) { Map props = new HashMap<>(); - props.put( JUnitCoreParameters.PARALLEL_OPTIMIZE_KEY, Boolean.toString( optimize ) ); + props.put(JUnitCoreParameters.PARALLEL_OPTIMIZE_KEY, Boolean.toString(optimize)); return props; } - private JUnitCoreParameters newTestSetDefault() - { - return new JUnitCoreParameters( newDefaultProperties() ); + private JUnitCoreParameters newTestSetDefault() { + return new JUnitCoreParameters(newDefaultProperties()); } - private JUnitCoreParameters newTestSetBoth() - { - return new JUnitCoreParameters( newPropertiesBoth() ); + private JUnitCoreParameters newTestSetBoth() { + return new JUnitCoreParameters(newPropertiesBoth()); } - private JUnitCoreParameters newTestSetClasses() - { - return new JUnitCoreParameters( newPropertiesClasses() ); + private JUnitCoreParameters newTestSetClasses() { + return new JUnitCoreParameters(newPropertiesClasses()); } - private JUnitCoreParameters newTestSetMethods() - { - return new JUnitCoreParameters( newPropertiesMethods() ); + private JUnitCoreParameters newTestSetMethods() { + return new JUnitCoreParameters(newPropertiesMethods()); } - private JUnitCoreParameters newTestSetOptimization( boolean optimize ) - { - return new JUnitCoreParameters( newPropertiesOptimization( optimize ) ); + private JUnitCoreParameters newTestSetOptimization(boolean optimize) { + return new JUnitCoreParameters(newPropertiesOptimization(optimize)); } - private JUnitCoreParameters newTestSetTimeouts( double timeout, double forcedTimeout ) - { - return new JUnitCoreParameters( newPropertiesTimeouts( timeout, forcedTimeout ) ); + private JUnitCoreParameters newTestSetTimeouts(double timeout, double forcedTimeout) { + return new JUnitCoreParameters(newPropertiesTimeouts(timeout, forcedTimeout)); } - private boolean isParallelMethodsAndClasses( JUnitCoreParameters jUnitCoreParameters ) - { + private boolean isParallelMethodsAndClasses(JUnitCoreParameters jUnitCoreParameters) { return jUnitCoreParameters.isParallelMethods() && jUnitCoreParameters.isParallelClasses(); } } diff --git a/surefire-providers/surefire-junit47/src/test/java/org/apache/maven/surefire/junitcore/JUnitCoreRunListenerTest.java b/surefire-providers/surefire-junit47/src/test/java/org/apache/maven/surefire/junitcore/JUnitCoreRunListenerTest.java index ec7196396f..55d04f4cd3 100644 --- a/surefire-providers/surefire-junit47/src/test/java/org/apache/maven/surefire/junitcore/JUnitCoreRunListenerTest.java +++ b/surefire-providers/surefire-junit47/src/test/java/org/apache/maven/surefire/junitcore/JUnitCoreRunListenerTest.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.junitcore; /* @@ -33,144 +51,126 @@ import org.junit.runner.notification.RunListener; import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.empty; +import static org.hamcrest.Matchers.hasSize; /** * @author Kristian Rosenvold */ -public class JUnitCoreRunListenerTest extends TestCase -{ - public void testTestRunStarted() - { - RunListener jUnit4TestSetReporter = new JUnitCoreRunListener( new MockReporter(), - new HashMap() ); +public class JUnitCoreRunListenerTest extends TestCase { + public void testTestRunStarted() { + RunListener jUnit4TestSetReporter = + new JUnitCoreRunListener(new MockReporter(), new HashMap()); JUnitCore core = new JUnitCore(); - core.addListener( jUnit4TestSetReporter ); - Result result = core.run( new Computer(), STest1.class, STest2.class ); - core.removeListener( jUnit4TestSetReporter ); - assertEquals( 2, result.getRunCount() ); + core.addListener(jUnit4TestSetReporter); + Result result = core.run(new Computer(), STest1.class, STest2.class); + core.removeListener(jUnit4TestSetReporter); + assertEquals(2, result.getRunCount()); } - public void testFailedAssumption() - { - RunListener jUnit4TestSetReporter = new JUnitCoreRunListener( new MockReporter(), - new HashMap() ); + public void testFailedAssumption() { + RunListener jUnit4TestSetReporter = + new JUnitCoreRunListener(new MockReporter(), new HashMap()); JUnitCore core = new JUnitCore(); - core.addListener( jUnit4TestSetReporter ); - Result result = core.run( new Computer(), TestWithAssumptionFailure.class ); - core.removeListener( jUnit4TestSetReporter ); - assertEquals( 1, result.getRunCount() ); + core.addListener(jUnit4TestSetReporter); + Result result = core.run(new Computer(), TestWithAssumptionFailure.class); + core.removeListener(jUnit4TestSetReporter); + assertEquals(1, result.getRunCount()); } - public void testStateForClassesWithNoChildren() throws Exception - { - Description testDescription = Description.createSuiteDescription( - "testMethod(cannot.be.loaded.by.junit.Test)" ); - Description st1 = Description.createSuiteDescription( STest1.class ); + public void testStateForClassesWithNoChildren() throws Exception { + Description testDescription = Description.createSuiteDescription("testMethod(cannot.be.loaded.by.junit.Test)"); + Description st1 = Description.createSuiteDescription(STest1.class); // st1.addChild( Description.createSuiteDescription( STest1.class ) ); - testDescription.addChild( st1 ); - Description st2 = Description.createSuiteDescription( STest2.class ); + testDescription.addChild(st1); + Description st2 = Description.createSuiteDescription(STest2.class); // st2.addChild( Description.createSuiteDescription( STest2.class ) ); - testDescription.addChild( st2 ); + testDescription.addChild(st2); Map classMethodCounts = new HashMap<>(); - JUnitCoreRunListener listener = new JUnitCoreRunListener( new MockReporter(), classMethodCounts ); - listener.testRunStarted( testDescription ); - assertEquals( 2, classMethodCounts.size() ); + JUnitCoreRunListener listener = new JUnitCoreRunListener(new MockReporter(), classMethodCounts); + listener.testRunStarted(testDescription); + assertEquals(2, classMethodCounts.size()); Iterator iterator = classMethodCounts.values().iterator(); - assertFalse( iterator.next().equals( iterator.next() ) ); + assertFalse(iterator.next().equals(iterator.next())); } - public void testTestClassNotLoadableFromJUnitClassLoader() throws Exception - { + public void testTestClassNotLoadableFromJUnitClassLoader() throws Exception { // can't use Description.createTestDescription() methods as these require a loaded Class - Description testDescription = Description.createSuiteDescription( - "testMethod(cannot.be.loaded.by.junit.Test)" ); - assertEquals( "testMethod", testDescription.getMethodName() ); - assertEquals( "cannot.be.loaded.by.junit.Test", testDescription.getClassName() ); + Description testDescription = Description.createSuiteDescription("testMethod(cannot.be.loaded.by.junit.Test)"); + assertEquals("testMethod", testDescription.getMethodName()); + assertEquals("cannot.be.loaded.by.junit.Test", testDescription.getClassName()); // assert that the test class is not visible by the JUnit classloader - assertNull( testDescription.getTestClass() ); - Description suiteDescription = Description.createSuiteDescription( "testSuite" ); - suiteDescription.addChild( testDescription ); + assertNull(testDescription.getTestClass()); + Description suiteDescription = Description.createSuiteDescription("testSuite"); + suiteDescription.addChild(testDescription); Map classMethodCounts = new HashMap<>(); - JUnitCoreRunListener listener = new JUnitCoreRunListener( new MockReporter(), classMethodCounts ); - listener.testRunStarted( suiteDescription ); - assertEquals( 1, classMethodCounts.size() ); - TestSet testSet = classMethodCounts.get( "cannot.be.loaded.by.junit.Test" ); - assertNotNull( testSet ); + JUnitCoreRunListener listener = new JUnitCoreRunListener(new MockReporter(), classMethodCounts); + listener.testRunStarted(suiteDescription); + assertEquals(1, classMethodCounts.size()); + TestSet testSet = classMethodCounts.get("cannot.be.loaded.by.junit.Test"); + assertNotNull(testSet); } - public void testNonEmptyTestRunStarted() throws Exception - { - Description aggregator = Description.createSuiteDescription( "null" ); - Description suite = Description.createSuiteDescription( "some.junit.Test" ); - suite.addChild( Description.createSuiteDescription( "testMethodA(some.junit.Test)" ) ); - suite.addChild( Description.createSuiteDescription( "testMethodB(some.junit.Test)" ) ); - suite.addChild( Description.createSuiteDescription( "testMethod(another.junit.Test)" ) ); - aggregator.addChild( suite ); + public void testNonEmptyTestRunStarted() throws Exception { + Description aggregator = Description.createSuiteDescription("null"); + Description suite = Description.createSuiteDescription("some.junit.Test"); + suite.addChild(Description.createSuiteDescription("testMethodA(some.junit.Test)")); + suite.addChild(Description.createSuiteDescription("testMethodB(some.junit.Test)")); + suite.addChild(Description.createSuiteDescription("testMethod(another.junit.Test)")); + aggregator.addChild(suite); Map classMethodCounts = new HashMap<>(); - JUnitCoreRunListener listener = new JUnitCoreRunListener( new MockReporter(), classMethodCounts ); - listener.testRunStarted( aggregator ); - assertThat( classMethodCounts.keySet(), hasSize( 2 ) ); - assertThat( classMethodCounts.keySet(), containsInAnyOrder( "some.junit.Test", "another.junit.Test" ) ); - TestSet testSet = classMethodCounts.get( "some.junit.Test" ); + JUnitCoreRunListener listener = new JUnitCoreRunListener(new MockReporter(), classMethodCounts); + listener.testRunStarted(aggregator); + assertThat(classMethodCounts.keySet(), hasSize(2)); + assertThat(classMethodCounts.keySet(), containsInAnyOrder("some.junit.Test", "another.junit.Test")); + TestSet testSet = classMethodCounts.get("some.junit.Test"); MockReporter reporter = new MockReporter(); - testSet.replay( reporter ); - assertTrue( reporter.containsNotification( MockReporter.SET_STARTED ) ); - assertTrue( reporter.containsNotification( MockReporter.SET_COMPLETED ) ); - listener.testRunFinished( null ); - assertThat( classMethodCounts.keySet(), empty() ); + testSet.replay(reporter); + assertTrue(reporter.containsNotification(MockReporter.SET_STARTED)); + assertTrue(reporter.containsNotification(MockReporter.SET_COMPLETED)); + listener.testRunFinished(null); + assertThat(classMethodCounts.keySet(), empty()); } - public void testEmptySuiteTestRunStarted() throws Exception - { - Description aggregator = Description.createSuiteDescription( "null" ); - Description suite = Description.createSuiteDescription( "some.junit.TestSuite" ); - aggregator.addChild( suite ); + public void testEmptySuiteTestRunStarted() throws Exception { + Description aggregator = Description.createSuiteDescription("null"); + Description suite = Description.createSuiteDescription("some.junit.TestSuite"); + aggregator.addChild(suite); Map classMethodCounts = new HashMap<>(); - JUnitCoreRunListener listener = new JUnitCoreRunListener( new MockReporter(), classMethodCounts ); - listener.testRunStarted( aggregator ); - assertThat( classMethodCounts.keySet(), hasSize( 1 ) ); - assertThat( classMethodCounts.keySet(), contains( "some.junit.TestSuite" ) ); - listener.testRunFinished( null ); - assertThat( classMethodCounts.keySet(), empty() ); + JUnitCoreRunListener listener = new JUnitCoreRunListener(new MockReporter(), classMethodCounts); + listener.testRunStarted(aggregator); + assertThat(classMethodCounts.keySet(), hasSize(1)); + assertThat(classMethodCounts.keySet(), contains("some.junit.TestSuite")); + listener.testRunFinished(null); + assertThat(classMethodCounts.keySet(), empty()); } /** * */ - public static class STest1 - { + public static class STest1 { @Test - public void testSomething() - { - } + public void testSomething() {} } /** * */ - public static class STest2 - { + public static class STest2 { @Test - public void testSomething2() - { - } + public void testSomething2() {} } /** * */ - public static class TestWithAssumptionFailure - { + public static class TestWithAssumptionFailure { @Test - public void testSomething2() - { - Assume.assumeTrue( false ); + public void testSomething2() { + Assume.assumeTrue(false); } } - } diff --git a/surefire-providers/surefire-junit47/src/test/java/org/apache/maven/surefire/junitcore/JUnitCoreTester.java b/surefire-providers/surefire-junit47/src/test/java/org/apache/maven/surefire/junitcore/JUnitCoreTester.java index 81536896f4..8884c966ae 100644 --- a/surefire-providers/surefire-junit47/src/test/java/org/apache/maven/surefire/junitcore/JUnitCoreTester.java +++ b/surefire-providers/surefire-junit47/src/test/java/org/apache/maven/surefire/junitcore/JUnitCoreTester.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.junitcore; /* @@ -19,6 +37,11 @@ * under the License. */ +import java.io.File; +import java.io.PrintStream; +import java.util.HashMap; +import java.util.concurrent.ExecutionException; + import org.apache.maven.plugin.surefire.StartupReportConfiguration; import org.apache.maven.plugin.surefire.extensions.SurefireConsoleOutputReporter; import org.apache.maven.plugin.surefire.extensions.SurefireStatelessReporter; @@ -31,59 +54,45 @@ import org.junit.runner.JUnitCore; import org.junit.runner.Result; -import java.io.File; -import java.io.PrintStream; -import java.util.HashMap; -import java.util.concurrent.ExecutionException; - -import static org.apache.maven.surefire.junitcore.ConcurrentRunListener.createInstance; import static org.apache.maven.surefire.api.report.ConsoleOutputCapture.startCapture; +import static org.apache.maven.surefire.junitcore.ConcurrentRunListener.createInstance; /** * @author Kristian Rosenvold */ -public class JUnitCoreTester -{ +public class JUnitCoreTester { private final Computer computer; - public JUnitCoreTester() - { - this( new Computer() ); + public JUnitCoreTester() { + this(new Computer()); } - public JUnitCoreTester( Computer computer ) - { + public JUnitCoreTester(Computer computer) { this.computer = computer; } - public Result run( boolean parallelClasses, Class... classes ) - throws TestSetFailedException, ExecutionException - { + public Result run(boolean parallelClasses, Class... classes) throws TestSetFailedException, ExecutionException { ReporterFactory reporterManagerFactory = defaultNoXml(); PrintStream out = System.out; PrintStream err = System.err; - try - { + try { HashMap classMethodCounts = new HashMap<>(); ConcurrentRunListener reporter = - createInstance( classMethodCounts, reporterManagerFactory, parallelClasses, false ); - JUnitCoreRunListener runListener = new JUnitCoreRunListener( reporter, classMethodCounts ); - startCapture( runListener ); + createInstance(classMethodCounts, reporterManagerFactory, parallelClasses, false); + JUnitCoreRunListener runListener = new JUnitCoreRunListener(reporter, classMethodCounts); + startCapture(runListener); JUnitCore junitCore = new JUnitCore(); - junitCore.addListener( runListener ); - final Result run = junitCore.run( computer, classes ); - junitCore.removeListener( runListener ); + junitCore.addListener(runListener); + final Result run = junitCore.run(computer, classes); + junitCore.removeListener(runListener); return run; - } - finally - { - System.setOut( out ); - System.setErr( err ); + } finally { + System.setOut(out); + System.setErr(err); reporterManagerFactory.close(); - if ( computer instanceof ConfigurableParallelComputer ) - { - ( (ConfigurableParallelComputer) computer ).close(); + if (computer instanceof ConfigurableParallelComputer) { + ((ConfigurableParallelComputer) computer).close(); } } } @@ -93,9 +102,8 @@ public Result run( boolean parallelClasses, Class... classes ) * * @return DefaultReporterFactory for testing purposes */ - public static DefaultReporterFactory defaultNoXml() - { - return new DefaultReporterFactory( defaultStartupReportConfiguration(), new NullConsoleLogger() ); + public static DefaultReporterFactory defaultNoXml() { + return new DefaultReporterFactory(defaultStartupReportConfiguration(), new NullConsoleLogger()); } /** @@ -103,12 +111,25 @@ public static DefaultReporterFactory defaultNoXml() * * @return StartupReportConfiguration fo testing purposes */ - private static StartupReportConfiguration defaultStartupReportConfiguration() - { - File target = new File( "./target" ); - File statisticsFile = new File( target, "TESTHASHxXML" ); - return new StartupReportConfiguration( true, true, "PLAIN", false, target, false, null, statisticsFile, - false, 0, null, null, false, new SurefireStatelessReporter(), new SurefireConsoleOutputReporter(), - new SurefireStatelessTestsetInfoReporter() ); + private static StartupReportConfiguration defaultStartupReportConfiguration() { + File target = new File("./target"); + File statisticsFile = new File(target, "TESTHASHxXML"); + return new StartupReportConfiguration( + true, + true, + "PLAIN", + false, + target, + false, + null, + statisticsFile, + false, + 0, + null, + null, + false, + new SurefireStatelessReporter(), + new SurefireConsoleOutputReporter(), + new SurefireStatelessTestsetInfoReporter()); } } diff --git a/surefire-providers/surefire-junit47/src/test/java/org/apache/maven/surefire/junitcore/MavenSurefireJUnit47RunnerTest.java b/surefire-providers/surefire-junit47/src/test/java/org/apache/maven/surefire/junitcore/MavenSurefireJUnit47RunnerTest.java index 14dab812d1..0f5d0d3f29 100644 --- a/surefire-providers/surefire-junit47/src/test/java/org/apache/maven/surefire/junitcore/MavenSurefireJUnit47RunnerTest.java +++ b/surefire-providers/surefire-junit47/src/test/java/org/apache/maven/surefire/junitcore/MavenSurefireJUnit47RunnerTest.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.junitcore; /* @@ -98,71 +116,64 @@ * @author Aslak Knutsen * @version $Revision: $ */ -public class MavenSurefireJUnit47RunnerTest - extends TestCase -{ +public class MavenSurefireJUnit47RunnerTest extends TestCase { /* - * Assumption: - * The ConcurrentReportingRunListener assumes a Test will be Started before it Fails or Finishes. - * - * Reality: - * JUnits ParentRunner is responsible for adding the BeforeClass/AfterClass statements to the - * statement execution chain. After BeforeClass is executed, a Statement that delegates to the - * abstract method: runChild(T child, RunNotifier notifier) is called. As the JavaDoc explains: - * "Subclasses are responsible for making sure that relevant test events are reported through notifier". - * When a @BeforeClass fail, the child that should handle the relevant test events(Started, Failed, Finished) - * is never executed. - * - * Result: - * When Test Failed event is received in ConcurrentReportingRunListener without a Started event received first, - * it causes a NullPointException because there is no ClassReporter setup for that class yet. When this Exception - * is thrown from the ConcurrentReportingRunListener, JUnit catches the exception and reports is as a Failed test. - * But to avoid a wild loop, it removes the failing Listener before calling Failed test again. Since the - * ConcurrentReportingRunListener now is removed from the chain it will never receive the RunFinished event - * and the recorded state will never be replayed on the ReportManager. - * - * The End result: ReporterManager falsely believe no Test were run. - * - */ - @SuppressWarnings( { "unchecked", "ThrowableResultOfMethodCallIgnored" } ) - public void testSurefireShouldBeAbleToReportRunStatusEvenWithFailingTests() - throws Exception - { - Result result = new JUnitCoreTester().run( false, FailingTestClassTestNot.class ); + * Assumption: + * The ConcurrentReportingRunListener assumes a Test will be Started before it Fails or Finishes. + * + * Reality: + * JUnits ParentRunner is responsible for adding the BeforeClass/AfterClass statements to the + * statement execution chain. After BeforeClass is executed, a Statement that delegates to the + * abstract method: runChild(T child, RunNotifier notifier) is called. As the JavaDoc explains: + * "Subclasses are responsible for making sure that relevant test events are reported through notifier". + * When a @BeforeClass fail, the child that should handle the relevant test events(Started, Failed, Finished) + * is never executed. + * + * Result: + * When Test Failed event is received in ConcurrentReportingRunListener without a Started event received first, + * it causes a NullPointException because there is no ClassReporter setup for that class yet. When this Exception + * is thrown from the ConcurrentReportingRunListener, JUnit catches the exception and reports is as a Failed test. + * But to avoid a wild loop, it removes the failing Listener before calling Failed test again. Since the + * ConcurrentReportingRunListener now is removed from the chain it will never receive the RunFinished event + * and the recorded state will never be replayed on the ReportManager. + * + * The End result: ReporterManager falsely believe no Test were run. + * + */ + @SuppressWarnings({"unchecked", "ThrowableResultOfMethodCallIgnored"}) + public void testSurefireShouldBeAbleToReportRunStatusEvenWithFailingTests() throws Exception { + Result result = new JUnitCoreTester().run(false, FailingTestClassTestNot.class); - Assert.assertEquals( "JUnit should report correctly number of test ran(Finished)", 0, result.getRunCount() ); + Assert.assertEquals("JUnit should report correctly number of test ran(Finished)", 0, result.getRunCount()); - for ( Failure failure : result.getFailures() ) - { - System.out.println( failure.getException().getMessage() ); + for (Failure failure : result.getFailures()) { + System.out.println(failure.getException().getMessage()); } - Assert.assertEquals( "There should only be one Exception reported, the one from the failing TestCase", 1, - result.getFailureCount() ); - - Assert.assertEquals( "The exception thrown by the failing TestCase", RuntimeException.class, - result.getFailures().get( 0 ).getException().getClass() ); + Assert.assertEquals( + "There should only be one Exception reported, the one from the failing TestCase", + 1, + result.getFailureCount()); + Assert.assertEquals( + "The exception thrown by the failing TestCase", + RuntimeException.class, + result.getFailures().get(0).getException().getClass()); } /** * Simple TestCase to force a Exception in @BeforeClass. */ - public static class FailingTestClassTestNot - { + public static class FailingTestClassTestNot { @BeforeClass - public static void failingBeforeClass() - throws Exception - { - throw new RuntimeException( "Opps, we failed in @BeforeClass" ); + public static void failingBeforeClass() throws Exception { + throw new RuntimeException("Opps, we failed in @BeforeClass"); } @Test - public void shouldNeverBeCalled() - throws Exception - { - Assert.assertTrue( true ); + public void shouldNeverBeCalled() throws Exception { + Assert.assertTrue(true); } } } diff --git a/surefire-providers/surefire-junit47/src/test/java/org/apache/maven/surefire/junitcore/MavenSurefireJUnit48RunnerTest.java b/surefire-providers/surefire-junit47/src/test/java/org/apache/maven/surefire/junitcore/MavenSurefireJUnit48RunnerTest.java index c9cc407bbe..19a9120353 100644 --- a/surefire-providers/surefire-junit47/src/test/java/org/apache/maven/surefire/junitcore/MavenSurefireJUnit48RunnerTest.java +++ b/surefire-providers/surefire-junit47/src/test/java/org/apache/maven/surefire/junitcore/MavenSurefireJUnit48RunnerTest.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.junitcore; /* @@ -98,71 +116,64 @@ * @author Aslak Knutsen * @version $Revision: $ */ -public class MavenSurefireJUnit48RunnerTest - extends TestCase -{ +public class MavenSurefireJUnit48RunnerTest extends TestCase { /* - * Assumption: - * The ConcurrentReportingRunListener assumes a Test will be Started before it Fails or Finishes. - * - * Reality: - * JUnits ParentRunner is responsible for adding the BeforeClass/AfterClass statements to the - * statement execution chain. After BeforeClass is executed, a Statement that delegates to the - * abstract method: runChild(T child, RunNotifier notifier) is called. As the JavaDoc explains: - * "Subclasses are responsible for making sure that relevant test events are reported through notifier". - * When a @BeforeClass fail, the child that should handle the relevant test events(Started, Failed, Finished) - * is never executed. - * - * Result: - * When Test Failed event is received in ConcurrentReportingRunListener without a Started event received first, - * it causes a NullPointException because there is no ClassReporter setup for that class yet. When this Exception - * is thrown from the ConcurrentReportingRunListener, JUnit catches the exception and reports is as a Failed test. - * But to avoid a wild loop, it removes the failing Listener before calling Failed test again. Since the - * ConcurrentReportingRunListener now is removed from the chain it will never receive the RunFinished event - * and the recorded state will never be replayed on the ReportManager. - * - * The End result: ReporterManager falsely believe no Test were run. - * - */ - @SuppressWarnings( { "unchecked", "ThrowableResultOfMethodCallIgnored" } ) - public void testSurefireShouldBeAbleToReportRunStatusEvenWithFailingTests() - throws Exception - { - Result result = new JUnitCoreTester().run( false, FailingTestClassTestNot.class ); + * Assumption: + * The ConcurrentReportingRunListener assumes a Test will be Started before it Fails or Finishes. + * + * Reality: + * JUnits ParentRunner is responsible for adding the BeforeClass/AfterClass statements to the + * statement execution chain. After BeforeClass is executed, a Statement that delegates to the + * abstract method: runChild(T child, RunNotifier notifier) is called. As the JavaDoc explains: + * "Subclasses are responsible for making sure that relevant test events are reported through notifier". + * When a @BeforeClass fail, the child that should handle the relevant test events(Started, Failed, Finished) + * is never executed. + * + * Result: + * When Test Failed event is received in ConcurrentReportingRunListener without a Started event received first, + * it causes a NullPointException because there is no ClassReporter setup for that class yet. When this Exception + * is thrown from the ConcurrentReportingRunListener, JUnit catches the exception and reports is as a Failed test. + * But to avoid a wild loop, it removes the failing Listener before calling Failed test again. Since the + * ConcurrentReportingRunListener now is removed from the chain it will never receive the RunFinished event + * and the recorded state will never be replayed on the ReportManager. + * + * The End result: ReporterManager falsely believe no Test were run. + * + */ + @SuppressWarnings({"unchecked", "ThrowableResultOfMethodCallIgnored"}) + public void testSurefireShouldBeAbleToReportRunStatusEvenWithFailingTests() throws Exception { + Result result = new JUnitCoreTester().run(false, FailingTestClassTestNot.class); - Assert.assertEquals( "JUnit should report correctly number of test ran(Finished)", 0, result.getRunCount() ); + Assert.assertEquals("JUnit should report correctly number of test ran(Finished)", 0, result.getRunCount()); - for ( Failure failure : result.getFailures() ) - { - System.out.println( failure.getException().getMessage() ); + for (Failure failure : result.getFailures()) { + System.out.println(failure.getException().getMessage()); } - Assert.assertEquals( "There should only be one Exception reported, the one from the failing TestCase", 1, - result.getFailureCount() ); - - Assert.assertEquals( "The exception thrown by the failing TestCase", RuntimeException.class, - result.getFailures().get( 0 ).getException().getClass() ); + Assert.assertEquals( + "There should only be one Exception reported, the one from the failing TestCase", + 1, + result.getFailureCount()); + Assert.assertEquals( + "The exception thrown by the failing TestCase", + RuntimeException.class, + result.getFailures().get(0).getException().getClass()); } /** * Simple TestCase to force a Exception in @BeforeClass. */ - public static class FailingTestClassTestNot - { + public static class FailingTestClassTestNot { @BeforeClass - public static void failingBeforeClass() - throws Exception - { - throw new RuntimeException( "Opps, we failed in @BeforeClass" ); + public static void failingBeforeClass() throws Exception { + throw new RuntimeException("Opps, we failed in @BeforeClass"); } @Test - public void shouldNeverBeCalled() - throws Exception - { - Assert.assertTrue( true ); + public void shouldNeverBeCalled() throws Exception { + Assert.assertTrue(true); } } } diff --git a/surefire-providers/surefire-junit47/src/test/java/org/apache/maven/surefire/junitcore/MockReporter.java b/surefire-providers/surefire-junit47/src/test/java/org/apache/maven/surefire/junitcore/MockReporter.java index 1fa59e07f3..bf0ecbe80e 100644 --- a/surefire-providers/surefire-junit47/src/test/java/org/apache/maven/surefire/junitcore/MockReporter.java +++ b/surefire-providers/surefire-junit47/src/test/java/org/apache/maven/surefire/junitcore/MockReporter.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.junitcore; /* @@ -34,9 +52,7 @@ /** * Internal tests use only. */ -final class MockReporter - extends ConcurrentRunListener -{ +final class MockReporter extends ConcurrentRunListener { private final List events = new ArrayList<>(); static final String SET_STARTED = "SET_STARTED"; @@ -57,149 +73,106 @@ final class MockReporter private final AtomicInteger testError = new AtomicInteger(); - MockReporter() - { - super( mock( ReporterFactory.class ), false, emptyMap() ); + MockReporter() { + super(mock(ReporterFactory.class), false, emptyMap()); } @Override - public void testSetStarting( TestSetReportEntry report ) - { - events.add( SET_STARTED ); + public void testSetStarting(TestSetReportEntry report) { + events.add(SET_STARTED); } @Override - public void testSetCompleted( TestSetReportEntry report ) - { - events.add( SET_COMPLETED ); + public void testSetCompleted(TestSetReportEntry report) { + events.add(SET_COMPLETED); } @Override - public void testStarting( ReportEntry report ) - { - events.add( TEST_STARTED ); + public void testStarting(ReportEntry report) { + events.add(TEST_STARTED); } @Override - public void testSucceeded( ReportEntry report ) - { - events.add( TEST_COMPLETED ); + public void testSucceeded(ReportEntry report) { + events.add(TEST_COMPLETED); testSucceeded.incrementAndGet(); } @Override - protected void checkIfTestSetCanBeReported( TestSet testSetForTest ) - { - - } + protected void checkIfTestSetCanBeReported(TestSet testSetForTest) {} @Override - public void testSkipped( ReportEntry report ) - { - events.add( TEST_SKIPPED ); + public void testSkipped(ReportEntry report) { + events.add(TEST_SKIPPED); testIgnored.incrementAndGet(); } @Override - public void testExecutionSkippedByUser() - { - } + public void testExecutionSkippedByUser() {} - public int getTestSucceeded() - { + public int getTestSucceeded() { return testSucceeded.get(); } - public int getTestFailed() - { + public int getTestFailed() { return testFailed.get(); } @Override - public void testError( ReportEntry report ) - { + public void testError(ReportEntry report) { testError.incrementAndGet(); } @Override - public void testFailed( ReportEntry report ) - { + public void testFailed(ReportEntry report) { testFailed.incrementAndGet(); } @Override - public void testAssumptionFailure( ReportEntry report ) - { - } + public void testAssumptionFailure(ReportEntry report) {} - public boolean containsNotification( String event ) - { - return events.contains( event ); + public boolean containsNotification(String event) { + return events.contains(event); } @Override - public void writeTestOutput( TestOutputReportEntry reportEntry ) - { - - } + public void writeTestOutput(TestOutputReportEntry reportEntry) {} @Override - public boolean isDebugEnabled() - { + public boolean isDebugEnabled() { return false; } @Override - public void debug( String message ) - { - - } + public void debug(String message) {} @Override - public boolean isInfoEnabled() - { + public boolean isInfoEnabled() { return false; } @Override - public void info( String message ) - { - - } + public void info(String message) {} @Override - public boolean isWarnEnabled() - { + public boolean isWarnEnabled() { return false; } @Override - public void warning( String message ) - { - - } + public void warning(String message) {} @Override - public boolean isErrorEnabled() - { + public boolean isErrorEnabled() { return false; } @Override - public void error( String message ) - { - - } + public void error(String message) {} @Override - public void error( String message, Throwable t ) - { - - } + public void error(String message, Throwable t) {} @Override - public void error( Throwable t ) - { - - } + public void error(Throwable t) {} } diff --git a/surefire-providers/surefire-junit47/src/test/java/org/apache/maven/surefire/junitcore/Surefire746Test.java b/surefire-providers/surefire-junit47/src/test/java/org/apache/maven/surefire/junitcore/Surefire746Test.java index fab0367b68..4f699475a6 100644 --- a/surefire-providers/surefire-junit47/src/test/java/org/apache/maven/surefire/junitcore/Surefire746Test.java +++ b/surefire-providers/surefire-junit47/src/test/java/org/apache/maven/surefire/junitcore/Surefire746Test.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.junitcore; /* @@ -99,91 +117,76 @@ * @author Aslak Knutsen * @version $Revision: $ */ -public class Surefire746Test -{ +public class Surefire746Test { @Rule public final ExpectedException exception = ExpectedException.none(); @Test - @SuppressWarnings( "checkstyle:methodname" ) - public void surefireIsConfused_ByMultipleIgnore_OnClassLevel() throws Exception - { + @SuppressWarnings("checkstyle:methodname") + public void surefireIsConfused_ByMultipleIgnore_OnClassLevel() throws Exception { ReporterFactory reporterFactory = JUnitCoreTester.defaultNoXml(); - BaseProviderFactory providerParameters = new BaseProviderFactory( true ); - providerParameters.setReporterFactory( reporterFactory ); + BaseProviderFactory providerParameters = new BaseProviderFactory(true); + providerParameters.setReporterFactory(reporterFactory); - providerParameters.setReporterConfiguration( new ReporterConfiguration( new File( "" ), false ) ); + providerParameters.setReporterConfiguration(new ReporterConfiguration(new File(""), false)); Map junitProps = new HashMap<>(); - junitProps.put( ProviderParameterNames.PARALLEL_PROP, "none" ); + junitProps.put(ProviderParameterNames.PARALLEL_PROP, "none"); - JUnitCoreParameters jUnitCoreParameters = new JUnitCoreParameters( junitProps ); + JUnitCoreParameters jUnitCoreParameters = new JUnitCoreParameters(junitProps); final Map testSetMap = new ConcurrentHashMap<>(); - ConcurrentRunListener listener = createInstance( testSetMap, reporterFactory, false, false ); + ConcurrentRunListener listener = createInstance(testSetMap, reporterFactory, false, false); - TestsToRun testsToRun = new TestsToRun( Collections.>singleton( TestClassTest.class ) ); + TestsToRun testsToRun = new TestsToRun(Collections.>singleton(TestClassTest.class)); - org.junit.runner.notification.RunListener jUnit4RunListener = new JUnitCoreRunListener( listener, testSetMap ); + org.junit.runner.notification.RunListener jUnit4RunListener = new JUnitCoreRunListener(listener, testSetMap); List customRunListeners = new ArrayList<>(); - customRunListeners.add( 0, jUnit4RunListener ); + customRunListeners.add(0, jUnit4RunListener); - try - { + try { // JUnitCoreWrapper#execute() is calling JUnit4RunListener#rethrowAnyTestMechanismFailures() // and rethrows a failure which happened in listener - exception.expect( TestSetFailedException.class ); - JUnit4RunListener dummy = new JUnit4RunListener( new MockReporter() ); - new JUnitCoreWrapper( new Notifier( dummy, 0 ), jUnitCoreParameters, mock( ConsoleLogger.class ) ) - .execute( testsToRun, customRunListeners, null ); - } - finally - { + exception.expect(TestSetFailedException.class); + JUnit4RunListener dummy = new JUnit4RunListener(new MockReporter()); + new JUnitCoreWrapper(new Notifier(dummy, 0), jUnitCoreParameters, mock(ConsoleLogger.class)) + .execute(testsToRun, customRunListeners, null); + } finally { RunResult result = reporterFactory.close(); - assertEquals( "JUnit should report correctly number of test ran(Finished)", 1, - result.getCompletedCount() ); + assertEquals("JUnit should report correctly number of test ran(Finished)", 1, result.getCompletedCount()); } } /** * */ - @RunWith( TestCaseRunner.class ) - public static class TestClassTest - { + @RunWith(TestCaseRunner.class) + public static class TestClassTest { @Test - public void shouldNeverBeCalled() throws Exception - { - } + public void shouldNeverBeCalled() throws Exception {} } /** * */ - public static class TestCaseRunner extends BlockJUnit4ClassRunner - { - public TestCaseRunner( Class klass ) throws InitializationError - { - super( klass ); + public static class TestCaseRunner extends BlockJUnit4ClassRunner { + public TestCaseRunner(Class klass) throws InitializationError { + super(klass); } @Override - public void run( RunNotifier notifier ) - { - notifier.addListener( new Listener() ); - super.run( notifier ); + public void run(RunNotifier notifier) { + notifier.addListener(new Listener()); + super.run(notifier); } - } - private static class Listener extends org.junit.runner.notification.RunListener - { + private static class Listener extends org.junit.runner.notification.RunListener { @Override - public void testFinished( Description description ) throws Exception - { + public void testFinished(Description description) throws Exception { throw new RuntimeException( - "This Exception will cause Surefire to receive an internal JUnit Description and fail." ); + "This Exception will cause Surefire to receive an internal JUnit Description and fail."); } } } diff --git a/surefire-providers/surefire-junit47/src/test/java/org/apache/maven/surefire/junitcore/Surefire813IncorrectResultTest.java b/surefire-providers/surefire-junit47/src/test/java/org/apache/maven/surefire/junitcore/Surefire813IncorrectResultTest.java index 90b0608a28..eb4adaacd5 100644 --- a/surefire-providers/surefire-junit47/src/test/java/org/apache/maven/surefire/junitcore/Surefire813IncorrectResultTest.java +++ b/surefire-providers/surefire-junit47/src/test/java/org/apache/maven/surefire/junitcore/Surefire813IncorrectResultTest.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.junitcore; /* @@ -21,8 +39,8 @@ import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; -import org.apache.maven.surefire.api.testset.TestSetFailedException; +import org.apache.maven.surefire.api.testset.TestSetFailedException; import org.junit.After; import org.junit.Test; import org.junit.runner.Result; @@ -33,61 +51,48 @@ * @author Kristian Rosenvold * @author nkeyval */ -public class Surefire813IncorrectResultTest -{ +public class Surefire813IncorrectResultTest { @Test - public void dcount() - throws TestSetFailedException, ExecutionException - { + public void dcount() throws TestSetFailedException, ExecutionException { JUnitCoreTester jUnitCoreTester = new JUnitCoreTester(); - final Result run = jUnitCoreTester.run( true, Test6.class ); - assertEquals( 0, run.getFailureCount() ); + final Result run = jUnitCoreTester.run(true, Test6.class); + assertEquals(0, run.getFailureCount()); } /** * */ - public static class Test6 - { - private final CountDownLatch latch = new CountDownLatch( 1 ); + public static class Test6 { + private final CountDownLatch latch = new CountDownLatch(1); @Test - public void test61() - throws Exception - { - System.out.println( "Hey" ); + public void test61() throws Exception { + System.out.println("Hey"); } @After - public void tearDown() - throws Exception - { + public void tearDown() throws Exception { new MyThread().start(); latch.await(); } private static final String STR = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"; - public void synchPrint() - { - for ( int i = 0; i < 1000; ++i ) // Increase this number if it does no fail + public void synchPrint() { + for (int i = 0; i < 1000; ++i) // Increase this number if it does no fail { - System.out.println( i + ":" + STR ); + System.out.println(i + ":" + STR); } } - private class MyThread - extends Thread - { + private class MyThread extends Thread { @Override - public void run() - { - System.out.println( STR ); + public void run() { + System.out.println(STR); latch.countDown(); synchPrint(); } } } - } diff --git a/surefire-providers/surefire-junit47/src/test/java/org/apache/maven/surefire/junitcore/TestMethodTest.java b/surefire-providers/surefire-junit47/src/test/java/org/apache/maven/surefire/junitcore/TestMethodTest.java index cd42fe9b8c..e40321354e 100644 --- a/surefire-providers/surefire-junit47/src/test/java/org/apache/maven/surefire/junitcore/TestMethodTest.java +++ b/surefire-providers/surefire-junit47/src/test/java/org/apache/maven/surefire/junitcore/TestMethodTest.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.junitcore; /* @@ -19,30 +37,26 @@ * under the License. */ +import junit.framework.TestCase; import org.apache.maven.surefire.api.report.ReportEntry; import org.apache.maven.surefire.api.report.SimpleReportEntry; -import junit.framework.TestCase; - import static org.apache.maven.surefire.api.report.RunMode.NORMAL_RUN; /** * @author Kristian Rosenvold */ -public class TestMethodTest - extends TestCase -{ +public class TestMethodTest extends TestCase { public static final int BIG_UPTIME = 100_000; - public void testTestFailure() - { - ReportEntry reportEntry = new SimpleReportEntry( NORMAL_RUN, 0L, "a", null, "b", null ); - TestSet testSet = new TestSet( TestMethodTest.class.getName(), NORMAL_RUN, null ); - TestMethod testMethod = new TestMethod( reportEntry, testSet ); - testMethod.testFailure( reportEntry ); + public void testTestFailure() { + ReportEntry reportEntry = new SimpleReportEntry(NORMAL_RUN, 0L, "a", null, "b", null); + TestSet testSet = new TestSet(TestMethodTest.class.getName(), NORMAL_RUN, null); + TestMethod testMethod = new TestMethod(reportEntry, testSet); + testMethod.testFailure(reportEntry); final int elapsed = testMethod.getElapsed(); - assertTrue( elapsed >= 0 ); - assertTrue( elapsed < BIG_UPTIME ); + assertTrue(elapsed >= 0); + assertTrue(elapsed < BIG_UPTIME); } } diff --git a/surefire-providers/surefire-junit47/src/test/java/org/apache/maven/surefire/junitcore/pc/OptimizedParallelComputerTest.java b/surefire-providers/surefire-junit47/src/test/java/org/apache/maven/surefire/junitcore/pc/OptimizedParallelComputerTest.java index 764c57a691..5ce9c66d40 100644 --- a/surefire-providers/surefire-junit47/src/test/java/org/apache/maven/surefire/junitcore/pc/OptimizedParallelComputerTest.java +++ b/surefire-providers/surefire-junit47/src/test/java/org/apache/maven/surefire/junitcore/pc/OptimizedParallelComputerTest.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.junitcore.pc; /* @@ -19,8 +37,11 @@ * under the License. */ -import org.apache.maven.surefire.junitcore.JUnitCoreParameters; +import java.util.HashMap; +import java.util.Map; + import org.apache.maven.surefire.api.testset.TestSetFailedException; +import org.apache.maven.surefire.junitcore.JUnitCoreParameters; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Rule; @@ -30,15 +51,12 @@ import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; -import java.util.HashMap; -import java.util.Map; - import static org.apache.maven.surefire.junitcore.JUnitCoreParameters.PARALLEL_KEY; -import static org.apache.maven.surefire.junitcore.JUnitCoreParameters.THREADCOUNT_KEY; -import static org.apache.maven.surefire.junitcore.JUnitCoreParameters.THREADCOUNTSUITES_KEY; import static org.apache.maven.surefire.junitcore.JUnitCoreParameters.THREADCOUNTCLASSES_KEY; -import static org.apache.maven.surefire.junitcore.pc.ParallelComputerUtil.resolveConcurrency; +import static org.apache.maven.surefire.junitcore.JUnitCoreParameters.THREADCOUNTSUITES_KEY; +import static org.apache.maven.surefire.junitcore.JUnitCoreParameters.THREADCOUNT_KEY; import static org.apache.maven.surefire.junitcore.pc.ParallelComputerUtil.overrideAvailableProcessors; +import static org.apache.maven.surefire.junitcore.pc.ParallelComputerUtil.resolveConcurrency; import static org.apache.maven.surefire.junitcore.pc.ParallelComputerUtil.setDefaultAvailableProcessors; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertFalse; @@ -53,10 +71,9 @@ * @see ParallelComputerUtil * @since 2.17 */ -@RunWith( Theories.class ) -@SuppressWarnings( "checkstyle:magicnumber" ) -public final class OptimizedParallelComputerTest -{ +@RunWith(Theories.class) +@SuppressWarnings("checkstyle:magicnumber") +public final class OptimizedParallelComputerTest { @DataPoint public static final int CPU_1 = 1; @@ -67,251 +84,237 @@ public final class OptimizedParallelComputerTest public final ExpectedException exception = ExpectedException.none(); @BeforeClass - public static void beforeClass() - { - overrideAvailableProcessors( 1 ); + public static void beforeClass() { + overrideAvailableProcessors(1); } @AfterClass - public static void afterClass() - { + public static void afterClass() { setDefaultAvailableProcessors(); } @Theory - public void threadCountSuites( int cpu ) throws TestSetFailedException - { - overrideAvailableProcessors( cpu ); + public void threadCountSuites(int cpu) throws TestSetFailedException { + overrideAvailableProcessors(cpu); Map properties = new HashMap<>(); - properties.put( PARALLEL_KEY, "suites" ); - properties.put( THREADCOUNT_KEY, "3" ); - JUnitCoreParameters params = new JUnitCoreParameters( properties ); - RunnerCounter counter = new RunnerCounter( 5, 10, 20 ); - Concurrency concurrency = resolveConcurrency( params, counter ); - assertTrue( params.isParallelSuites() ); - assertFalse( params.isParallelClasses() ); - assertFalse( params.isParallelMethods() ); - assertThat( concurrency.capacity, is( 0 ) ); - assertThat( concurrency.suites, is( (int) Math.min( 3 * cpu, counter.suites ) ) ); - assertThat( concurrency.classes, is( 0 ) ); - assertThat( concurrency.methods, is( 0 ) ); + properties.put(PARALLEL_KEY, "suites"); + properties.put(THREADCOUNT_KEY, "3"); + JUnitCoreParameters params = new JUnitCoreParameters(properties); + RunnerCounter counter = new RunnerCounter(5, 10, 20); + Concurrency concurrency = resolveConcurrency(params, counter); + assertTrue(params.isParallelSuites()); + assertFalse(params.isParallelClasses()); + assertFalse(params.isParallelMethods()); + assertThat(concurrency.capacity, is(0)); + assertThat(concurrency.suites, is((int) Math.min(3 * cpu, counter.suites))); + assertThat(concurrency.classes, is(0)); + assertThat(concurrency.methods, is(0)); } @Theory - public void threadCountClasses( int cpu ) throws TestSetFailedException - { - overrideAvailableProcessors( cpu ); + public void threadCountClasses(int cpu) throws TestSetFailedException { + overrideAvailableProcessors(cpu); Map properties = new HashMap<>(); - properties.put( PARALLEL_KEY, "classes" ); - properties.put( THREADCOUNT_KEY, "3" ); - JUnitCoreParameters params = new JUnitCoreParameters( properties ); - RunnerCounter counter = new RunnerCounter( 1, 5, 10 ); - Concurrency concurrency = resolveConcurrency( params, counter ); - assertFalse( params.isParallelSuites() ); - assertTrue( params.isParallelClasses() ); - assertFalse( params.isParallelMethods() ); - assertThat( concurrency.capacity, is( 0 ) ); - assertThat( concurrency.suites, is( 0 ) ); - assertThat( concurrency.classes, is( (int) Math.min( 3 * cpu, counter.classes ) ) ); - assertThat( concurrency.methods, is( 0 ) ); + properties.put(PARALLEL_KEY, "classes"); + properties.put(THREADCOUNT_KEY, "3"); + JUnitCoreParameters params = new JUnitCoreParameters(properties); + RunnerCounter counter = new RunnerCounter(1, 5, 10); + Concurrency concurrency = resolveConcurrency(params, counter); + assertFalse(params.isParallelSuites()); + assertTrue(params.isParallelClasses()); + assertFalse(params.isParallelMethods()); + assertThat(concurrency.capacity, is(0)); + assertThat(concurrency.suites, is(0)); + assertThat(concurrency.classes, is((int) Math.min(3 * cpu, counter.classes))); + assertThat(concurrency.methods, is(0)); } @Theory - public void threadCountMethods( int cpu ) throws TestSetFailedException - { - overrideAvailableProcessors( cpu ); + public void threadCountMethods(int cpu) throws TestSetFailedException { + overrideAvailableProcessors(cpu); Map properties = new HashMap<>(); - properties.put( PARALLEL_KEY, "methods" ); - properties.put( THREADCOUNT_KEY, "3" ); - JUnitCoreParameters params = new JUnitCoreParameters( properties ); - RunnerCounter counter = new RunnerCounter( 1, 2, 5 ); - Concurrency concurrency = resolveConcurrency( params, counter ); - assertFalse( params.isParallelSuites() ); - assertFalse( params.isParallelClasses() ); - assertTrue( params.isParallelMethods() ); - assertThat( concurrency.capacity, is( 0 ) ); - assertThat( concurrency.suites, is( 0 ) ); - assertThat( concurrency.classes, is( 0 ) ); - assertThat( concurrency.methods, is( (int) Math.min( 3 * cpu, counter.methods ) ) ); + properties.put(PARALLEL_KEY, "methods"); + properties.put(THREADCOUNT_KEY, "3"); + JUnitCoreParameters params = new JUnitCoreParameters(properties); + RunnerCounter counter = new RunnerCounter(1, 2, 5); + Concurrency concurrency = resolveConcurrency(params, counter); + assertFalse(params.isParallelSuites()); + assertFalse(params.isParallelClasses()); + assertTrue(params.isParallelMethods()); + assertThat(concurrency.capacity, is(0)); + assertThat(concurrency.suites, is(0)); + assertThat(concurrency.classes, is(0)); + assertThat(concurrency.methods, is((int) Math.min(3 * cpu, counter.methods))); } @Theory - public void threadCountBoth( int cpu ) throws TestSetFailedException - { - overrideAvailableProcessors( cpu ); + public void threadCountBoth(int cpu) throws TestSetFailedException { + overrideAvailableProcessors(cpu); Map properties = new HashMap<>(); - properties.put( PARALLEL_KEY, "both" ); - properties.put( THREADCOUNT_KEY, "3" ); - JUnitCoreParameters params = new JUnitCoreParameters( properties ); - RunnerCounter counter = new RunnerCounter( 1, 2, 5 ); - Concurrency concurrency = resolveConcurrency( params, counter ); - assertFalse( params.isParallelSuites() ); - assertTrue( params.isParallelClasses() ); - assertTrue( params.isParallelMethods() ); - assertThat( concurrency.capacity, is( 3 * cpu ) ); - assertThat( concurrency.suites, is( 0 ) ); - assertThat( concurrency.classes, is( (int) Math.min( ( 3d / 2 ) * cpu, 2 ) ) ); - assertThat( concurrency.methods, is( Integer.MAX_VALUE ) ); + properties.put(PARALLEL_KEY, "both"); + properties.put(THREADCOUNT_KEY, "3"); + JUnitCoreParameters params = new JUnitCoreParameters(properties); + RunnerCounter counter = new RunnerCounter(1, 2, 5); + Concurrency concurrency = resolveConcurrency(params, counter); + assertFalse(params.isParallelSuites()); + assertTrue(params.isParallelClasses()); + assertTrue(params.isParallelMethods()); + assertThat(concurrency.capacity, is(3 * cpu)); + assertThat(concurrency.suites, is(0)); + assertThat(concurrency.classes, is((int) Math.min((3d / 2) * cpu, 2))); + assertThat(concurrency.methods, is(Integer.MAX_VALUE)); } @Theory - public void threadCountClassesAndMethods( int cpu ) throws TestSetFailedException - { - overrideAvailableProcessors( cpu ); + public void threadCountClassesAndMethods(int cpu) throws TestSetFailedException { + overrideAvailableProcessors(cpu); Map properties = new HashMap<>(); - properties.put( PARALLEL_KEY, "classesAndMethods" ); - properties.put( THREADCOUNT_KEY, "3" ); - JUnitCoreParameters params = new JUnitCoreParameters( properties ); - RunnerCounter counter = new RunnerCounter( 1, 2, 5 ); - Concurrency concurrency = resolveConcurrency( params, counter ); - assertFalse( params.isParallelSuites() ); - assertTrue( params.isParallelClasses() ); - assertTrue( params.isParallelMethods() ); - assertThat( concurrency.capacity, is( 3 * cpu ) ); - assertThat( concurrency.suites, is( 0 ) ); - assertThat( concurrency.classes, is( (int) Math.min( ( 3d / 2 ) * cpu, 2 ) ) ); - assertThat( concurrency.methods, is( Integer.MAX_VALUE ) ); + properties.put(PARALLEL_KEY, "classesAndMethods"); + properties.put(THREADCOUNT_KEY, "3"); + JUnitCoreParameters params = new JUnitCoreParameters(properties); + RunnerCounter counter = new RunnerCounter(1, 2, 5); + Concurrency concurrency = resolveConcurrency(params, counter); + assertFalse(params.isParallelSuites()); + assertTrue(params.isParallelClasses()); + assertTrue(params.isParallelMethods()); + assertThat(concurrency.capacity, is(3 * cpu)); + assertThat(concurrency.suites, is(0)); + assertThat(concurrency.classes, is((int) Math.min((3d / 2) * cpu, 2))); + assertThat(concurrency.methods, is(Integer.MAX_VALUE)); } @Theory - public void threadCountSuitesAndMethods( int cpu ) throws TestSetFailedException - { - overrideAvailableProcessors( cpu ); + public void threadCountSuitesAndMethods(int cpu) throws TestSetFailedException { + overrideAvailableProcessors(cpu); Map properties = new HashMap<>(); - properties.put( PARALLEL_KEY, "suitesAndMethods" ); - properties.put( THREADCOUNT_KEY, "3" ); - JUnitCoreParameters params = new JUnitCoreParameters( properties ); - RunnerCounter counter = new RunnerCounter( 2, 3, 5 ); - Concurrency concurrency = resolveConcurrency( params, counter ); - assertTrue( params.isParallelSuites() ); - assertFalse( params.isParallelClasses() ); - assertTrue( params.isParallelMethods() ); - assertThat( concurrency.capacity, is( 3 * cpu ) ); - assertThat( concurrency.suites, is( (int) Math.min( ( 3d / 2 ) * cpu, 2 ) ) ); - assertThat( concurrency.classes, is( 0 ) ); - assertThat( concurrency.methods, is( Integer.MAX_VALUE ) ); + properties.put(PARALLEL_KEY, "suitesAndMethods"); + properties.put(THREADCOUNT_KEY, "3"); + JUnitCoreParameters params = new JUnitCoreParameters(properties); + RunnerCounter counter = new RunnerCounter(2, 3, 5); + Concurrency concurrency = resolveConcurrency(params, counter); + assertTrue(params.isParallelSuites()); + assertFalse(params.isParallelClasses()); + assertTrue(params.isParallelMethods()); + assertThat(concurrency.capacity, is(3 * cpu)); + assertThat(concurrency.suites, is((int) Math.min((3d / 2) * cpu, 2))); + assertThat(concurrency.classes, is(0)); + assertThat(concurrency.methods, is(Integer.MAX_VALUE)); } @Theory - public void threadCountSuitesAndClasses( int cpu ) throws TestSetFailedException - { - overrideAvailableProcessors( cpu ); + public void threadCountSuitesAndClasses(int cpu) throws TestSetFailedException { + overrideAvailableProcessors(cpu); Map properties = new HashMap<>(); - properties.put( PARALLEL_KEY, "suitesAndClasses" ); - properties.put( THREADCOUNT_KEY, "3" ); - JUnitCoreParameters params = new JUnitCoreParameters( properties ); - RunnerCounter counter = new RunnerCounter( 2, 5, 20 ); - Concurrency concurrency = resolveConcurrency( params, counter ); - assertTrue( params.isParallelSuites() ); - assertTrue( params.isParallelClasses() ); - assertFalse( params.isParallelMethods() ); - assertThat( concurrency.capacity, is( 3 * cpu ) ); - assertThat( concurrency.suites, is( (int) Math.min( ( 2d * 3 / 7 ) * cpu, 2 ) ) ); - assertThat( concurrency.classes, is( Integer.MAX_VALUE ) ); - assertThat( concurrency.methods, is( 0 ) ); + properties.put(PARALLEL_KEY, "suitesAndClasses"); + properties.put(THREADCOUNT_KEY, "3"); + JUnitCoreParameters params = new JUnitCoreParameters(properties); + RunnerCounter counter = new RunnerCounter(2, 5, 20); + Concurrency concurrency = resolveConcurrency(params, counter); + assertTrue(params.isParallelSuites()); + assertTrue(params.isParallelClasses()); + assertFalse(params.isParallelMethods()); + assertThat(concurrency.capacity, is(3 * cpu)); + assertThat(concurrency.suites, is((int) Math.min((2d * 3 / 7) * cpu, 2))); + assertThat(concurrency.classes, is(Integer.MAX_VALUE)); + assertThat(concurrency.methods, is(0)); } @Theory - public void threadCountAll( int cpu ) throws TestSetFailedException - { - overrideAvailableProcessors( cpu ); + public void threadCountAll(int cpu) throws TestSetFailedException { + overrideAvailableProcessors(cpu); Map properties = new HashMap<>(); - properties.put( PARALLEL_KEY, "all" ); - properties.put( THREADCOUNT_KEY, "3" ); - JUnitCoreParameters params = new JUnitCoreParameters( properties ); - RunnerCounter counter = new RunnerCounter( 2, 5, 20 ); - Concurrency concurrency = resolveConcurrency( params, counter ); - assertTrue( params.isParallelSuites() ); - assertTrue( params.isParallelClasses() ); - assertTrue( params.isParallelMethods() ); - assertThat( concurrency.capacity, is( 3 * cpu ) ); - assertThat( concurrency.suites, is( (int) Math.min( ( 2d * 3 / 11 ) * cpu, 2 ) ) ); - assertThat( concurrency.classes, is( (int) Math.min( ( 5d * 3 / 11 ) * cpu, 5 ) ) ); - assertThat( concurrency.methods, is( Integer.MAX_VALUE ) ); + properties.put(PARALLEL_KEY, "all"); + properties.put(THREADCOUNT_KEY, "3"); + JUnitCoreParameters params = new JUnitCoreParameters(properties); + RunnerCounter counter = new RunnerCounter(2, 5, 20); + Concurrency concurrency = resolveConcurrency(params, counter); + assertTrue(params.isParallelSuites()); + assertTrue(params.isParallelClasses()); + assertTrue(params.isParallelMethods()); + assertThat(concurrency.capacity, is(3 * cpu)); + assertThat(concurrency.suites, is((int) Math.min((2d * 3 / 11) * cpu, 2))); + assertThat(concurrency.classes, is((int) Math.min((5d * 3 / 11) * cpu, 5))); + assertThat(concurrency.methods, is(Integer.MAX_VALUE)); } @Theory - public void reusableThreadCountSuitesAndClasses( int cpu ) throws TestSetFailedException - { + public void reusableThreadCountSuitesAndClasses(int cpu) throws TestSetFailedException { // 4 * cpu to 5 * cpu threads to run test classes - overrideAvailableProcessors( cpu ); + overrideAvailableProcessors(cpu); Map properties = new HashMap<>(); - properties.put( PARALLEL_KEY, "suitesAndClasses" ); - properties.put( THREADCOUNT_KEY, "6" ); - properties.put( THREADCOUNTSUITES_KEY, "2" ); - JUnitCoreParameters params = new JUnitCoreParameters( properties ); - RunnerCounter counter = new RunnerCounter( 3, 5, 20 ); - Concurrency concurrency = resolveConcurrency( params, counter ); - assertTrue( params.isParallelSuites() ); - assertTrue( params.isParallelClasses() ); - assertFalse( params.isParallelMethods() ); - assertThat( concurrency.capacity, is( 6 * cpu ) ); - assertThat( concurrency.suites, is( Math.min( 2 * cpu, 3 ) ) ); - assertThat( concurrency.classes, is( Integer.MAX_VALUE ) ); - assertThat( concurrency.methods, is( 0 ) ); + properties.put(PARALLEL_KEY, "suitesAndClasses"); + properties.put(THREADCOUNT_KEY, "6"); + properties.put(THREADCOUNTSUITES_KEY, "2"); + JUnitCoreParameters params = new JUnitCoreParameters(properties); + RunnerCounter counter = new RunnerCounter(3, 5, 20); + Concurrency concurrency = resolveConcurrency(params, counter); + assertTrue(params.isParallelSuites()); + assertTrue(params.isParallelClasses()); + assertFalse(params.isParallelMethods()); + assertThat(concurrency.capacity, is(6 * cpu)); + assertThat(concurrency.suites, is(Math.min(2 * cpu, 3))); + assertThat(concurrency.classes, is(Integer.MAX_VALUE)); + assertThat(concurrency.methods, is(0)); } @Theory - public void reusableThreadCountSuitesAndMethods( int cpu ) throws TestSetFailedException - { + public void reusableThreadCountSuitesAndMethods(int cpu) throws TestSetFailedException { // 4 * cpu to 5 * cpu threads to run test methods - overrideAvailableProcessors( cpu ); + overrideAvailableProcessors(cpu); Map properties = new HashMap<>(); - properties.put( PARALLEL_KEY, "suitesAndMethods" ); - properties.put( THREADCOUNT_KEY, "6" ); - properties.put( THREADCOUNTSUITES_KEY, "2" ); - JUnitCoreParameters params = new JUnitCoreParameters( properties ); - RunnerCounter counter = new RunnerCounter( 3, 5, 20 ); - Concurrency concurrency = resolveConcurrency( params, counter ); - assertTrue( params.isParallelSuites() ); - assertFalse( params.isParallelClasses() ); - assertTrue( params.isParallelMethods() ); - assertThat( concurrency.capacity, is( 6 * cpu ) ); - assertThat( concurrency.suites, is( Math.min( 2 * cpu, 3 ) ) ); - assertThat( concurrency.classes, is( 0 ) ); - assertThat( concurrency.methods, is( Integer.MAX_VALUE ) ); + properties.put(PARALLEL_KEY, "suitesAndMethods"); + properties.put(THREADCOUNT_KEY, "6"); + properties.put(THREADCOUNTSUITES_KEY, "2"); + JUnitCoreParameters params = new JUnitCoreParameters(properties); + RunnerCounter counter = new RunnerCounter(3, 5, 20); + Concurrency concurrency = resolveConcurrency(params, counter); + assertTrue(params.isParallelSuites()); + assertFalse(params.isParallelClasses()); + assertTrue(params.isParallelMethods()); + assertThat(concurrency.capacity, is(6 * cpu)); + assertThat(concurrency.suites, is(Math.min(2 * cpu, 3))); + assertThat(concurrency.classes, is(0)); + assertThat(concurrency.methods, is(Integer.MAX_VALUE)); } @Theory - public void reusableThreadCountClassesAndMethods( int cpu ) throws TestSetFailedException - { + public void reusableThreadCountClassesAndMethods(int cpu) throws TestSetFailedException { // 4 * cpu to 5 * cpu threads to run test methods - overrideAvailableProcessors( cpu ); + overrideAvailableProcessors(cpu); Map properties = new HashMap<>(); - properties.put( PARALLEL_KEY, "classesAndMethods" ); - properties.put( THREADCOUNT_KEY, "6" ); - properties.put( THREADCOUNTCLASSES_KEY, "2" ); - JUnitCoreParameters params = new JUnitCoreParameters( properties ); - RunnerCounter counter = new RunnerCounter( 3, 5, 20 ); - Concurrency concurrency = resolveConcurrency( params, counter ); - assertFalse( params.isParallelSuites() ); - assertTrue( params.isParallelClasses() ); - assertTrue( params.isParallelMethods() ); - assertThat( concurrency.capacity, is( 6 * cpu ) ); - assertThat( concurrency.suites, is( 0 ) ); - assertThat( concurrency.classes, is( Math.min( 2 * cpu, 5 ) ) ); - assertThat( concurrency.methods, is( Integer.MAX_VALUE ) ); + properties.put(PARALLEL_KEY, "classesAndMethods"); + properties.put(THREADCOUNT_KEY, "6"); + properties.put(THREADCOUNTCLASSES_KEY, "2"); + JUnitCoreParameters params = new JUnitCoreParameters(properties); + RunnerCounter counter = new RunnerCounter(3, 5, 20); + Concurrency concurrency = resolveConcurrency(params, counter); + assertFalse(params.isParallelSuites()); + assertTrue(params.isParallelClasses()); + assertTrue(params.isParallelMethods()); + assertThat(concurrency.capacity, is(6 * cpu)); + assertThat(concurrency.suites, is(0)); + assertThat(concurrency.classes, is(Math.min(2 * cpu, 5))); + assertThat(concurrency.methods, is(Integer.MAX_VALUE)); } @Theory - public void reusableThreadCountAll( int cpu ) throws TestSetFailedException - { + public void reusableThreadCountAll(int cpu) throws TestSetFailedException { // 8 * cpu to 13 * cpu threads to run test methods - overrideAvailableProcessors( cpu ); + overrideAvailableProcessors(cpu); Map properties = new HashMap<>(); - properties.put( PARALLEL_KEY, "all" ); - properties.put( THREADCOUNT_KEY, "14" ); - properties.put( THREADCOUNTSUITES_KEY, "2" ); - properties.put( THREADCOUNTCLASSES_KEY, "4" ); - JUnitCoreParameters params = new JUnitCoreParameters( properties ); - RunnerCounter counter = new RunnerCounter( 3, 5, 20 ); - Concurrency concurrency = resolveConcurrency( params, counter ); - assertTrue( params.isParallelSuites() ); - assertTrue( params.isParallelClasses() ); - assertTrue( params.isParallelMethods() ); - assertThat( concurrency.capacity, is( 14 * cpu ) ); - assertThat( concurrency.suites, is( Math.min( 2 * cpu, 3 ) ) ); - assertThat( concurrency.classes, is( Math.min( 4 * cpu, 5 ) ) ); - assertThat( concurrency.methods, is( Integer.MAX_VALUE ) ); + properties.put(PARALLEL_KEY, "all"); + properties.put(THREADCOUNT_KEY, "14"); + properties.put(THREADCOUNTSUITES_KEY, "2"); + properties.put(THREADCOUNTCLASSES_KEY, "4"); + JUnitCoreParameters params = new JUnitCoreParameters(properties); + RunnerCounter counter = new RunnerCounter(3, 5, 20); + Concurrency concurrency = resolveConcurrency(params, counter); + assertTrue(params.isParallelSuites()); + assertTrue(params.isParallelClasses()); + assertTrue(params.isParallelMethods()); + assertThat(concurrency.capacity, is(14 * cpu)); + assertThat(concurrency.suites, is(Math.min(2 * cpu, 3))); + assertThat(concurrency.classes, is(Math.min(4 * cpu, 5))); + assertThat(concurrency.methods, is(Integer.MAX_VALUE)); } } diff --git a/surefire-providers/surefire-junit47/src/test/java/org/apache/maven/surefire/junitcore/pc/ParallelComputerBuilderTest.java b/surefire-providers/surefire-junit47/src/test/java/org/apache/maven/surefire/junitcore/pc/ParallelComputerBuilderTest.java index 5716256bd1..920ee43c08 100755 --- a/surefire-providers/surefire-junit47/src/test/java/org/apache/maven/surefire/junitcore/pc/ParallelComputerBuilderTest.java +++ b/surefire-providers/surefire-junit47/src/test/java/org/apache/maven/surefire/junitcore/pc/ParallelComputerBuilderTest.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.junitcore.pc; /* @@ -19,6 +37,17 @@ * under the License. */ +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.Comparator; +import java.util.Date; +import java.util.Iterator; +import java.util.List; +import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.concurrent.TimeUnit; + import net.jcip.annotations.NotThreadSafe; import org.apache.maven.plugin.surefire.log.api.ConsoleLogger; import org.junit.After; @@ -35,17 +64,6 @@ import org.junit.runners.Suite; import org.junit.runners.model.InitializationError; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.Comparator; -import java.util.Date; -import java.util.Iterator; -import java.util.List; -import java.util.concurrent.ConcurrentLinkedQueue; -import java.util.concurrent.TimeUnit; - import static org.apache.maven.surefire.junitcore.pc.RangeMatcher.between; import static org.hamcrest.core.AnyOf.anyOf; import static org.hamcrest.core.Is.is; @@ -63,9 +81,8 @@ * @author Tibor Digana (tibor17) * @since 2.16 */ -@SuppressWarnings( "checkstyle:magicnumber" ) -public class ParallelComputerBuilderTest -{ +@SuppressWarnings("checkstyle:magicnumber") +public class ParallelComputerBuilderTest { private static final int DELAY_MULTIPLIER = 7; private static final Object CLASS1BLOCK = new Object(); @@ -74,39 +91,34 @@ public class ParallelComputerBuilderTest private static volatile Runnable shutdownTask; - private static final ConsoleLogger LOGGER = mock( ConsoleLogger.class ); + private static final ConsoleLogger LOGGER = mock(ConsoleLogger.class); - private static void testKeepBeforeAfter( ParallelComputerBuilder builder, Class... classes ) - { + private static void testKeepBeforeAfter(ParallelComputerBuilder builder, Class... classes) { JUnitCore core = new JUnitCore(); - for ( int round = 0; round < 5; round++ ) - { + for (int round = 0; round < 5; round++) { NothingDoingTest1.METHODS.clear(); - Result result = core.run( builder.buildComputer(), classes ); - assertTrue( result.wasSuccessful() ); + Result result = core.run(builder.buildComputer(), classes); + assertTrue(result.wasSuccessful()); Iterator methods = NothingDoingTest1.METHODS.iterator(); - for ( Class clazz : classes ) - { + for (Class clazz : classes) { String a = clazz.getName() + "#a()"; String b = clazz.getName() + "#b()"; - assertThat( methods.next(), is( "init" ) ); - assertThat( methods.next(), anyOf( is( a ), is( b ) ) ); - assertThat( methods.next(), anyOf( is( a ), is( b ) ) ); - assertThat( methods.next(), is( "deinit" ) ); + assertThat(methods.next(), is("init")); + assertThat(methods.next(), anyOf(is(a), is(b))); + assertThat(methods.next(), anyOf(is(a), is(b))); + assertThat(methods.next(), is("deinit")); } } } @BeforeClass - public static void cleanup() throws InterruptedException - { + public static void cleanup() throws InterruptedException { System.gc(); - Thread.sleep( 500L ); + Thread.sleep(500L); } @Before - public void beforeTest() - { + public void beforeTest() { Class1.maxConcurrentMethods = 0; Class1.concurrentMethods = 0; shutdownTask = null; @@ -118,189 +130,180 @@ public void beforeTest() } @Test - public void testsWithoutChildrenShouldAlsoBeRun() - { - ParallelComputerBuilder parallelComputerBuilder = new ParallelComputerBuilder( LOGGER ); + public void testsWithoutChildrenShouldAlsoBeRun() { + ParallelComputerBuilder parallelComputerBuilder = new ParallelComputerBuilder(LOGGER); ParallelComputerBuilder.PC computer = (ParallelComputerBuilder.PC) parallelComputerBuilder.buildComputer(); - Result result = new JUnitCore().run( computer, TestWithoutPrecalculatedChildren.class ); - assertThat( result.getRunCount(), is( 1 ) ); + Result result = new JUnitCore().run(computer, TestWithoutPrecalculatedChildren.class); + assertThat(result.getRunCount(), is(1)); } @Test - public void parallelMethodsReuseOneOrTwoThreads() - { - ParallelComputerBuilder parallelComputerBuilder = new ParallelComputerBuilder( LOGGER ); - parallelComputerBuilder.useOnePool( 4 ); + public void parallelMethodsReuseOneOrTwoThreads() { + ParallelComputerBuilder parallelComputerBuilder = new ParallelComputerBuilder(LOGGER); + parallelComputerBuilder.useOnePool(4); // One thread because one suite: TestSuite, however the capacity is 5. - parallelComputerBuilder.parallelSuites( 5 ); + parallelComputerBuilder.parallelSuites(5); // Two threads because TestSuite has two classes, however the capacity is 5. - parallelComputerBuilder.parallelClasses( 5 ); + parallelComputerBuilder.parallelClasses(5); // One or two threads because one threads comes from '#useOnePool(4)' // and next thread may be reused from finished class, however the capacity is 3. - parallelComputerBuilder.parallelMethods( 3 ); + parallelComputerBuilder.parallelMethods(3); - assertFalse( parallelComputerBuilder.isOptimized() ); + assertFalse(parallelComputerBuilder.isOptimized()); ParallelComputerBuilder.PC computer = (ParallelComputerBuilder.PC) parallelComputerBuilder.buildComputer(); final JUnitCore core = new JUnitCore(); final long t1 = systemMillis(); - final Result result = core.run( computer, TestSuite.class ); + final Result result = core.run(computer, TestSuite.class); final long t2 = systemMillis(); final long timeSpent = t2 - t1; - assertThat( computer.getSuites().size(), is( 1 ) ); - assertThat( computer.getClasses().size(), is( 0 ) ); - assertThat( computer.getNestedClasses().size(), is( 2 ) ); - assertThat( computer.getNestedSuites().size(), is( 0 ) ); - assertFalse( computer.isSplitPool() ); - assertThat( computer.getPoolCapacity(), is( 4 ) ); - assertTrue( result.wasSuccessful() ); - if ( Class1.maxConcurrentMethods == 1 ) - { - assertThat( timeSpent, between( 2000 * DELAY_MULTIPLIER - 50, 2250 * DELAY_MULTIPLIER ) ); - } - else if ( Class1.maxConcurrentMethods == 2 ) - { - assertThat( timeSpent, between( 1500 * DELAY_MULTIPLIER - 50, 1750 * DELAY_MULTIPLIER ) ); - } - else - { + assertThat(computer.getSuites().size(), is(1)); + assertThat(computer.getClasses().size(), is(0)); + assertThat(computer.getNestedClasses().size(), is(2)); + assertThat(computer.getNestedSuites().size(), is(0)); + assertFalse(computer.isSplitPool()); + assertThat(computer.getPoolCapacity(), is(4)); + assertTrue(result.wasSuccessful()); + if (Class1.maxConcurrentMethods == 1) { + assertThat(timeSpent, between(2000 * DELAY_MULTIPLIER - 50, 2250 * DELAY_MULTIPLIER)); + } else if (Class1.maxConcurrentMethods == 2) { + assertThat(timeSpent, between(1500 * DELAY_MULTIPLIER - 50, 1750 * DELAY_MULTIPLIER)); + } else { fail(); } } @Test - public void suiteAndClassInOnePool() - { - ParallelComputerBuilder parallelComputerBuilder = new ParallelComputerBuilder( LOGGER ); - parallelComputerBuilder.useOnePool( 5 ); - parallelComputerBuilder.parallelSuites( 5 ); - parallelComputerBuilder.parallelClasses( 5 ); - parallelComputerBuilder.parallelMethods( 3 ); - assertFalse( parallelComputerBuilder.isOptimized() ); + public void suiteAndClassInOnePool() { + ParallelComputerBuilder parallelComputerBuilder = new ParallelComputerBuilder(LOGGER); + parallelComputerBuilder.useOnePool(5); + parallelComputerBuilder.parallelSuites(5); + parallelComputerBuilder.parallelClasses(5); + parallelComputerBuilder.parallelMethods(3); + assertFalse(parallelComputerBuilder.isOptimized()); ParallelComputerBuilder.PC computer = (ParallelComputerBuilder.PC) parallelComputerBuilder.buildComputer(); final JUnitCore core = new JUnitCore(); final long t1 = systemMillis(); - final Result result = core.run( computer, TestSuite.class, Class1.class ); + final Result result = core.run(computer, TestSuite.class, Class1.class); final long t2 = systemMillis(); final long timeSpent = t2 - t1; - assertThat( computer.getSuites().size(), is( 1 ) ); - assertThat( computer.getClasses().size(), is( 1 ) ); - assertThat( computer.getNestedClasses().size(), is( 2 ) ); - assertThat( computer.getNestedSuites().size(), is( 0 ) ); - assertFalse( computer.isSplitPool() ); - assertThat( computer.getPoolCapacity(), is( 5 ) ); - assertTrue( result.wasSuccessful() ); - assertThat( Class1.maxConcurrentMethods, is( 2 ) ); - assertThat( timeSpent, anyOf( between( 1500 * DELAY_MULTIPLIER - 50, 1750 * DELAY_MULTIPLIER ), - between( 2000 * DELAY_MULTIPLIER - 50, 2250 * DELAY_MULTIPLIER ), - between( 2500 * DELAY_MULTIPLIER - 50, 2750 * DELAY_MULTIPLIER ) ) ); + assertThat(computer.getSuites().size(), is(1)); + assertThat(computer.getClasses().size(), is(1)); + assertThat(computer.getNestedClasses().size(), is(2)); + assertThat(computer.getNestedSuites().size(), is(0)); + assertFalse(computer.isSplitPool()); + assertThat(computer.getPoolCapacity(), is(5)); + assertTrue(result.wasSuccessful()); + assertThat(Class1.maxConcurrentMethods, is(2)); + assertThat( + timeSpent, + anyOf( + between(1500 * DELAY_MULTIPLIER - 50, 1750 * DELAY_MULTIPLIER), + between(2000 * DELAY_MULTIPLIER - 50, 2250 * DELAY_MULTIPLIER), + between(2500 * DELAY_MULTIPLIER - 50, 2750 * DELAY_MULTIPLIER))); } @Test - public void onePoolWithUnlimitedParallelMethods() - { + public void onePoolWithUnlimitedParallelMethods() { // see ParallelComputerBuilder Javadoc - ParallelComputerBuilder parallelComputerBuilder = new ParallelComputerBuilder( LOGGER ); - parallelComputerBuilder.useOnePool( 8 ); - parallelComputerBuilder.parallelSuites( 2 ); - parallelComputerBuilder.parallelClasses( 4 ); + ParallelComputerBuilder parallelComputerBuilder = new ParallelComputerBuilder(LOGGER); + parallelComputerBuilder.useOnePool(8); + parallelComputerBuilder.parallelSuites(2); + parallelComputerBuilder.parallelClasses(4); parallelComputerBuilder.parallelMethods(); - assertFalse( parallelComputerBuilder.isOptimized() ); + assertFalse(parallelComputerBuilder.isOptimized()); ParallelComputerBuilder.PC computer = (ParallelComputerBuilder.PC) parallelComputerBuilder.buildComputer(); final JUnitCore core = new JUnitCore(); final long t1 = systemMillis(); - final Result result = core.run( computer, TestSuite.class, Class1.class ); + final Result result = core.run(computer, TestSuite.class, Class1.class); final long t2 = systemMillis(); final long timeSpent = t2 - t1; - assertThat( computer.getSuites().size(), is( 1 ) ); - assertThat( computer.getClasses().size(), is( 1 ) ); - assertThat( computer.getNestedClasses().size(), is( 2 ) ); - assertThat( computer.getNestedSuites().size(), is( 0 ) ); - assertFalse( computer.isSplitPool() ); - assertThat( computer.getPoolCapacity(), is( 8 ) ); - assertTrue( result.wasSuccessful() ); - assertThat( Class1.maxConcurrentMethods, is( 4 ) ); - assertThat( timeSpent, between( 1000 * DELAY_MULTIPLIER - 50, 1250 * DELAY_MULTIPLIER ) ); + assertThat(computer.getSuites().size(), is(1)); + assertThat(computer.getClasses().size(), is(1)); + assertThat(computer.getNestedClasses().size(), is(2)); + assertThat(computer.getNestedSuites().size(), is(0)); + assertFalse(computer.isSplitPool()); + assertThat(computer.getPoolCapacity(), is(8)); + assertTrue(result.wasSuccessful()); + assertThat(Class1.maxConcurrentMethods, is(4)); + assertThat(timeSpent, between(1000 * DELAY_MULTIPLIER - 50, 1250 * DELAY_MULTIPLIER)); } @Test - public void underflowParallelism() - { - ParallelComputerBuilder parallelComputerBuilder = new ParallelComputerBuilder( LOGGER ); - parallelComputerBuilder.useOnePool( 3 ); + public void underflowParallelism() { + ParallelComputerBuilder parallelComputerBuilder = new ParallelComputerBuilder(LOGGER); + parallelComputerBuilder.useOnePool(3); // One thread because one suite: TestSuite. - parallelComputerBuilder.parallelSuites( 5 ); + parallelComputerBuilder.parallelSuites(5); // One thread because of the limitation which is bottleneck. - parallelComputerBuilder.parallelClasses( 1 ); + parallelComputerBuilder.parallelClasses(1); // One thread remains from '#useOnePool(3)'. - parallelComputerBuilder.parallelMethods( 3 ); + parallelComputerBuilder.parallelMethods(3); - assertFalse( parallelComputerBuilder.isOptimized() ); + assertFalse(parallelComputerBuilder.isOptimized()); ParallelComputerBuilder.PC computer = (ParallelComputerBuilder.PC) parallelComputerBuilder.buildComputer(); final JUnitCore core = new JUnitCore(); final long t1 = systemMillis(); - final Result result = core.run( computer, TestSuite.class ); + final Result result = core.run(computer, TestSuite.class); final long t2 = systemMillis(); final long timeSpent = t2 - t1; - assertThat( computer.getSuites().size(), is( 1 ) ); - assertThat( computer.getClasses().size(), is( 0 ) ); - assertThat( computer.getNestedClasses().size(), is( 2 ) ); - assertThat( computer.getNestedSuites().size(), is( 0 ) ); - assertFalse( computer.isSplitPool() ); - assertThat( computer.getPoolCapacity(), is( 3 ) ); - assertTrue( result.wasSuccessful() ); - assertThat( Class1.maxConcurrentMethods, is( 1 ) ); - assertThat( timeSpent, between( 2000 * DELAY_MULTIPLIER - 50, 2250 * DELAY_MULTIPLIER ) ); + assertThat(computer.getSuites().size(), is(1)); + assertThat(computer.getClasses().size(), is(0)); + assertThat(computer.getNestedClasses().size(), is(2)); + assertThat(computer.getNestedSuites().size(), is(0)); + assertFalse(computer.isSplitPool()); + assertThat(computer.getPoolCapacity(), is(3)); + assertTrue(result.wasSuccessful()); + assertThat(Class1.maxConcurrentMethods, is(1)); + assertThat(timeSpent, between(2000 * DELAY_MULTIPLIER - 50, 2250 * DELAY_MULTIPLIER)); } @Test - public void separatePoolsWithSuite() - { - ParallelComputerBuilder parallelComputerBuilder = new ParallelComputerBuilder( LOGGER ); - parallelComputerBuilder.parallelSuites( 5 ); - parallelComputerBuilder.parallelClasses( 5 ); - parallelComputerBuilder.parallelMethods( 3 ); - assertFalse( parallelComputerBuilder.isOptimized() ); + public void separatePoolsWithSuite() { + ParallelComputerBuilder parallelComputerBuilder = new ParallelComputerBuilder(LOGGER); + parallelComputerBuilder.parallelSuites(5); + parallelComputerBuilder.parallelClasses(5); + parallelComputerBuilder.parallelMethods(3); + assertFalse(parallelComputerBuilder.isOptimized()); ParallelComputerBuilder.PC computer = (ParallelComputerBuilder.PC) parallelComputerBuilder.buildComputer(); final JUnitCore core = new JUnitCore(); final long t1 = systemMillis(); - final Result result = core.run( computer, TestSuite.class ); + final Result result = core.run(computer, TestSuite.class); final long t2 = systemMillis(); final long timeSpent = t2 - t1; - assertThat( computer.getSuites().size(), is( 1 ) ); - assertThat( computer.getClasses().size(), is( 0 ) ); - assertThat( computer.getNestedClasses().size(), is( 2 ) ); - assertThat( computer.getNestedSuites().size(), is( 0 ) ); - assertTrue( computer.isSplitPool() ); - assertThat( computer.getPoolCapacity(), is( ParallelComputerBuilder.TOTAL_POOL_SIZE_UNDEFINED ) ); - assertTrue( result.wasSuccessful() ); - assertThat( Class1.maxConcurrentMethods, is( 3 ) ); - assertThat( timeSpent, between( 1000 * DELAY_MULTIPLIER - 50, 1250 * DELAY_MULTIPLIER ) ); + assertThat(computer.getSuites().size(), is(1)); + assertThat(computer.getClasses().size(), is(0)); + assertThat(computer.getNestedClasses().size(), is(2)); + assertThat(computer.getNestedSuites().size(), is(0)); + assertTrue(computer.isSplitPool()); + assertThat(computer.getPoolCapacity(), is(ParallelComputerBuilder.TOTAL_POOL_SIZE_UNDEFINED)); + assertTrue(result.wasSuccessful()); + assertThat(Class1.maxConcurrentMethods, is(3)); + assertThat(timeSpent, between(1000 * DELAY_MULTIPLIER - 50, 1250 * DELAY_MULTIPLIER)); } @Test - public void separatePoolsWithSuiteAndClass() - { - ParallelComputerBuilder parallelComputerBuilder = new ParallelComputerBuilder( LOGGER ); - parallelComputerBuilder.parallelSuites( 5 ); - parallelComputerBuilder.parallelClasses( 5 ); - parallelComputerBuilder.parallelMethods( 3 ); - assertFalse( parallelComputerBuilder.isOptimized() ); + public void separatePoolsWithSuiteAndClass() { + ParallelComputerBuilder parallelComputerBuilder = new ParallelComputerBuilder(LOGGER); + parallelComputerBuilder.parallelSuites(5); + parallelComputerBuilder.parallelClasses(5); + parallelComputerBuilder.parallelMethods(3); + assertFalse(parallelComputerBuilder.isOptimized()); // 6 methods altogether. // 2 groups with 3 threads. @@ -308,361 +311,358 @@ public void separatePoolsWithSuiteAndClass() ParallelComputerBuilder.PC computer = (ParallelComputerBuilder.PC) parallelComputerBuilder.buildComputer(); final JUnitCore core = new JUnitCore(); final long t1 = systemMillis(); - final Result result = core.run( computer, TestSuite.class, Class1.class ); + final Result result = core.run(computer, TestSuite.class, Class1.class); final long t2 = systemMillis(); final long timeSpent = t2 - t1; - assertThat( computer.getSuites().size(), is( 1 ) ); - assertThat( computer.getClasses().size(), is( 1 ) ); - assertThat( computer.getNestedClasses().size(), is( 2 ) ); - assertThat( computer.getNestedSuites().size(), is( 0 ) ); - assertTrue( computer.isSplitPool() ); - assertThat( computer.getPoolCapacity(), is( ParallelComputerBuilder.TOTAL_POOL_SIZE_UNDEFINED ) ); - assertTrue( result.wasSuccessful() ); - assertThat( Class1.maxConcurrentMethods, is( 3 ) ); - assertThat( timeSpent, between( 1000 * DELAY_MULTIPLIER - 50, 1250 * DELAY_MULTIPLIER ) ); + assertThat(computer.getSuites().size(), is(1)); + assertThat(computer.getClasses().size(), is(1)); + assertThat(computer.getNestedClasses().size(), is(2)); + assertThat(computer.getNestedSuites().size(), is(0)); + assertTrue(computer.isSplitPool()); + assertThat(computer.getPoolCapacity(), is(ParallelComputerBuilder.TOTAL_POOL_SIZE_UNDEFINED)); + assertTrue(result.wasSuccessful()); + assertThat(Class1.maxConcurrentMethods, is(3)); + assertThat(timeSpent, between(1000 * DELAY_MULTIPLIER - 50, 1250 * DELAY_MULTIPLIER)); } @Test - public void separatePoolsWithSuiteAndSequentialClasses() - { - ParallelComputerBuilder parallelComputerBuilder = new ParallelComputerBuilder( LOGGER ); - parallelComputerBuilder.parallelSuites( 5 ); - parallelComputerBuilder.parallelClasses( 1 ); - parallelComputerBuilder.parallelMethods( 3 ); - assertFalse( parallelComputerBuilder.isOptimized() ); + public void separatePoolsWithSuiteAndSequentialClasses() { + ParallelComputerBuilder parallelComputerBuilder = new ParallelComputerBuilder(LOGGER); + parallelComputerBuilder.parallelSuites(5); + parallelComputerBuilder.parallelClasses(1); + parallelComputerBuilder.parallelMethods(3); + assertFalse(parallelComputerBuilder.isOptimized()); ParallelComputerBuilder.PC computer = (ParallelComputerBuilder.PC) parallelComputerBuilder.buildComputer(); final JUnitCore core = new JUnitCore(); final long t1 = systemMillis(); - final Result result = core.run( computer, TestSuite.class, Class1.class ); + final Result result = core.run(computer, TestSuite.class, Class1.class); final long t2 = systemMillis(); final long timeSpent = t2 - t1; - assertThat( computer.getSuites().size(), is( 1 ) ); - assertThat( computer.getClasses().size(), is( 1 ) ); - assertThat( computer.getNestedClasses().size(), is( 2 ) ); - assertThat( computer.getNestedSuites().size(), is( 0 ) ); - assertTrue( computer.isSplitPool() ); - assertThat( computer.getPoolCapacity(), is( ParallelComputerBuilder.TOTAL_POOL_SIZE_UNDEFINED ) ); - assertTrue( result.wasSuccessful() ); - assertThat( Class1.maxConcurrentMethods, is( 2 ) ); - assertThat( timeSpent, between( 1500 * DELAY_MULTIPLIER - 50, 1750 * DELAY_MULTIPLIER ) ); + assertThat(computer.getSuites().size(), is(1)); + assertThat(computer.getClasses().size(), is(1)); + assertThat(computer.getNestedClasses().size(), is(2)); + assertThat(computer.getNestedSuites().size(), is(0)); + assertTrue(computer.isSplitPool()); + assertThat(computer.getPoolCapacity(), is(ParallelComputerBuilder.TOTAL_POOL_SIZE_UNDEFINED)); + assertTrue(result.wasSuccessful()); + assertThat(Class1.maxConcurrentMethods, is(2)); + assertThat(timeSpent, between(1500 * DELAY_MULTIPLIER - 50, 1750 * DELAY_MULTIPLIER)); } - @Test( timeout = 2000 * DELAY_MULTIPLIER ) - public void shutdown() - { + @Test(timeout = 2000 * DELAY_MULTIPLIER) + public void shutdown() { final long t1 = systemMillis(); - final Result result = new ShutdownTest().run( false ); + final Result result = new ShutdownTest().run(false); final long t2 = systemMillis(); final long timeSpent = t2 - t1; - assertTrue( result.wasSuccessful() ); - assertTrue( beforeShutdown ); - assertThat( timeSpent, between( 500 * DELAY_MULTIPLIER - 50, 1250 * DELAY_MULTIPLIER ) ); + assertTrue(result.wasSuccessful()); + assertTrue(beforeShutdown); + assertThat(timeSpent, between(500 * DELAY_MULTIPLIER - 50, 1250 * DELAY_MULTIPLIER)); } - @Test( timeout = 2000 * DELAY_MULTIPLIER ) - public void shutdownWithInterrupt() - { + @Test(timeout = 2000 * DELAY_MULTIPLIER) + public void shutdownWithInterrupt() { final long t1 = systemMillis(); - new ShutdownTest().run( true ); + new ShutdownTest().run(true); final long t2 = systemMillis(); final long timeSpent = t2 - t1; - assertTrue( beforeShutdown ); - assertThat( timeSpent, between( 500 * DELAY_MULTIPLIER - 50, 1250 * DELAY_MULTIPLIER ) ); + assertTrue(beforeShutdown); + assertThat(timeSpent, between(500 * DELAY_MULTIPLIER - 50, 1250 * DELAY_MULTIPLIER)); } @Test - public void nothingParallel() - { + public void nothingParallel() { JUnitCore core = new JUnitCore(); - ParallelComputerBuilder builder = new ParallelComputerBuilder( LOGGER ); - assertFalse( builder.isOptimized() ); + ParallelComputerBuilder builder = new ParallelComputerBuilder(LOGGER); + assertFalse(builder.isOptimized()); - Result result = core.run( builder.buildComputer(), NothingDoingTest1.class, NothingDoingTest2.class ); - assertTrue( result.wasSuccessful() ); + Result result = core.run(builder.buildComputer(), NothingDoingTest1.class, NothingDoingTest2.class); + assertTrue(result.wasSuccessful()); - result = core.run( builder.buildComputer(), NothingDoingTest1.class, NothingDoingSuite.class ); - assertTrue( result.wasSuccessful() ); + result = core.run(builder.buildComputer(), NothingDoingTest1.class, NothingDoingSuite.class); + assertTrue(result.wasSuccessful()); - builder.useOnePool( 1 ); - assertFalse( builder.isOptimized() ); - result = core.run( builder.buildComputer(), NothingDoingTest1.class, NothingDoingTest2.class ); - assertTrue( result.wasSuccessful() ); + builder.useOnePool(1); + assertFalse(builder.isOptimized()); + result = core.run(builder.buildComputer(), NothingDoingTest1.class, NothingDoingTest2.class); + assertTrue(result.wasSuccessful()); - builder.useOnePool( 1 ); - assertFalse( builder.isOptimized() ); - result = core.run( builder.buildComputer(), NothingDoingTest1.class, NothingDoingSuite.class ); - assertTrue( result.wasSuccessful() ); + builder.useOnePool(1); + assertFalse(builder.isOptimized()); + result = core.run(builder.buildComputer(), NothingDoingTest1.class, NothingDoingSuite.class); + assertTrue(result.wasSuccessful()); - builder.useOnePool( 2 ); - assertFalse( builder.isOptimized() ); - result = core.run( builder.buildComputer(), NothingDoingTest1.class, NothingDoingSuite.class ); - assertTrue( result.wasSuccessful() ); + builder.useOnePool(2); + assertFalse(builder.isOptimized()); + result = core.run(builder.buildComputer(), NothingDoingTest1.class, NothingDoingSuite.class); + assertTrue(result.wasSuccessful()); Class[] classes = {NothingDoingTest1.class, NothingDoingSuite.class}; - builder.useOnePool( 2 ).parallelSuites( 1 ).parallelClasses( 1 ); - assertFalse( builder.isOptimized() ); - result = core.run( builder.buildComputer(), classes ); - assertTrue( result.wasSuccessful() ); + builder.useOnePool(2).parallelSuites(1).parallelClasses(1); + assertFalse(builder.isOptimized()); + result = core.run(builder.buildComputer(), classes); + assertTrue(result.wasSuccessful()); - builder.useOnePool( 2 ).parallelSuites( 1 ).parallelClasses(); - assertFalse( builder.isOptimized() ); - result = core.run( builder.buildComputer(), classes ); - assertTrue( result.wasSuccessful() ); + builder.useOnePool(2).parallelSuites(1).parallelClasses(); + assertFalse(builder.isOptimized()); + result = core.run(builder.buildComputer(), classes); + assertTrue(result.wasSuccessful()); - classes = new Class[] { NothingDoingSuite.class, NothingDoingSuite.class, NothingDoingTest1.class, - NothingDoingTest2.class, NothingDoingTest3.class }; + classes = new Class[] { + NothingDoingSuite.class, + NothingDoingSuite.class, + NothingDoingTest1.class, + NothingDoingTest2.class, + NothingDoingTest3.class + }; - builder.useOnePool( 2 ).parallelSuites( 1 ).parallelClasses( 1 ); - assertFalse( builder.isOptimized() ); - result = core.run( builder.buildComputer(), classes ); - assertTrue( result.wasSuccessful() ); + builder.useOnePool(2).parallelSuites(1).parallelClasses(1); + assertFalse(builder.isOptimized()); + result = core.run(builder.buildComputer(), classes); + assertTrue(result.wasSuccessful()); - builder.useOnePool( 2 ).parallelSuites( 1 ).parallelClasses(); - assertFalse( builder.isOptimized() ); - result = core.run( builder.buildComputer(), classes ); - assertTrue( result.wasSuccessful() ); + builder.useOnePool(2).parallelSuites(1).parallelClasses(); + assertFalse(builder.isOptimized()); + result = core.run(builder.buildComputer(), classes); + assertTrue(result.wasSuccessful()); } @Test - public void keepBeforeAfterOneClass() - { - ParallelComputerBuilder builder = new ParallelComputerBuilder( LOGGER ); + public void keepBeforeAfterOneClass() { + ParallelComputerBuilder builder = new ParallelComputerBuilder(LOGGER); builder.parallelMethods(); - assertFalse( builder.isOptimized() ); - testKeepBeforeAfter( builder, NothingDoingTest1.class ); + assertFalse(builder.isOptimized()); + testKeepBeforeAfter(builder, NothingDoingTest1.class); } @Test - public void keepBeforeAfterTwoClasses() - { - ParallelComputerBuilder builder = new ParallelComputerBuilder( LOGGER ); - builder.useOnePool( 5 ).parallelClasses( 1 ).parallelMethods( 2 ); - assertFalse( builder.isOptimized() ); - testKeepBeforeAfter( builder, NothingDoingTest1.class, NothingDoingTest2.class ); + public void keepBeforeAfterTwoClasses() { + ParallelComputerBuilder builder = new ParallelComputerBuilder(LOGGER); + builder.useOnePool(5).parallelClasses(1).parallelMethods(2); + assertFalse(builder.isOptimized()); + testKeepBeforeAfter(builder, NothingDoingTest1.class, NothingDoingTest2.class); } @Test - public void keepBeforeAfterTwoParallelClasses() - { - ParallelComputerBuilder builder = new ParallelComputerBuilder( LOGGER ); - builder.useOnePool( 8 ).parallelClasses( 2 ).parallelMethods( 2 ); - assertFalse( builder.isOptimized() ); + public void keepBeforeAfterTwoParallelClasses() { + ParallelComputerBuilder builder = new ParallelComputerBuilder(LOGGER); + builder.useOnePool(8).parallelClasses(2).parallelMethods(2); + assertFalse(builder.isOptimized()); JUnitCore core = new JUnitCore(); NothingDoingTest1.METHODS.clear(); Class[] classes = {NothingDoingTest1.class, NothingDoingTest2.class, NothingDoingTest3.class}; - Result result = core.run( builder.buildComputer(), classes ); - assertTrue( result.wasSuccessful() ); - ArrayList methods = new ArrayList<>( NothingDoingTest1.METHODS ); - assertThat( methods.size(), is( 12 ) ); - assertThat( methods.subList( 9, 12 ), is( not( Arrays.asList( "deinit", "deinit", "deinit" ) ) ) ); + Result result = core.run(builder.buildComputer(), classes); + assertTrue(result.wasSuccessful()); + ArrayList methods = new ArrayList<>(NothingDoingTest1.METHODS); + assertThat(methods.size(), is(12)); + assertThat(methods.subList(9, 12), is(not(Arrays.asList("deinit", "deinit", "deinit")))); } @Test - public void notThreadSafeTest() - { - ParallelComputerBuilder builder = new ParallelComputerBuilder( LOGGER ).useOnePool( 6 ).optimize( - true ).parallelClasses( 3 ).parallelMethods( 3 ); + public void notThreadSafeTest() { + ParallelComputerBuilder builder = new ParallelComputerBuilder(LOGGER) + .useOnePool(6) + .optimize(true) + .parallelClasses(3) + .parallelMethods(3); ParallelComputerBuilder.PC computer = (ParallelComputerBuilder.PC) builder.buildComputer(); - Result result = new JUnitCore().run( computer, NotThreadSafeTest1.class, NotThreadSafeTest2.class ); - assertTrue( result.wasSuccessful() ); - assertThat( result.getRunCount(), is( 2 ) ); - assertNotNull( NotThreadSafeTest1.t ); - assertNotNull( NotThreadSafeTest2.t ); - assertSame( NotThreadSafeTest1.t, NotThreadSafeTest2.t ); - assertThat( computer.getNotParallelRunners().size(), is( 2 ) ); - assertTrue( computer.getSuites().isEmpty() ); - assertTrue( computer.getClasses().isEmpty() ); - assertTrue( computer.getNestedClasses().isEmpty() ); - assertTrue( computer.getNestedSuites().isEmpty() ); - assertFalse( computer.isSplitPool() ); - assertThat( computer.getPoolCapacity(), is( 6 ) ); + Result result = new JUnitCore().run(computer, NotThreadSafeTest1.class, NotThreadSafeTest2.class); + assertTrue(result.wasSuccessful()); + assertThat(result.getRunCount(), is(2)); + assertNotNull(NotThreadSafeTest1.t); + assertNotNull(NotThreadSafeTest2.t); + assertSame(NotThreadSafeTest1.t, NotThreadSafeTest2.t); + assertThat(computer.getNotParallelRunners().size(), is(2)); + assertTrue(computer.getSuites().isEmpty()); + assertTrue(computer.getClasses().isEmpty()); + assertTrue(computer.getNestedClasses().isEmpty()); + assertTrue(computer.getNestedSuites().isEmpty()); + assertFalse(computer.isSplitPool()); + assertThat(computer.getPoolCapacity(), is(6)); } @Test - public void mixedThreadSafety() - { - ParallelComputerBuilder builder = new ParallelComputerBuilder( LOGGER ).useOnePool( 6 ).optimize( - true ).parallelClasses( 3 ).parallelMethods( 3 ); + public void mixedThreadSafety() { + ParallelComputerBuilder builder = new ParallelComputerBuilder(LOGGER) + .useOnePool(6) + .optimize(true) + .parallelClasses(3) + .parallelMethods(3); ParallelComputerBuilder.PC computer = (ParallelComputerBuilder.PC) builder.buildComputer(); - Result result = new JUnitCore().run( computer, NotThreadSafeTest1.class, NormalTest1.class ); - assertTrue( result.wasSuccessful() ); - assertThat( result.getRunCount(), is( 2 ) ); - assertNotNull( NotThreadSafeTest1.t ); - assertNotNull( NormalTest1.t ); - assertThat( NormalTest1.t.getName(), is( not( "maven-surefire-plugin@NotThreadSafe" ) ) ); - assertNotSame( NotThreadSafeTest1.t, NormalTest1.t ); - assertThat( computer.getNotParallelRunners().size(), is( 1 ) ); - assertTrue( computer.getSuites().isEmpty() ); - assertThat( computer.getClasses().size(), is( 1 ) ); - assertTrue( computer.getNestedClasses().isEmpty() ); - assertTrue( computer.getNestedSuites().isEmpty() ); - assertFalse( computer.isSplitPool() ); - assertThat( computer.getPoolCapacity(), is( 6 ) ); + Result result = new JUnitCore().run(computer, NotThreadSafeTest1.class, NormalTest1.class); + assertTrue(result.wasSuccessful()); + assertThat(result.getRunCount(), is(2)); + assertNotNull(NotThreadSafeTest1.t); + assertNotNull(NormalTest1.t); + assertThat(NormalTest1.t.getName(), is(not("maven-surefire-plugin@NotThreadSafe"))); + assertNotSame(NotThreadSafeTest1.t, NormalTest1.t); + assertThat(computer.getNotParallelRunners().size(), is(1)); + assertTrue(computer.getSuites().isEmpty()); + assertThat(computer.getClasses().size(), is(1)); + assertTrue(computer.getNestedClasses().isEmpty()); + assertTrue(computer.getNestedSuites().isEmpty()); + assertFalse(computer.isSplitPool()); + assertThat(computer.getPoolCapacity(), is(6)); } @Test - public void notThreadSafeTestsInSuite() - { - ParallelComputerBuilder builder = new ParallelComputerBuilder( LOGGER ).useOnePool( 5 ).parallelMethods( 3 ); - assertFalse( builder.isOptimized() ); + public void notThreadSafeTestsInSuite() { + ParallelComputerBuilder builder = + new ParallelComputerBuilder(LOGGER).useOnePool(5).parallelMethods(3); + assertFalse(builder.isOptimized()); ParallelComputerBuilder.PC computer = (ParallelComputerBuilder.PC) builder.buildComputer(); - Result result = new JUnitCore().run( computer, NotThreadSafeTestSuite.class ); - assertTrue( result.wasSuccessful() ); - assertNotNull( NormalTest1.t ); - assertNotNull( NormalTest2.t ); - assertSame( NormalTest1.t, NormalTest2.t ); - assertThat( NormalTest1.t.getName(), is( "maven-surefire-plugin@NotThreadSafe" ) ); - assertThat( NormalTest2.t.getName(), is( "maven-surefire-plugin@NotThreadSafe" ) ); - assertThat( computer.getNotParallelRunners().size(), is( 1 ) ); - assertTrue( computer.getSuites().isEmpty() ); - assertTrue( computer.getClasses().isEmpty() ); - assertTrue( computer.getNestedClasses().isEmpty() ); - assertTrue( computer.getNestedSuites().isEmpty() ); - assertFalse( computer.isSplitPool() ); - assertThat( computer.getPoolCapacity(), is( 5 ) ); + Result result = new JUnitCore().run(computer, NotThreadSafeTestSuite.class); + assertTrue(result.wasSuccessful()); + assertNotNull(NormalTest1.t); + assertNotNull(NormalTest2.t); + assertSame(NormalTest1.t, NormalTest2.t); + assertThat(NormalTest1.t.getName(), is("maven-surefire-plugin@NotThreadSafe")); + assertThat(NormalTest2.t.getName(), is("maven-surefire-plugin@NotThreadSafe")); + assertThat(computer.getNotParallelRunners().size(), is(1)); + assertTrue(computer.getSuites().isEmpty()); + assertTrue(computer.getClasses().isEmpty()); + assertTrue(computer.getNestedClasses().isEmpty()); + assertTrue(computer.getNestedSuites().isEmpty()); + assertFalse(computer.isSplitPool()); + assertThat(computer.getPoolCapacity(), is(5)); } @Test - public void mixedThreadSafetyInSuite() - { - ParallelComputerBuilder builder = new ParallelComputerBuilder( LOGGER ).useOnePool( 10 ).optimize( - true ).parallelSuites( 2 ).parallelClasses( 3 ).parallelMethods( 3 ); + public void mixedThreadSafetyInSuite() { + ParallelComputerBuilder builder = new ParallelComputerBuilder(LOGGER) + .useOnePool(10) + .optimize(true) + .parallelSuites(2) + .parallelClasses(3) + .parallelMethods(3); ParallelComputerBuilder.PC computer = (ParallelComputerBuilder.PC) builder.buildComputer(); - Result result = new JUnitCore().run( computer, MixedSuite.class ); - assertTrue( result.wasSuccessful() ); - assertThat( result.getRunCount(), is( 2 ) ); - assertNotNull( NotThreadSafeTest1.t ); - assertNotNull( NormalTest1.t ); - assertThat( NormalTest1.t.getName(), is( not( "maven-surefire-plugin@NotThreadSafe" ) ) ); - assertNotSame( NotThreadSafeTest1.t, NormalTest1.t ); - assertTrue( computer.getNotParallelRunners().isEmpty() ); - assertThat( computer.getSuites().size(), is( 1 ) ); - assertTrue( computer.getClasses().isEmpty() ); - assertThat( computer.getNestedClasses().size(), is( 1 ) ); - assertTrue( computer.getNestedSuites().isEmpty() ); - assertFalse( computer.isSplitPool() ); - assertThat( computer.getPoolCapacity(), is( 10 ) ); + Result result = new JUnitCore().run(computer, MixedSuite.class); + assertTrue(result.wasSuccessful()); + assertThat(result.getRunCount(), is(2)); + assertNotNull(NotThreadSafeTest1.t); + assertNotNull(NormalTest1.t); + assertThat(NormalTest1.t.getName(), is(not("maven-surefire-plugin@NotThreadSafe"))); + assertNotSame(NotThreadSafeTest1.t, NormalTest1.t); + assertTrue(computer.getNotParallelRunners().isEmpty()); + assertThat(computer.getSuites().size(), is(1)); + assertTrue(computer.getClasses().isEmpty()); + assertThat(computer.getNestedClasses().size(), is(1)); + assertTrue(computer.getNestedSuites().isEmpty()); + assertFalse(computer.isSplitPool()); + assertThat(computer.getPoolCapacity(), is(10)); } @Test - public void inheritanceWithNotThreadSafe() - { - ParallelComputerBuilder builder = new ParallelComputerBuilder( LOGGER ).useOnePool( 10 ).optimize( - true ).parallelSuites( 2 ).parallelClasses( 3 ).parallelMethods( 3 ); + public void inheritanceWithNotThreadSafe() { + ParallelComputerBuilder builder = new ParallelComputerBuilder(LOGGER) + .useOnePool(10) + .optimize(true) + .parallelSuites(2) + .parallelClasses(3) + .parallelMethods(3); ParallelComputerBuilder.PC computer = (ParallelComputerBuilder.PC) builder.buildComputer(); - Result result = new JUnitCore().run( computer, OverMixedSuite.class ); - assertTrue( result.wasSuccessful() ); - assertThat( result.getRunCount(), is( 2 ) ); - assertNotNull( NotThreadSafeTest3.t ); - assertNotNull( NormalTest1.t ); - assertThat( NormalTest1.t.getName(), is( "maven-surefire-plugin@NotThreadSafe" ) ); - assertSame( NotThreadSafeTest3.t, NormalTest1.t ); - assertThat( computer.getNotParallelRunners().size(), is( 1 ) ); - assertTrue( computer.getSuites().isEmpty() ); - assertTrue( computer.getClasses().isEmpty() ); - assertTrue( computer.getNestedClasses().isEmpty() ); - assertTrue( computer.getNestedSuites().isEmpty() ); - assertFalse( computer.isSplitPool() ); - assertThat( computer.getPoolCapacity(), is( 10 ) ); + Result result = new JUnitCore().run(computer, OverMixedSuite.class); + assertTrue(result.wasSuccessful()); + assertThat(result.getRunCount(), is(2)); + assertNotNull(NotThreadSafeTest3.t); + assertNotNull(NormalTest1.t); + assertThat(NormalTest1.t.getName(), is("maven-surefire-plugin@NotThreadSafe")); + assertSame(NotThreadSafeTest3.t, NormalTest1.t); + assertThat(computer.getNotParallelRunners().size(), is(1)); + assertTrue(computer.getSuites().isEmpty()); + assertTrue(computer.getClasses().isEmpty()); + assertTrue(computer.getNestedClasses().isEmpty()); + assertTrue(computer.getNestedSuites().isEmpty()); + assertFalse(computer.isSplitPool()); + assertThat(computer.getPoolCapacity(), is(10)); } @Test - public void beforeAfterThreadChanges() throws InterruptedException - { + public void beforeAfterThreadChanges() throws InterruptedException { // try to GC dead Thread objects from previous tests - for ( int i = 0; i < 5; i++ ) - { + for (int i = 0; i < 5; i++) { System.gc(); - TimeUnit.MILLISECONDS.sleep( 500L ); + TimeUnit.MILLISECONDS.sleep(500L); } Collection expectedThreads = jvmThreads(); - ParallelComputerBuilder parallelComputerBuilder = new ParallelComputerBuilder( LOGGER ); - parallelComputerBuilder.parallelMethods( 3 ); + ParallelComputerBuilder parallelComputerBuilder = new ParallelComputerBuilder(LOGGER); + parallelComputerBuilder.parallelMethods(3); ParallelComputer computer = parallelComputerBuilder.buildComputer(); - Result result = new JUnitCore().run( computer, TestWithBeforeAfter.class ); - assertTrue( result.wasSuccessful() ); + Result result = new JUnitCore().run(computer, TestWithBeforeAfter.class); + assertTrue(result.wasSuccessful()); // try to GC dead Thread objects - for ( int i = 0; i < 5 && expectedThreads.size() != jvmThreads().size(); i++ ) - { + for (int i = 0; i < 5 && expectedThreads.size() != jvmThreads().size(); i++) { System.gc(); - TimeUnit.MILLISECONDS.sleep( 500L ); + TimeUnit.MILLISECONDS.sleep(500L); } - assertThat( jvmThreads(), is( expectedThreads ) ); + assertThat(jvmThreads(), is(expectedThreads)); } - private static Collection jvmThreads() - { + private static Collection jvmThreads() { Thread[] t = new Thread[1000]; - Thread.enumerate( t ); - ArrayList appThreads = new ArrayList<>( t.length ); - Collections.addAll( appThreads, t ); - appThreads.removeAll( Collections.singleton( (Thread) null ) ); - Collections.sort( appThreads, new Comparator() - { + Thread.enumerate(t); + ArrayList appThreads = new ArrayList<>(t.length); + Collections.addAll(appThreads, t); + appThreads.removeAll(Collections.singleton((Thread) null)); + Collections.sort(appThreads, new Comparator() { @Override - public int compare( Thread t1, Thread t2 ) - { - return (int) Math.signum( t1.getId() - t2.getId() ); + public int compare(Thread t1, Thread t2) { + return (int) Math.signum(t1.getId() - t2.getId()); } - } ); + }); return appThreads; } - private static class ShutdownTest - { - Result run( final boolean useInterrupt ) - { - ParallelComputerBuilder parallelComputerBuilder = new ParallelComputerBuilder( LOGGER ).useOnePool( - 8 ).parallelSuites( 2 ).parallelClasses( 3 ).parallelMethods( 3 ); + private static class ShutdownTest { + Result run(final boolean useInterrupt) { + ParallelComputerBuilder parallelComputerBuilder = new ParallelComputerBuilder(LOGGER) + .useOnePool(8) + .parallelSuites(2) + .parallelClasses(3) + .parallelMethods(3); - assertFalse( parallelComputerBuilder.isOptimized() ); + assertFalse(parallelComputerBuilder.isOptimized()); final ParallelComputerBuilder.PC computer = (ParallelComputerBuilder.PC) parallelComputerBuilder.buildComputer(); - shutdownTask = new Runnable() - { + shutdownTask = new Runnable() { @Override - public void run() - { - Collection startedTests = computer.describeStopped( useInterrupt ).getTriggeredTests(); - assertThat( startedTests.size(), is( not( 0 ) ) ); + public void run() { + Collection startedTests = + computer.describeStopped(useInterrupt).getTriggeredTests(); + assertThat(startedTests.size(), is(not(0))); } }; - return new JUnitCore().run( computer, TestSuite.class, Class2.class, Class3.class ); + return new JUnitCore().run(computer, TestSuite.class, Class2.class, Class3.class); } } /** * */ - public static class Class1 - { + public static class Class1 { static volatile int concurrentMethods = 0; static volatile int maxConcurrentMethods = 0; @Test - public void test1() throws InterruptedException - { - synchronized ( CLASS1BLOCK ) - { + public void test1() throws InterruptedException { + synchronized (CLASS1BLOCK) { ++concurrentMethods; - CLASS1BLOCK.wait( DELAY_MULTIPLIER * 500L ); - maxConcurrentMethods = Math.max( maxConcurrentMethods, concurrentMethods-- ); + CLASS1BLOCK.wait(DELAY_MULTIPLIER * 500L); + maxConcurrentMethods = Math.max(maxConcurrentMethods, concurrentMethods--); } } @Test - public void test2() throws InterruptedException - { + public void test2() throws InterruptedException { test1(); Runnable shutdownTask = ParallelComputerBuilderTest.shutdownTask; - if ( shutdownTask != null ) - { + if (shutdownTask != null) { beforeShutdown = true; shutdownTask.run(); } @@ -672,146 +672,116 @@ public void test2() throws InterruptedException /** * */ - public static class Class2 extends Class1 - { - } + public static class Class2 extends Class1 {} /** * */ - public static class Class3 extends Class1 - { - } + public static class Class3 extends Class1 {} /** * */ - public static class NothingDoingTest1 - { + public static class NothingDoingTest1 { private static final Collection METHODS = new ConcurrentLinkedQueue<>(); @BeforeClass - public static void init() - { - METHODS.add( "init" ); + public static void init() { + METHODS.add("init"); } @AfterClass - public static void deinit() - { - METHODS.add( "deinit" ); + public static void deinit() { + METHODS.add("deinit"); } @Test - public void a() throws InterruptedException - { - Thread.sleep( 5 ); - METHODS.add( getClass().getName() + "#a()" ); + public void a() throws InterruptedException { + Thread.sleep(5); + METHODS.add(getClass().getName() + "#a()"); } @Test - public void b() throws InterruptedException - { - Thread.sleep( 5 ); - METHODS.add( getClass().getName() + "#b()" ); + public void b() throws InterruptedException { + Thread.sleep(5); + METHODS.add(getClass().getName() + "#b()"); } } /** * */ - public static class NothingDoingTest2 extends NothingDoingTest1 - { - } + public static class NothingDoingTest2 extends NothingDoingTest1 {} /** * */ - public static class NothingDoingTest3 extends NothingDoingTest1 - { - } + public static class NothingDoingTest3 extends NothingDoingTest1 {} /** * */ - @RunWith( Suite.class ) - @Suite.SuiteClasses( {NothingDoingTest1.class, NothingDoingTest2.class} ) - public static class NothingDoingSuite - { - } + @RunWith(Suite.class) + @Suite.SuiteClasses({NothingDoingTest1.class, NothingDoingTest2.class}) + public static class NothingDoingSuite {} /** * */ - @RunWith( Suite.class ) - @Suite.SuiteClasses( {Class2.class, Class1.class} ) - public static class TestSuite - { - } + @RunWith(Suite.class) + @Suite.SuiteClasses({Class2.class, Class1.class}) + public static class TestSuite {} /** * */ - public static class Test2 - { + public static class Test2 { @Test - public void test() - { - - } + public void test() {} } /** * */ - @RunWith( ReportOneTestAtRuntimeRunner.class ) - public static class TestWithoutPrecalculatedChildren - { - } + @RunWith(ReportOneTestAtRuntimeRunner.class) + public static class TestWithoutPrecalculatedChildren {} /** * */ - public static class ReportOneTestAtRuntimeRunner extends ParentRunner - { + public static class ReportOneTestAtRuntimeRunner extends ParentRunner { private final Class testClass; private final Description suiteDescription; private final Description myTestMethodDescr; - @SuppressWarnings( "unchecked" ) - public ReportOneTestAtRuntimeRunner( Class testClass ) throws InitializationError - { - super( Object.class ); + @SuppressWarnings("unchecked") + public ReportOneTestAtRuntimeRunner(Class testClass) throws InitializationError { + super(Object.class); this.testClass = testClass; - suiteDescription = Description.createSuiteDescription( testClass ); - myTestMethodDescr = Description.createTestDescription( testClass, "my_test" ); + suiteDescription = Description.createSuiteDescription(testClass); + myTestMethodDescr = Description.createTestDescription(testClass, "my_test"); // suiteDescription.addChild(myTestMethodDescr); // let it be not known at start time } - protected List getChildren() - { - throw new UnsupportedOperationException( "workflow from ParentRunner not supported" ); + protected List getChildren() { + throw new UnsupportedOperationException("workflow from ParentRunner not supported"); } - protected Description describeChild( Object child ) - { - throw new UnsupportedOperationException( "workflow from ParentRunner not supported" ); + protected Description describeChild(Object child) { + throw new UnsupportedOperationException("workflow from ParentRunner not supported"); } - protected void runChild( Object child, RunNotifier notifier ) - { - throw new UnsupportedOperationException( "workflow from ParentRunner not supported" ); + protected void runChild(Object child, RunNotifier notifier) { + throw new UnsupportedOperationException("workflow from ParentRunner not supported"); } - public Description getDescription() - { + public Description getDescription() { return suiteDescription; } - public void run( RunNotifier notifier ) - { - notifier.fireTestStarted( myTestMethodDescr ); - notifier.fireTestFinished( Description.createTestDescription( testClass, "my_test" ) ); + public void run(RunNotifier notifier) { + notifier.fireTestStarted(myTestMethodDescr); + notifier.fireTestFinished(Description.createTestDescription(testClass, "my_test")); } } @@ -819,27 +789,23 @@ public void run( RunNotifier notifier ) * */ @NotThreadSafe - public static class NotThreadSafeTest1 - { + public static class NotThreadSafeTest1 { static volatile Thread t; @BeforeClass - public static void beforeSuite() - { - assertThat( Thread.currentThread().getName(), is( not( "maven-surefire-plugin@NotThreadSafe" ) ) ); + public static void beforeSuite() { + assertThat(Thread.currentThread().getName(), is(not("maven-surefire-plugin@NotThreadSafe"))); } @AfterClass - public static void afterSuite() - { - assertThat( Thread.currentThread().getName(), is( not( "maven-surefire-plugin@NotThreadSafe" ) ) ); + public static void afterSuite() { + assertThat(Thread.currentThread().getName(), is(not("maven-surefire-plugin@NotThreadSafe"))); } @Test - public void test() - { + public void test() { t = Thread.currentThread(); - assertThat( t.getName(), is( "maven-surefire-plugin@NotThreadSafe" ) ); + assertThat(t.getName(), is("maven-surefire-plugin@NotThreadSafe")); } } @@ -847,27 +813,23 @@ public void test() * */ @NotThreadSafe - public static class NotThreadSafeTest2 - { + public static class NotThreadSafeTest2 { static volatile Thread t; @BeforeClass - public static void beforeSuite() - { - assertThat( Thread.currentThread().getName(), is( not( "maven-surefire-plugin@NotThreadSafe" ) ) ); + public static void beforeSuite() { + assertThat(Thread.currentThread().getName(), is(not("maven-surefire-plugin@NotThreadSafe"))); } @AfterClass - public static void afterSuite() - { - assertThat( Thread.currentThread().getName(), is( not( "maven-surefire-plugin@NotThreadSafe" ) ) ); + public static void afterSuite() { + assertThat(Thread.currentThread().getName(), is(not("maven-surefire-plugin@NotThreadSafe"))); } @Test - public void test() - { + public void test() { t = Thread.currentThread(); - assertThat( t.getName(), is( "maven-surefire-plugin@NotThreadSafe" ) ); + assertThat(t.getName(), is("maven-surefire-plugin@NotThreadSafe")); } } @@ -875,49 +837,42 @@ public void test() * */ @NotThreadSafe - public static class NotThreadSafeTest3 - { + public static class NotThreadSafeTest3 { static volatile Thread t; @Test - public void test() - { + public void test() { t = Thread.currentThread(); - assertThat( t.getName(), is( "maven-surefire-plugin@NotThreadSafe" ) ); + assertThat(t.getName(), is("maven-surefire-plugin@NotThreadSafe")); } } /** * */ - @RunWith( Suite.class ) - @Suite.SuiteClasses( {NormalTest1.class, NormalTest2.class} ) + @RunWith(Suite.class) + @Suite.SuiteClasses({NormalTest1.class, NormalTest2.class}) @NotThreadSafe - public static class NotThreadSafeTestSuite - { + public static class NotThreadSafeTestSuite { @BeforeClass - public static void beforeSuite() - { - assertThat( Thread.currentThread().getName(), is( not( "maven-surefire-plugin@NotThreadSafe" ) ) ); + public static void beforeSuite() { + assertThat(Thread.currentThread().getName(), is(not("maven-surefire-plugin@NotThreadSafe"))); } @AfterClass - public static void afterSuite() - { - assertThat( Thread.currentThread().getName(), is( not( "maven-surefire-plugin@NotThreadSafe" ) ) ); + public static void afterSuite() { + assertThat(Thread.currentThread().getName(), is(not("maven-surefire-plugin@NotThreadSafe"))); } } /** * */ - public static class NormalTest1 - { + public static class NormalTest1 { static volatile Thread t; @Test - public void test() - { + public void test() { t = Thread.currentThread(); } } @@ -925,13 +880,11 @@ public void test() /** * */ - public static class NormalTest2 - { + public static class NormalTest2 { static volatile Thread t; @Test - public void test() - { + public void test() { t = Thread.currentThread(); } } @@ -939,97 +892,83 @@ public void test() /** * */ - @RunWith( Suite.class ) - @Suite.SuiteClasses( {NotThreadSafeTest1.class, NormalTest1.class} ) - public static class MixedSuite - { + @RunWith(Suite.class) + @Suite.SuiteClasses({NotThreadSafeTest1.class, NormalTest1.class}) + public static class MixedSuite { @BeforeClass - public static void beforeSuite() - { - assertThat( Thread.currentThread().getName(), is( not( "maven-surefire-plugin@NotThreadSafe" ) ) ); + public static void beforeSuite() { + assertThat(Thread.currentThread().getName(), is(not("maven-surefire-plugin@NotThreadSafe"))); } @AfterClass - public static void afterSuite() - { - assertThat( Thread.currentThread().getName(), is( not( "maven-surefire-plugin@NotThreadSafe" ) ) ); + public static void afterSuite() { + assertThat(Thread.currentThread().getName(), is(not("maven-surefire-plugin@NotThreadSafe"))); } } /** * */ - @RunWith( Suite.class ) - @Suite.SuiteClasses( {NotThreadSafeTest3.class, NormalTest1.class} ) + @RunWith(Suite.class) + @Suite.SuiteClasses({NotThreadSafeTest3.class, NormalTest1.class}) @NotThreadSafe - public static class OverMixedSuite - { + public static class OverMixedSuite { @BeforeClass - public static void beforeSuite() - { - assertThat( Thread.currentThread().getName(), is( not( "maven-surefire-plugin@NotThreadSafe" ) ) ); + public static void beforeSuite() { + assertThat(Thread.currentThread().getName(), is(not("maven-surefire-plugin@NotThreadSafe"))); } @AfterClass - public static void afterSuite() - { - assertThat( Thread.currentThread().getName(), is( not( "maven-surefire-plugin@NotThreadSafe" ) ) ); + public static void afterSuite() { + assertThat(Thread.currentThread().getName(), is(not("maven-surefire-plugin@NotThreadSafe"))); } } /** * */ - public static class TestWithBeforeAfter - { + public static class TestWithBeforeAfter { @BeforeClass - public static void beforeClass() throws InterruptedException - { - System.out.println( new Date() + " BEG: beforeClass" ); - sleepSeconds( 1 ); - System.out.println( new Date() + " END: beforeClass" ); + public static void beforeClass() throws InterruptedException { + System.out.println(new Date() + " BEG: beforeClass"); + sleepSeconds(1); + System.out.println(new Date() + " END: beforeClass"); } @Before - public void before() throws InterruptedException - { - System.out.println( new Date() + " BEG: before" ); - sleepSeconds( 1 ); - System.out.println( new Date() + " END: before" ); + public void before() throws InterruptedException { + System.out.println(new Date() + " BEG: before"); + sleepSeconds(1); + System.out.println(new Date() + " END: before"); } @Test - public void test() throws InterruptedException - { - System.out.println( new Date() + " BEG: test" ); - sleepSeconds( 1 ); - System.out.println( new Date() + " END: test" ); + public void test() throws InterruptedException { + System.out.println(new Date() + " BEG: test"); + sleepSeconds(1); + System.out.println(new Date() + " END: test"); } @After - public void after() throws InterruptedException - { - System.out.println( new Date() + " BEG: after" ); - sleepSeconds( 1 ); - System.out.println( new Date() + " END: after" ); + public void after() throws InterruptedException { + System.out.println(new Date() + " BEG: after"); + sleepSeconds(1); + System.out.println(new Date() + " END: after"); } @AfterClass - public static void afterClass() throws InterruptedException - { - System.out.println( new Date() + " BEG: afterClass" ); - sleepSeconds( 1 ); - System.out.println( new Date() + " END: afterClass" ); + public static void afterClass() throws InterruptedException { + System.out.println(new Date() + " BEG: afterClass"); + sleepSeconds(1); + System.out.println(new Date() + " END: afterClass"); } } - private static long systemMillis() - { - return TimeUnit.NANOSECONDS.toMillis( System.nanoTime() ); + private static long systemMillis() { + return TimeUnit.NANOSECONDS.toMillis(System.nanoTime()); } - private static void sleepSeconds( int seconds ) throws InterruptedException - { - TimeUnit.SECONDS.sleep( seconds ); + private static void sleepSeconds(int seconds) throws InterruptedException { + TimeUnit.SECONDS.sleep(seconds); } } diff --git a/surefire-providers/surefire-junit47/src/test/java/org/apache/maven/surefire/junitcore/pc/ParallelComputerUtilTest.java b/surefire-providers/surefire-junit47/src/test/java/org/apache/maven/surefire/junitcore/pc/ParallelComputerUtilTest.java index 9dd87d09a3..96aeec0493 100644 --- a/surefire-providers/surefire-junit47/src/test/java/org/apache/maven/surefire/junitcore/pc/ParallelComputerUtilTest.java +++ b/surefire-providers/surefire-junit47/src/test/java/org/apache/maven/surefire/junitcore/pc/ParallelComputerUtilTest.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.junitcore.pc; /* @@ -19,6 +37,11 @@ * under the License. */ +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.TimeUnit; + import org.apache.maven.plugin.surefire.log.api.ConsoleLogger; import org.apache.maven.surefire.api.testset.TestSetFailedException; import org.apache.maven.surefire.junitcore.JUnitCoreParameters; @@ -35,11 +58,6 @@ import org.junit.runner.Result; import org.junit.runner.RunWith; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; -import java.util.concurrent.TimeUnit; - import static org.apache.maven.surefire.junitcore.JUnitCoreParameters.PARALLEL_KEY; import static org.apache.maven.surefire.junitcore.JUnitCoreParameters.PARALLEL_TIMEOUTFORCED_KEY; import static org.apache.maven.surefire.junitcore.JUnitCoreParameters.PARALLEL_TIMEOUT_KEY; @@ -64,11 +82,10 @@ * @see ParallelComputerUtil * @since 2.16 */ -@RunWith( Theories.class ) -@SuppressWarnings( "checkstyle:magicnumber" ) -public final class ParallelComputerUtilTest -{ - private static final ConsoleLogger LOGGER = mock( ConsoleLogger.class ); +@RunWith(Theories.class) +@SuppressWarnings("checkstyle:magicnumber") +public final class ParallelComputerUtilTest { + private static final ConsoleLogger LOGGER = mock(ConsoleLogger.class); @DataPoint public static final int CPU_1 = 1; @@ -80,1037 +97,975 @@ public final class ParallelComputerUtilTest public final ExpectedException exception = ExpectedException.none(); @BeforeClass - public static void beforeClass() - { - ParallelComputerUtil.overrideAvailableProcessors( 1 ); + public static void beforeClass() { + ParallelComputerUtil.overrideAvailableProcessors(1); } @AfterClass - public static void afterClass() - { + public static void afterClass() { ParallelComputerUtil.setDefaultAvailableProcessors(); } @Before - public void beforeTest() throws InterruptedException - { + public void beforeTest() throws InterruptedException { System.gc(); - Thread.sleep( 50L ); - assertFalse( Thread.currentThread().isInterrupted() ); + Thread.sleep(50L); + assertFalse(Thread.currentThread().isInterrupted()); } - private static Map parallel( String parallel ) - { - return Collections.singletonMap( PARALLEL_KEY, parallel ); + private static Map parallel(String parallel) { + return Collections.singletonMap(PARALLEL_KEY, parallel); } @Test - public void unknownParallel() throws TestSetFailedException - { + public void unknownParallel() throws TestSetFailedException { Map properties = new HashMap<>(); - exception.expect( TestSetFailedException.class ); - resolveConcurrency( new JUnitCoreParameters( properties ), null ); + exception.expect(TestSetFailedException.class); + resolveConcurrency(new JUnitCoreParameters(properties), null); } @Test - public void unknownThreadCountSuites() throws TestSetFailedException - { - JUnitCoreParameters params = new JUnitCoreParameters( parallel( "suites" ) ); - assertTrue( params.isParallelSuites() ); - assertFalse( params.isParallelClasses() ); - assertFalse( params.isParallelMethods() ); - exception.expect( TestSetFailedException.class ); - resolveConcurrency( params, null ); + public void unknownThreadCountSuites() throws TestSetFailedException { + JUnitCoreParameters params = new JUnitCoreParameters(parallel("suites")); + assertTrue(params.isParallelSuites()); + assertFalse(params.isParallelClasses()); + assertFalse(params.isParallelMethods()); + exception.expect(TestSetFailedException.class); + resolveConcurrency(params, null); } @Test - public void unknownThreadCountClasses() throws TestSetFailedException - { - JUnitCoreParameters params = new JUnitCoreParameters( parallel( "classes" ) ); - assertFalse( params.isParallelSuites() ); - assertTrue( params.isParallelClasses() ); - assertFalse( params.isParallelMethods() ); - exception.expect( TestSetFailedException.class ); - resolveConcurrency( params, null ); + public void unknownThreadCountClasses() throws TestSetFailedException { + JUnitCoreParameters params = new JUnitCoreParameters(parallel("classes")); + assertFalse(params.isParallelSuites()); + assertTrue(params.isParallelClasses()); + assertFalse(params.isParallelMethods()); + exception.expect(TestSetFailedException.class); + resolveConcurrency(params, null); } @Test - public void unknownThreadCountMethods() throws TestSetFailedException - { - JUnitCoreParameters params = new JUnitCoreParameters( parallel( "methods" ) ); - assertFalse( params.isParallelSuites() ); - assertFalse( params.isParallelClasses() ); - assertTrue( params.isParallelMethods() ); - exception.expect( TestSetFailedException.class ); - resolveConcurrency( params, null ); + public void unknownThreadCountMethods() throws TestSetFailedException { + JUnitCoreParameters params = new JUnitCoreParameters(parallel("methods")); + assertFalse(params.isParallelSuites()); + assertFalse(params.isParallelClasses()); + assertTrue(params.isParallelMethods()); + exception.expect(TestSetFailedException.class); + resolveConcurrency(params, null); } @Test - public void unknownThreadCountBoth() throws TestSetFailedException - { - JUnitCoreParameters params = new JUnitCoreParameters( parallel( "both" ) ); - assertFalse( params.isParallelSuites() ); - assertTrue( params.isParallelClasses() ); - assertTrue( params.isParallelMethods() ); - exception.expect( TestSetFailedException.class ); - resolveConcurrency( params, null ); + public void unknownThreadCountBoth() throws TestSetFailedException { + JUnitCoreParameters params = new JUnitCoreParameters(parallel("both")); + assertFalse(params.isParallelSuites()); + assertTrue(params.isParallelClasses()); + assertTrue(params.isParallelMethods()); + exception.expect(TestSetFailedException.class); + resolveConcurrency(params, null); } @Test - public void unknownThreadCountAll() throws TestSetFailedException - { - JUnitCoreParameters params = new JUnitCoreParameters( parallel( "all" ) ); - assertTrue( params.isParallelSuites() ); - assertTrue( params.isParallelClasses() ); - assertTrue( params.isParallelMethods() ); - exception.expect( TestSetFailedException.class ); - resolveConcurrency( params, null ); + public void unknownThreadCountAll() throws TestSetFailedException { + JUnitCoreParameters params = new JUnitCoreParameters(parallel("all")); + assertTrue(params.isParallelSuites()); + assertTrue(params.isParallelClasses()); + assertTrue(params.isParallelMethods()); + exception.expect(TestSetFailedException.class); + resolveConcurrency(params, null); } @Test - public void unknownThreadCountSuitesAndClasses() throws TestSetFailedException - { - JUnitCoreParameters params = new JUnitCoreParameters( parallel( "suitesAndClasses" ) ); - assertTrue( params.isParallelSuites() ); - assertTrue( params.isParallelClasses() ); - assertFalse( params.isParallelMethods() ); - exception.expect( TestSetFailedException.class ); - resolveConcurrency( params, null ); + public void unknownThreadCountSuitesAndClasses() throws TestSetFailedException { + JUnitCoreParameters params = new JUnitCoreParameters(parallel("suitesAndClasses")); + assertTrue(params.isParallelSuites()); + assertTrue(params.isParallelClasses()); + assertFalse(params.isParallelMethods()); + exception.expect(TestSetFailedException.class); + resolveConcurrency(params, null); } @Test - public void unknownThreadCountSuitesAndMethods() throws TestSetFailedException - { - JUnitCoreParameters params = new JUnitCoreParameters( parallel( "suitesAndMethods" ) ); - assertTrue( params.isParallelSuites() ); - assertFalse( params.isParallelClasses() ); - assertTrue( params.isParallelMethods() ); - exception.expect( TestSetFailedException.class ); - resolveConcurrency( params, null ); + public void unknownThreadCountSuitesAndMethods() throws TestSetFailedException { + JUnitCoreParameters params = new JUnitCoreParameters(parallel("suitesAndMethods")); + assertTrue(params.isParallelSuites()); + assertFalse(params.isParallelClasses()); + assertTrue(params.isParallelMethods()); + exception.expect(TestSetFailedException.class); + resolveConcurrency(params, null); } @Test - public void unknownThreadCountClassesAndMethods() throws TestSetFailedException - { - JUnitCoreParameters params = new JUnitCoreParameters( parallel( "classesAndMethods" ) ); - assertFalse( params.isParallelSuites() ); - assertTrue( params.isParallelClasses() ); - assertTrue( params.isParallelMethods() ); - exception.expect( TestSetFailedException.class ); - resolveConcurrency( params, null ); + public void unknownThreadCountClassesAndMethods() throws TestSetFailedException { + JUnitCoreParameters params = new JUnitCoreParameters(parallel("classesAndMethods")); + assertFalse(params.isParallelSuites()); + assertTrue(params.isParallelClasses()); + assertTrue(params.isParallelMethods()); + exception.expect(TestSetFailedException.class); + resolveConcurrency(params, null); } @Theory - public void useUnlimitedThreadsSuites( int cpu ) throws TestSetFailedException - { - ParallelComputerUtil.overrideAvailableProcessors( cpu ); + public void useUnlimitedThreadsSuites(int cpu) throws TestSetFailedException { + ParallelComputerUtil.overrideAvailableProcessors(cpu); Map properties = new HashMap<>(); - properties.put( PARALLEL_KEY, "suites" ); - properties.put( USEUNLIMITEDTHREADS_KEY, "true" ); - JUnitCoreParameters params = new JUnitCoreParameters( properties ); - Concurrency concurrency = resolveConcurrency( params, null ); - assertTrue( params.isParallelSuites() ); - assertFalse( params.isParallelClasses() ); - assertFalse( params.isParallelMethods() ); - assertThat( concurrency.capacity, is( Integer.MAX_VALUE ) ); - assertThat( concurrency.suites, is( Integer.MAX_VALUE ) ); - assertThat( concurrency.classes, is( 0 ) ); - assertThat( concurrency.methods, is( 0 ) ); - - properties.put( THREADCOUNTSUITES_KEY, "5" ); - params = new JUnitCoreParameters( properties ); - concurrency = resolveConcurrency( params, null ); - assertTrue( params.isParallelSuites() ); - assertFalse( params.isParallelClasses() ); - assertFalse( params.isParallelMethods() ); - assertThat( concurrency.capacity, is( Integer.MAX_VALUE ) ); - assertThat( concurrency.suites, is( 5 * cpu ) ); - assertThat( concurrency.classes, is( 0 ) ); - assertThat( concurrency.methods, is( 0 ) ); + properties.put(PARALLEL_KEY, "suites"); + properties.put(USEUNLIMITEDTHREADS_KEY, "true"); + JUnitCoreParameters params = new JUnitCoreParameters(properties); + Concurrency concurrency = resolveConcurrency(params, null); + assertTrue(params.isParallelSuites()); + assertFalse(params.isParallelClasses()); + assertFalse(params.isParallelMethods()); + assertThat(concurrency.capacity, is(Integer.MAX_VALUE)); + assertThat(concurrency.suites, is(Integer.MAX_VALUE)); + assertThat(concurrency.classes, is(0)); + assertThat(concurrency.methods, is(0)); + + properties.put(THREADCOUNTSUITES_KEY, "5"); + params = new JUnitCoreParameters(properties); + concurrency = resolveConcurrency(params, null); + assertTrue(params.isParallelSuites()); + assertFalse(params.isParallelClasses()); + assertFalse(params.isParallelMethods()); + assertThat(concurrency.capacity, is(Integer.MAX_VALUE)); + assertThat(concurrency.suites, is(5 * cpu)); + assertThat(concurrency.classes, is(0)); + assertThat(concurrency.methods, is(0)); } @Theory - public void useUnlimitedThreadsClasses( int cpu ) throws TestSetFailedException - { - ParallelComputerUtil.overrideAvailableProcessors( cpu ); + public void useUnlimitedThreadsClasses(int cpu) throws TestSetFailedException { + ParallelComputerUtil.overrideAvailableProcessors(cpu); Map properties = new HashMap<>(); - properties.put( PARALLEL_KEY, "classes" ); - properties.put( USEUNLIMITEDTHREADS_KEY, "true" ); - JUnitCoreParameters params = new JUnitCoreParameters( properties ); - Concurrency concurrency = resolveConcurrency( params, null ); - assertFalse( params.isParallelSuites() ); - assertTrue( params.isParallelClasses() ); - assertFalse( params.isParallelMethods() ); - assertThat( concurrency.capacity, is( Integer.MAX_VALUE ) ); - assertThat( concurrency.suites, is( 0 ) ); - assertThat( concurrency.classes, is( Integer.MAX_VALUE ) ); - assertThat( concurrency.methods, is( 0 ) ); - - properties.put( THREADCOUNTCLASSES_KEY, "5" ); - params = new JUnitCoreParameters( properties ); - concurrency = resolveConcurrency( params, null ); - assertFalse( params.isParallelSuites() ); - assertTrue( params.isParallelClasses() ); - assertFalse( params.isParallelMethods() ); - assertThat( concurrency.capacity, is( Integer.MAX_VALUE ) ); - assertThat( concurrency.suites, is( 0 ) ); - assertThat( concurrency.classes, is( 5 * cpu ) ); - assertThat( concurrency.methods, is( 0 ) ); + properties.put(PARALLEL_KEY, "classes"); + properties.put(USEUNLIMITEDTHREADS_KEY, "true"); + JUnitCoreParameters params = new JUnitCoreParameters(properties); + Concurrency concurrency = resolveConcurrency(params, null); + assertFalse(params.isParallelSuites()); + assertTrue(params.isParallelClasses()); + assertFalse(params.isParallelMethods()); + assertThat(concurrency.capacity, is(Integer.MAX_VALUE)); + assertThat(concurrency.suites, is(0)); + assertThat(concurrency.classes, is(Integer.MAX_VALUE)); + assertThat(concurrency.methods, is(0)); + + properties.put(THREADCOUNTCLASSES_KEY, "5"); + params = new JUnitCoreParameters(properties); + concurrency = resolveConcurrency(params, null); + assertFalse(params.isParallelSuites()); + assertTrue(params.isParallelClasses()); + assertFalse(params.isParallelMethods()); + assertThat(concurrency.capacity, is(Integer.MAX_VALUE)); + assertThat(concurrency.suites, is(0)); + assertThat(concurrency.classes, is(5 * cpu)); + assertThat(concurrency.methods, is(0)); } @Theory - public void unlimitedThreadsMethods( int cpu ) throws TestSetFailedException - { - ParallelComputerUtil.overrideAvailableProcessors( cpu ); + public void unlimitedThreadsMethods(int cpu) throws TestSetFailedException { + ParallelComputerUtil.overrideAvailableProcessors(cpu); Map properties = new HashMap<>(); - properties.put( PARALLEL_KEY, "methods" ); - properties.put( USEUNLIMITEDTHREADS_KEY, "true" ); - JUnitCoreParameters params = new JUnitCoreParameters( properties ); - Concurrency concurrency = resolveConcurrency( params, null ); - assertFalse( params.isParallelSuites() ); - assertFalse( params.isParallelClasses() ); - assertTrue( params.isParallelMethods() ); - assertThat( concurrency.capacity, is( Integer.MAX_VALUE ) ); - assertThat( concurrency.suites, is( 0 ) ); - assertThat( concurrency.classes, is( 0 ) ); - assertThat( concurrency.methods, is( Integer.MAX_VALUE ) ); - - properties.put( THREADCOUNTMETHODS_KEY, "5" ); - params = new JUnitCoreParameters( properties ); - concurrency = resolveConcurrency( params, null ); - assertFalse( params.isParallelSuites() ); - assertFalse( params.isParallelClasses() ); - assertTrue( params.isParallelMethods() ); - assertThat( concurrency.capacity, is( Integer.MAX_VALUE ) ); - assertThat( concurrency.suites, is( 0 ) ); - assertThat( concurrency.classes, is( 0 ) ); - assertThat( concurrency.methods, is( 5 * cpu ) ); + properties.put(PARALLEL_KEY, "methods"); + properties.put(USEUNLIMITEDTHREADS_KEY, "true"); + JUnitCoreParameters params = new JUnitCoreParameters(properties); + Concurrency concurrency = resolveConcurrency(params, null); + assertFalse(params.isParallelSuites()); + assertFalse(params.isParallelClasses()); + assertTrue(params.isParallelMethods()); + assertThat(concurrency.capacity, is(Integer.MAX_VALUE)); + assertThat(concurrency.suites, is(0)); + assertThat(concurrency.classes, is(0)); + assertThat(concurrency.methods, is(Integer.MAX_VALUE)); + + properties.put(THREADCOUNTMETHODS_KEY, "5"); + params = new JUnitCoreParameters(properties); + concurrency = resolveConcurrency(params, null); + assertFalse(params.isParallelSuites()); + assertFalse(params.isParallelClasses()); + assertTrue(params.isParallelMethods()); + assertThat(concurrency.capacity, is(Integer.MAX_VALUE)); + assertThat(concurrency.suites, is(0)); + assertThat(concurrency.classes, is(0)); + assertThat(concurrency.methods, is(5 * cpu)); } @Theory - public void unlimitedThreadsSuitesAndClasses( int cpu ) throws TestSetFailedException - { - ParallelComputerUtil.overrideAvailableProcessors( cpu ); + public void unlimitedThreadsSuitesAndClasses(int cpu) throws TestSetFailedException { + ParallelComputerUtil.overrideAvailableProcessors(cpu); Map properties = new HashMap<>(); - properties.put( PARALLEL_KEY, "suitesAndClasses" ); - properties.put( USEUNLIMITEDTHREADS_KEY, "true" ); - JUnitCoreParameters params = new JUnitCoreParameters( properties ); - Concurrency concurrency = resolveConcurrency( params, null ); - assertTrue( params.isParallelSuites() ); - assertTrue( params.isParallelClasses() ); - assertFalse( params.isParallelMethods() ); - assertThat( concurrency.capacity, is( Integer.MAX_VALUE ) ); - assertThat( concurrency.suites, is( Integer.MAX_VALUE ) ); - assertThat( concurrency.classes, is( Integer.MAX_VALUE ) ); - assertThat( concurrency.methods, is( 0 ) ); - - properties.put( THREADCOUNTSUITES_KEY, "5" ); - properties.put( THREADCOUNTCLASSES_KEY, "15" ); - params = new JUnitCoreParameters( properties ); - concurrency = resolveConcurrency( params, null ); - assertTrue( params.isParallelSuites() ); - assertTrue( params.isParallelClasses() ); - assertFalse( params.isParallelMethods() ); - assertThat( concurrency.capacity, is( Integer.MAX_VALUE ) ); - assertThat( concurrency.suites, is( 5 * cpu ) ); - assertThat( concurrency.classes, is( 15 * cpu ) ); - assertThat( concurrency.methods, is( 0 ) ); + properties.put(PARALLEL_KEY, "suitesAndClasses"); + properties.put(USEUNLIMITEDTHREADS_KEY, "true"); + JUnitCoreParameters params = new JUnitCoreParameters(properties); + Concurrency concurrency = resolveConcurrency(params, null); + assertTrue(params.isParallelSuites()); + assertTrue(params.isParallelClasses()); + assertFalse(params.isParallelMethods()); + assertThat(concurrency.capacity, is(Integer.MAX_VALUE)); + assertThat(concurrency.suites, is(Integer.MAX_VALUE)); + assertThat(concurrency.classes, is(Integer.MAX_VALUE)); + assertThat(concurrency.methods, is(0)); + + properties.put(THREADCOUNTSUITES_KEY, "5"); + properties.put(THREADCOUNTCLASSES_KEY, "15"); + params = new JUnitCoreParameters(properties); + concurrency = resolveConcurrency(params, null); + assertTrue(params.isParallelSuites()); + assertTrue(params.isParallelClasses()); + assertFalse(params.isParallelMethods()); + assertThat(concurrency.capacity, is(Integer.MAX_VALUE)); + assertThat(concurrency.suites, is(5 * cpu)); + assertThat(concurrency.classes, is(15 * cpu)); + assertThat(concurrency.methods, is(0)); } @Theory - public void unlimitedThreadsSuitesAndMethods( int cpu ) throws TestSetFailedException - { - ParallelComputerUtil.overrideAvailableProcessors( cpu ); + public void unlimitedThreadsSuitesAndMethods(int cpu) throws TestSetFailedException { + ParallelComputerUtil.overrideAvailableProcessors(cpu); Map properties = new HashMap<>(); - properties.put( PARALLEL_KEY, "suitesAndMethods" ); - properties.put( USEUNLIMITEDTHREADS_KEY, "true" ); - JUnitCoreParameters params = new JUnitCoreParameters( properties ); - Concurrency concurrency = resolveConcurrency( params, null ); - assertTrue( params.isParallelSuites() ); - assertFalse( params.isParallelClasses() ); - assertTrue( params.isParallelMethods() ); - assertThat( concurrency.capacity, is( Integer.MAX_VALUE ) ); - assertThat( concurrency.suites, is( Integer.MAX_VALUE ) ); - assertThat( concurrency.classes, is( 0 ) ); - assertThat( concurrency.methods, is( Integer.MAX_VALUE ) ); - - properties.put( THREADCOUNTSUITES_KEY, "5" ); - properties.put( THREADCOUNTMETHODS_KEY, "15" ); - params = new JUnitCoreParameters( properties ); - concurrency = resolveConcurrency( params, null ); - assertTrue( params.isParallelSuites() ); - assertFalse( params.isParallelClasses() ); - assertTrue( params.isParallelMethods() ); - assertThat( concurrency.capacity, is( Integer.MAX_VALUE ) ); - assertThat( concurrency.suites, is( 5 * cpu ) ); - assertThat( concurrency.classes, is( 0 ) ); - assertThat( concurrency.methods, is( 15 * cpu ) ); + properties.put(PARALLEL_KEY, "suitesAndMethods"); + properties.put(USEUNLIMITEDTHREADS_KEY, "true"); + JUnitCoreParameters params = new JUnitCoreParameters(properties); + Concurrency concurrency = resolveConcurrency(params, null); + assertTrue(params.isParallelSuites()); + assertFalse(params.isParallelClasses()); + assertTrue(params.isParallelMethods()); + assertThat(concurrency.capacity, is(Integer.MAX_VALUE)); + assertThat(concurrency.suites, is(Integer.MAX_VALUE)); + assertThat(concurrency.classes, is(0)); + assertThat(concurrency.methods, is(Integer.MAX_VALUE)); + + properties.put(THREADCOUNTSUITES_KEY, "5"); + properties.put(THREADCOUNTMETHODS_KEY, "15"); + params = new JUnitCoreParameters(properties); + concurrency = resolveConcurrency(params, null); + assertTrue(params.isParallelSuites()); + assertFalse(params.isParallelClasses()); + assertTrue(params.isParallelMethods()); + assertThat(concurrency.capacity, is(Integer.MAX_VALUE)); + assertThat(concurrency.suites, is(5 * cpu)); + assertThat(concurrency.classes, is(0)); + assertThat(concurrency.methods, is(15 * cpu)); } @Theory - public void unlimitedThreadsClassesAndMethods( int cpu ) throws TestSetFailedException - { - ParallelComputerUtil.overrideAvailableProcessors( cpu ); + public void unlimitedThreadsClassesAndMethods(int cpu) throws TestSetFailedException { + ParallelComputerUtil.overrideAvailableProcessors(cpu); Map properties = new HashMap<>(); - properties.put( PARALLEL_KEY, "classesAndMethods" ); - properties.put( USEUNLIMITEDTHREADS_KEY, "true" ); - JUnitCoreParameters params = new JUnitCoreParameters( properties ); - Concurrency concurrency = resolveConcurrency( params, null ); - assertFalse( params.isParallelSuites() ); - assertTrue( params.isParallelClasses() ); - assertTrue( params.isParallelMethods() ); - assertThat( concurrency.capacity, is( Integer.MAX_VALUE ) ); - assertThat( concurrency.suites, is( 0 ) ); - assertThat( concurrency.classes, is( Integer.MAX_VALUE ) ); - assertThat( concurrency.methods, is( Integer.MAX_VALUE ) ); - - properties.put( THREADCOUNTCLASSES_KEY, "5" ); - properties.put( THREADCOUNTMETHODS_KEY, "15" ); - params = new JUnitCoreParameters( properties ); - concurrency = resolveConcurrency( params, null ); - assertFalse( params.isParallelSuites() ); - assertTrue( params.isParallelClasses() ); - assertTrue( params.isParallelMethods() ); - assertThat( concurrency.capacity, is( Integer.MAX_VALUE ) ); - assertThat( concurrency.suites, is( 0 ) ); - assertThat( concurrency.classes, is( 5 * cpu ) ); - assertThat( concurrency.methods, is( 15 * cpu ) ); + properties.put(PARALLEL_KEY, "classesAndMethods"); + properties.put(USEUNLIMITEDTHREADS_KEY, "true"); + JUnitCoreParameters params = new JUnitCoreParameters(properties); + Concurrency concurrency = resolveConcurrency(params, null); + assertFalse(params.isParallelSuites()); + assertTrue(params.isParallelClasses()); + assertTrue(params.isParallelMethods()); + assertThat(concurrency.capacity, is(Integer.MAX_VALUE)); + assertThat(concurrency.suites, is(0)); + assertThat(concurrency.classes, is(Integer.MAX_VALUE)); + assertThat(concurrency.methods, is(Integer.MAX_VALUE)); + + properties.put(THREADCOUNTCLASSES_KEY, "5"); + properties.put(THREADCOUNTMETHODS_KEY, "15"); + params = new JUnitCoreParameters(properties); + concurrency = resolveConcurrency(params, null); + assertFalse(params.isParallelSuites()); + assertTrue(params.isParallelClasses()); + assertTrue(params.isParallelMethods()); + assertThat(concurrency.capacity, is(Integer.MAX_VALUE)); + assertThat(concurrency.suites, is(0)); + assertThat(concurrency.classes, is(5 * cpu)); + assertThat(concurrency.methods, is(15 * cpu)); } @Theory - public void unlimitedThreadsAll( int cpu ) throws TestSetFailedException - { - ParallelComputerUtil.overrideAvailableProcessors( cpu ); + public void unlimitedThreadsAll(int cpu) throws TestSetFailedException { + ParallelComputerUtil.overrideAvailableProcessors(cpu); Map properties = new HashMap<>(); - properties.put( PARALLEL_KEY, "all" ); - properties.put( USEUNLIMITEDTHREADS_KEY, "true" ); - JUnitCoreParameters params = new JUnitCoreParameters( properties ); - Concurrency concurrency = resolveConcurrency( params, null ); - assertTrue( params.isParallelSuites() ); - assertTrue( params.isParallelClasses() ); - assertTrue( params.isParallelMethods() ); - assertThat( concurrency.capacity, is( Integer.MAX_VALUE ) ); - assertThat( concurrency.suites, is( Integer.MAX_VALUE ) ); - assertThat( concurrency.classes, is( Integer.MAX_VALUE ) ); - assertThat( concurrency.methods, is( Integer.MAX_VALUE ) ); - - properties.put( THREADCOUNTSUITES_KEY, "5" ); - properties.put( THREADCOUNTCLASSES_KEY, "15" ); - properties.put( THREADCOUNTMETHODS_KEY, "30" ); - params = new JUnitCoreParameters( properties ); - concurrency = resolveConcurrency( params, null ); - assertTrue( params.isParallelSuites() ); - assertTrue( params.isParallelClasses() ); - assertTrue( params.isParallelMethods() ); - assertThat( concurrency.capacity, is( Integer.MAX_VALUE ) ); - assertThat( concurrency.suites, is( 5 * cpu ) ); - assertThat( concurrency.classes, is( 15 * cpu ) ); - assertThat( concurrency.methods, is( 30 * cpu ) ); + properties.put(PARALLEL_KEY, "all"); + properties.put(USEUNLIMITEDTHREADS_KEY, "true"); + JUnitCoreParameters params = new JUnitCoreParameters(properties); + Concurrency concurrency = resolveConcurrency(params, null); + assertTrue(params.isParallelSuites()); + assertTrue(params.isParallelClasses()); + assertTrue(params.isParallelMethods()); + assertThat(concurrency.capacity, is(Integer.MAX_VALUE)); + assertThat(concurrency.suites, is(Integer.MAX_VALUE)); + assertThat(concurrency.classes, is(Integer.MAX_VALUE)); + assertThat(concurrency.methods, is(Integer.MAX_VALUE)); + + properties.put(THREADCOUNTSUITES_KEY, "5"); + properties.put(THREADCOUNTCLASSES_KEY, "15"); + properties.put(THREADCOUNTMETHODS_KEY, "30"); + params = new JUnitCoreParameters(properties); + concurrency = resolveConcurrency(params, null); + assertTrue(params.isParallelSuites()); + assertTrue(params.isParallelClasses()); + assertTrue(params.isParallelMethods()); + assertThat(concurrency.capacity, is(Integer.MAX_VALUE)); + assertThat(concurrency.suites, is(5 * cpu)); + assertThat(concurrency.classes, is(15 * cpu)); + assertThat(concurrency.methods, is(30 * cpu)); } @Theory - public void threadCountSuites( int cpu ) throws TestSetFailedException - { - ParallelComputerUtil.overrideAvailableProcessors( cpu ); + public void threadCountSuites(int cpu) throws TestSetFailedException { + ParallelComputerUtil.overrideAvailableProcessors(cpu); Map properties = new HashMap<>(); - properties.put( PARALLEL_KEY, "suites" ); - properties.put( THREADCOUNT_KEY, "3" ); - JUnitCoreParameters params = new JUnitCoreParameters( properties ); - Concurrency concurrency = resolveConcurrency( params, null ); - assertTrue( params.isParallelSuites() ); - assertFalse( params.isParallelClasses() ); - assertFalse( params.isParallelMethods() ); - assertThat( concurrency.capacity, is( 0 ) ); - assertThat( concurrency.suites, is( 3 * cpu ) ); - assertThat( concurrency.classes, is( 0 ) ); - assertThat( concurrency.methods, is( 0 ) ); + properties.put(PARALLEL_KEY, "suites"); + properties.put(THREADCOUNT_KEY, "3"); + JUnitCoreParameters params = new JUnitCoreParameters(properties); + Concurrency concurrency = resolveConcurrency(params, null); + assertTrue(params.isParallelSuites()); + assertFalse(params.isParallelClasses()); + assertFalse(params.isParallelMethods()); + assertThat(concurrency.capacity, is(0)); + assertThat(concurrency.suites, is(3 * cpu)); + assertThat(concurrency.classes, is(0)); + assertThat(concurrency.methods, is(0)); } @Theory - public void threadCountClasses( int cpu ) throws TestSetFailedException - { - ParallelComputerUtil.overrideAvailableProcessors( cpu ); + public void threadCountClasses(int cpu) throws TestSetFailedException { + ParallelComputerUtil.overrideAvailableProcessors(cpu); Map properties = new HashMap<>(); - properties.put( PARALLEL_KEY, "classes" ); - properties.put( THREADCOUNT_KEY, "3" ); - JUnitCoreParameters params = new JUnitCoreParameters( properties ); - Concurrency concurrency = resolveConcurrency( params, null ); - assertFalse( params.isParallelSuites() ); - assertTrue( params.isParallelClasses() ); - assertFalse( params.isParallelMethods() ); - assertThat( concurrency.capacity, is( 0 ) ); - assertThat( concurrency.suites, is( 0 ) ); - assertThat( concurrency.classes, is( 3 * cpu ) ); - assertThat( concurrency.methods, is( 0 ) ); + properties.put(PARALLEL_KEY, "classes"); + properties.put(THREADCOUNT_KEY, "3"); + JUnitCoreParameters params = new JUnitCoreParameters(properties); + Concurrency concurrency = resolveConcurrency(params, null); + assertFalse(params.isParallelSuites()); + assertTrue(params.isParallelClasses()); + assertFalse(params.isParallelMethods()); + assertThat(concurrency.capacity, is(0)); + assertThat(concurrency.suites, is(0)); + assertThat(concurrency.classes, is(3 * cpu)); + assertThat(concurrency.methods, is(0)); } @Theory - public void threadCountMethods( int cpu ) throws TestSetFailedException - { - ParallelComputerUtil.overrideAvailableProcessors( cpu ); + public void threadCountMethods(int cpu) throws TestSetFailedException { + ParallelComputerUtil.overrideAvailableProcessors(cpu); Map properties = new HashMap<>(); - properties.put( PARALLEL_KEY, "methods" ); - properties.put( THREADCOUNT_KEY, "3" ); - JUnitCoreParameters params = new JUnitCoreParameters( properties ); - Concurrency concurrency = resolveConcurrency( params, null ); - assertFalse( params.isParallelSuites() ); - assertFalse( params.isParallelClasses() ); - assertTrue( params.isParallelMethods() ); - assertThat( concurrency.capacity, is( 0 ) ); - assertThat( concurrency.suites, is( 0 ) ); - assertThat( concurrency.classes, is( 0 ) ); - assertThat( concurrency.methods, is( 3 * cpu ) ); + properties.put(PARALLEL_KEY, "methods"); + properties.put(THREADCOUNT_KEY, "3"); + JUnitCoreParameters params = new JUnitCoreParameters(properties); + Concurrency concurrency = resolveConcurrency(params, null); + assertFalse(params.isParallelSuites()); + assertFalse(params.isParallelClasses()); + assertTrue(params.isParallelMethods()); + assertThat(concurrency.capacity, is(0)); + assertThat(concurrency.suites, is(0)); + assertThat(concurrency.classes, is(0)); + assertThat(concurrency.methods, is(3 * cpu)); } @Theory - public void threadCountBoth( int cpu ) throws TestSetFailedException - { - ParallelComputerUtil.overrideAvailableProcessors( cpu ); + public void threadCountBoth(int cpu) throws TestSetFailedException { + ParallelComputerUtil.overrideAvailableProcessors(cpu); Map properties = new HashMap<>(); - properties.put( PARALLEL_KEY, "both" ); - properties.put( THREADCOUNT_KEY, "3" ); - JUnitCoreParameters params = new JUnitCoreParameters( properties ); - Concurrency concurrency = resolveConcurrency( params, null ); - assertFalse( params.isParallelSuites() ); - assertTrue( params.isParallelClasses() ); - assertTrue( params.isParallelMethods() ); - assertThat( concurrency.capacity, is( 3 * cpu ) ); - assertThat( concurrency.suites, is( 0 ) ); - assertThat( concurrency.classes, is( (int) ( ( 3d / 2 ) * cpu ) ) ); - assertThat( concurrency.methods, is( Integer.MAX_VALUE ) ); + properties.put(PARALLEL_KEY, "both"); + properties.put(THREADCOUNT_KEY, "3"); + JUnitCoreParameters params = new JUnitCoreParameters(properties); + Concurrency concurrency = resolveConcurrency(params, null); + assertFalse(params.isParallelSuites()); + assertTrue(params.isParallelClasses()); + assertTrue(params.isParallelMethods()); + assertThat(concurrency.capacity, is(3 * cpu)); + assertThat(concurrency.suites, is(0)); + assertThat(concurrency.classes, is((int) ((3d / 2) * cpu))); + assertThat(concurrency.methods, is(Integer.MAX_VALUE)); } @Theory - public void threadCountClassesAndMethods( int cpu ) throws TestSetFailedException - { - ParallelComputerUtil.overrideAvailableProcessors( cpu ); + public void threadCountClassesAndMethods(int cpu) throws TestSetFailedException { + ParallelComputerUtil.overrideAvailableProcessors(cpu); Map properties = new HashMap<>(); - properties.put( PARALLEL_KEY, "classesAndMethods" ); - properties.put( THREADCOUNT_KEY, "3" ); - JUnitCoreParameters params = new JUnitCoreParameters( properties ); - Concurrency concurrency = resolveConcurrency( params, null ); - assertFalse( params.isParallelSuites() ); - assertTrue( params.isParallelClasses() ); - assertTrue( params.isParallelMethods() ); - assertThat( concurrency.capacity, is( 3 * cpu ) ); - assertThat( concurrency.suites, is( 0 ) ); - assertThat( concurrency.classes, is( (int) ( ( 3d / 2 ) * cpu ) ) ); - assertThat( concurrency.methods, is( Integer.MAX_VALUE ) ); + properties.put(PARALLEL_KEY, "classesAndMethods"); + properties.put(THREADCOUNT_KEY, "3"); + JUnitCoreParameters params = new JUnitCoreParameters(properties); + Concurrency concurrency = resolveConcurrency(params, null); + assertFalse(params.isParallelSuites()); + assertTrue(params.isParallelClasses()); + assertTrue(params.isParallelMethods()); + assertThat(concurrency.capacity, is(3 * cpu)); + assertThat(concurrency.suites, is(0)); + assertThat(concurrency.classes, is((int) ((3d / 2) * cpu))); + assertThat(concurrency.methods, is(Integer.MAX_VALUE)); } @Theory - public void threadCountSuitesAndMethods( int cpu ) throws TestSetFailedException - { - ParallelComputerUtil.overrideAvailableProcessors( cpu ); + public void threadCountSuitesAndMethods(int cpu) throws TestSetFailedException { + ParallelComputerUtil.overrideAvailableProcessors(cpu); Map properties = new HashMap<>(); - properties.put( PARALLEL_KEY, "suitesAndMethods" ); - properties.put( THREADCOUNT_KEY, "3" ); - JUnitCoreParameters params = new JUnitCoreParameters( properties ); - Concurrency concurrency = resolveConcurrency( params, null ); - assertTrue( params.isParallelSuites() ); - assertFalse( params.isParallelClasses() ); - assertTrue( params.isParallelMethods() ); - assertThat( concurrency.capacity, is( 3 * cpu ) ); - assertThat( concurrency.suites, is( (int) ( ( 3d / 2 ) * cpu ) ) ); - assertThat( concurrency.classes, is( 0 ) ); - assertThat( concurrency.methods, is( Integer.MAX_VALUE ) ); + properties.put(PARALLEL_KEY, "suitesAndMethods"); + properties.put(THREADCOUNT_KEY, "3"); + JUnitCoreParameters params = new JUnitCoreParameters(properties); + Concurrency concurrency = resolveConcurrency(params, null); + assertTrue(params.isParallelSuites()); + assertFalse(params.isParallelClasses()); + assertTrue(params.isParallelMethods()); + assertThat(concurrency.capacity, is(3 * cpu)); + assertThat(concurrency.suites, is((int) ((3d / 2) * cpu))); + assertThat(concurrency.classes, is(0)); + assertThat(concurrency.methods, is(Integer.MAX_VALUE)); } @Theory - public void threadCountSuitesAndClasses( int cpu ) throws TestSetFailedException - { - ParallelComputerUtil.overrideAvailableProcessors( cpu ); + public void threadCountSuitesAndClasses(int cpu) throws TestSetFailedException { + ParallelComputerUtil.overrideAvailableProcessors(cpu); Map properties = new HashMap<>(); - properties.put( PARALLEL_KEY, "suitesAndClasses" ); - properties.put( THREADCOUNT_KEY, "3" ); - JUnitCoreParameters params = new JUnitCoreParameters( properties ); - Concurrency concurrency = resolveConcurrency( params, null ); - assertTrue( params.isParallelSuites() ); - assertTrue( params.isParallelClasses() ); - assertFalse( params.isParallelMethods() ); - assertThat( concurrency.capacity, is( 3 * cpu ) ); - assertThat( concurrency.suites, is( (int) ( ( 3d / 2 ) * cpu ) ) ); - assertThat( concurrency.classes, is( Integer.MAX_VALUE ) ); - assertThat( concurrency.methods, is( 0 ) ); + properties.put(PARALLEL_KEY, "suitesAndClasses"); + properties.put(THREADCOUNT_KEY, "3"); + JUnitCoreParameters params = new JUnitCoreParameters(properties); + Concurrency concurrency = resolveConcurrency(params, null); + assertTrue(params.isParallelSuites()); + assertTrue(params.isParallelClasses()); + assertFalse(params.isParallelMethods()); + assertThat(concurrency.capacity, is(3 * cpu)); + assertThat(concurrency.suites, is((int) ((3d / 2) * cpu))); + assertThat(concurrency.classes, is(Integer.MAX_VALUE)); + assertThat(concurrency.methods, is(0)); } @Theory - public void threadCountAll( int cpu ) throws TestSetFailedException - { - ParallelComputerUtil.overrideAvailableProcessors( cpu ); + public void threadCountAll(int cpu) throws TestSetFailedException { + ParallelComputerUtil.overrideAvailableProcessors(cpu); Map properties = new HashMap<>(); - properties.put( PARALLEL_KEY, "all" ); - properties.put( THREADCOUNT_KEY, "3" ); - JUnitCoreParameters params = new JUnitCoreParameters( properties ); - Concurrency concurrency = resolveConcurrency( params, null ); - assertTrue( params.isParallelSuites() ); - assertTrue( params.isParallelClasses() ); - assertTrue( params.isParallelMethods() ); - assertThat( concurrency.capacity, is( 3 * cpu ) ); - assertThat( concurrency.suites, is( cpu ) ); - assertThat( concurrency.classes, is( cpu ) ); - assertThat( concurrency.methods, is( Integer.MAX_VALUE ) ); + properties.put(PARALLEL_KEY, "all"); + properties.put(THREADCOUNT_KEY, "3"); + JUnitCoreParameters params = new JUnitCoreParameters(properties); + Concurrency concurrency = resolveConcurrency(params, null); + assertTrue(params.isParallelSuites()); + assertTrue(params.isParallelClasses()); + assertTrue(params.isParallelMethods()); + assertThat(concurrency.capacity, is(3 * cpu)); + assertThat(concurrency.suites, is(cpu)); + assertThat(concurrency.classes, is(cpu)); + assertThat(concurrency.methods, is(Integer.MAX_VALUE)); } @Theory - public void everyThreadCountSuitesAndClasses( int cpu ) throws TestSetFailedException - { - ParallelComputerUtil.overrideAvailableProcessors( cpu ); + public void everyThreadCountSuitesAndClasses(int cpu) throws TestSetFailedException { + ParallelComputerUtil.overrideAvailableProcessors(cpu); Map properties = new HashMap<>(); - properties.put( PARALLEL_KEY, "suitesAndClasses" ); - properties.put( THREADCOUNT_KEY, "3" ); + properties.put(PARALLEL_KEY, "suitesAndClasses"); + properties.put(THREADCOUNT_KEY, "3"); // % percentage ratio - properties.put( THREADCOUNTSUITES_KEY, "34" ); - properties.put( THREADCOUNTCLASSES_KEY, "66" ); - JUnitCoreParameters params = new JUnitCoreParameters( properties ); - Concurrency concurrency = resolveConcurrency( params, null ); - assertTrue( params.isParallelSuites() ); - assertTrue( params.isParallelClasses() ); - assertFalse( params.isParallelMethods() ); - assertThat( concurrency.capacity, is( 3 * cpu ) ); - int concurrentSuites = (int) ( 0.34d * concurrency.capacity ); - assertThat( concurrency.suites, is( concurrentSuites ) ); - assertThat( concurrency.classes, is( concurrency.capacity - concurrentSuites ) ); - assertThat( concurrency.methods, is( 0 ) ); + properties.put(THREADCOUNTSUITES_KEY, "34"); + properties.put(THREADCOUNTCLASSES_KEY, "66"); + JUnitCoreParameters params = new JUnitCoreParameters(properties); + Concurrency concurrency = resolveConcurrency(params, null); + assertTrue(params.isParallelSuites()); + assertTrue(params.isParallelClasses()); + assertFalse(params.isParallelMethods()); + assertThat(concurrency.capacity, is(3 * cpu)); + int concurrentSuites = (int) (0.34d * concurrency.capacity); + assertThat(concurrency.suites, is(concurrentSuites)); + assertThat(concurrency.classes, is(concurrency.capacity - concurrentSuites)); + assertThat(concurrency.methods, is(0)); } @Theory - public void everyThreadCountSuitesAndMethods( int cpu ) throws TestSetFailedException - { - ParallelComputerUtil.overrideAvailableProcessors( cpu ); + public void everyThreadCountSuitesAndMethods(int cpu) throws TestSetFailedException { + ParallelComputerUtil.overrideAvailableProcessors(cpu); Map properties = new HashMap<>(); - properties.put( PARALLEL_KEY, "suitesAndMethods" ); - properties.put( THREADCOUNT_KEY, "3" ); + properties.put(PARALLEL_KEY, "suitesAndMethods"); + properties.put(THREADCOUNT_KEY, "3"); // % percentage ratio - properties.put( THREADCOUNTSUITES_KEY, "34" ); - properties.put( THREADCOUNTMETHODS_KEY, "66" ); - JUnitCoreParameters params = new JUnitCoreParameters( properties ); - Concurrency concurrency = resolveConcurrency( params, null ); - assertTrue( params.isParallelSuites() ); - assertFalse( params.isParallelClasses() ); - assertTrue( params.isParallelMethods() ); - assertThat( concurrency.capacity, is( 3 * cpu ) ); - int concurrentSuites = (int) ( 0.34d * concurrency.capacity ); - assertThat( concurrency.suites, is( concurrentSuites ) ); - assertThat( concurrency.classes, is( 0 ) ); - assertThat( concurrency.methods, is( concurrency.capacity - concurrentSuites ) ); + properties.put(THREADCOUNTSUITES_KEY, "34"); + properties.put(THREADCOUNTMETHODS_KEY, "66"); + JUnitCoreParameters params = new JUnitCoreParameters(properties); + Concurrency concurrency = resolveConcurrency(params, null); + assertTrue(params.isParallelSuites()); + assertFalse(params.isParallelClasses()); + assertTrue(params.isParallelMethods()); + assertThat(concurrency.capacity, is(3 * cpu)); + int concurrentSuites = (int) (0.34d * concurrency.capacity); + assertThat(concurrency.suites, is(concurrentSuites)); + assertThat(concurrency.classes, is(0)); + assertThat(concurrency.methods, is(concurrency.capacity - concurrentSuites)); } @Theory - public void everyThreadCountClassesAndMethods( int cpu ) throws TestSetFailedException - { - ParallelComputerUtil.overrideAvailableProcessors( cpu ); + public void everyThreadCountClassesAndMethods(int cpu) throws TestSetFailedException { + ParallelComputerUtil.overrideAvailableProcessors(cpu); Map properties = new HashMap<>(); - properties.put( PARALLEL_KEY, "classesAndMethods" ); - properties.put( THREADCOUNT_KEY, "3" ); + properties.put(PARALLEL_KEY, "classesAndMethods"); + properties.put(THREADCOUNT_KEY, "3"); // % percentage ratio - properties.put( THREADCOUNTCLASSES_KEY, "34" ); - properties.put( THREADCOUNTMETHODS_KEY, "66" ); - JUnitCoreParameters params = new JUnitCoreParameters( properties ); - Concurrency concurrency = resolveConcurrency( params, null ); - assertFalse( params.isParallelSuites() ); - assertTrue( params.isParallelClasses() ); - assertTrue( params.isParallelMethods() ); - assertThat( concurrency.capacity, is( 3 * cpu ) ); - assertThat( concurrency.suites, is( 0 ) ); - int concurrentClasses = (int) ( 0.34d * concurrency.capacity ); - assertThat( concurrency.classes, is( concurrentClasses ) ); - assertThat( concurrency.methods, is( concurrency.capacity - concurrentClasses ) ); + properties.put(THREADCOUNTCLASSES_KEY, "34"); + properties.put(THREADCOUNTMETHODS_KEY, "66"); + JUnitCoreParameters params = new JUnitCoreParameters(properties); + Concurrency concurrency = resolveConcurrency(params, null); + assertFalse(params.isParallelSuites()); + assertTrue(params.isParallelClasses()); + assertTrue(params.isParallelMethods()); + assertThat(concurrency.capacity, is(3 * cpu)); + assertThat(concurrency.suites, is(0)); + int concurrentClasses = (int) (0.34d * concurrency.capacity); + assertThat(concurrency.classes, is(concurrentClasses)); + assertThat(concurrency.methods, is(concurrency.capacity - concurrentClasses)); } @Theory - public void everyThreadCountAll( int cpu ) throws TestSetFailedException - { - ParallelComputerUtil.overrideAvailableProcessors( cpu ); + public void everyThreadCountAll(int cpu) throws TestSetFailedException { + ParallelComputerUtil.overrideAvailableProcessors(cpu); Map properties = new HashMap<>(); - properties.put( PARALLEL_KEY, "all" ); - properties.put( THREADCOUNT_KEY, "3" ); + properties.put(PARALLEL_KEY, "all"); + properties.put(THREADCOUNT_KEY, "3"); // % percentage ratio - properties.put( THREADCOUNTSUITES_KEY, "17" ); - properties.put( THREADCOUNTCLASSES_KEY, "34" ); - properties.put( THREADCOUNTMETHODS_KEY, "49" ); - JUnitCoreParameters params = new JUnitCoreParameters( properties ); - Concurrency concurrency = resolveConcurrency( params, null ); - assertTrue( params.isParallelSuites() ); - assertTrue( params.isParallelClasses() ); - assertTrue( params.isParallelMethods() ); - assertThat( concurrency.capacity, is( 3 * cpu ) ); - int concurrentSuites = (int) ( 0.17d * concurrency.capacity ); - int concurrentClasses = (int) ( 0.34d * concurrency.capacity ); - assertThat( concurrency.suites, is( concurrentSuites ) ); - assertThat( concurrency.classes, is( concurrentClasses ) ); - assertThat( concurrency.methods, is( concurrency.capacity - concurrentSuites - concurrentClasses ) ); + properties.put(THREADCOUNTSUITES_KEY, "17"); + properties.put(THREADCOUNTCLASSES_KEY, "34"); + properties.put(THREADCOUNTMETHODS_KEY, "49"); + JUnitCoreParameters params = new JUnitCoreParameters(properties); + Concurrency concurrency = resolveConcurrency(params, null); + assertTrue(params.isParallelSuites()); + assertTrue(params.isParallelClasses()); + assertTrue(params.isParallelMethods()); + assertThat(concurrency.capacity, is(3 * cpu)); + int concurrentSuites = (int) (0.17d * concurrency.capacity); + int concurrentClasses = (int) (0.34d * concurrency.capacity); + assertThat(concurrency.suites, is(concurrentSuites)); + assertThat(concurrency.classes, is(concurrentClasses)); + assertThat(concurrency.methods, is(concurrency.capacity - concurrentSuites - concurrentClasses)); } @Theory - public void reusableThreadCountSuitesAndClasses( int cpu ) throws TestSetFailedException - { + public void reusableThreadCountSuitesAndClasses(int cpu) throws TestSetFailedException { // 4 * cpu to 5 * cpu threads to run test classes - ParallelComputerUtil.overrideAvailableProcessors( cpu ); + ParallelComputerUtil.overrideAvailableProcessors(cpu); Map properties = new HashMap<>(); - properties.put( PARALLEL_KEY, "suitesAndClasses" ); - properties.put( THREADCOUNT_KEY, "6" ); - properties.put( THREADCOUNTSUITES_KEY, "2" ); - JUnitCoreParameters params = new JUnitCoreParameters( properties ); - Concurrency concurrency = resolveConcurrency( params, null ); - assertTrue( params.isParallelSuites() ); - assertTrue( params.isParallelClasses() ); - assertFalse( params.isParallelMethods() ); - assertThat( concurrency.capacity, is( 6 * cpu ) ); - assertThat( concurrency.suites, is( 2 * cpu ) ); - assertThat( concurrency.classes, is( Integer.MAX_VALUE ) ); - assertThat( concurrency.methods, is( 0 ) ); + properties.put(PARALLEL_KEY, "suitesAndClasses"); + properties.put(THREADCOUNT_KEY, "6"); + properties.put(THREADCOUNTSUITES_KEY, "2"); + JUnitCoreParameters params = new JUnitCoreParameters(properties); + Concurrency concurrency = resolveConcurrency(params, null); + assertTrue(params.isParallelSuites()); + assertTrue(params.isParallelClasses()); + assertFalse(params.isParallelMethods()); + assertThat(concurrency.capacity, is(6 * cpu)); + assertThat(concurrency.suites, is(2 * cpu)); + assertThat(concurrency.classes, is(Integer.MAX_VALUE)); + assertThat(concurrency.methods, is(0)); } @Theory - public void reusableThreadCountSuitesAndMethods( int cpu ) throws TestSetFailedException - { + public void reusableThreadCountSuitesAndMethods(int cpu) throws TestSetFailedException { // 4 * cpu to 5 * cpu threads to run test methods - ParallelComputerUtil.overrideAvailableProcessors( cpu ); + ParallelComputerUtil.overrideAvailableProcessors(cpu); Map properties = new HashMap<>(); - properties.put( PARALLEL_KEY, "suitesAndMethods" ); - properties.put( THREADCOUNT_KEY, "6" ); - properties.put( THREADCOUNTSUITES_KEY, "2" ); - JUnitCoreParameters params = new JUnitCoreParameters( properties ); - Concurrency concurrency = resolveConcurrency( params, null ); - assertTrue( params.isParallelSuites() ); - assertFalse( params.isParallelClasses() ); - assertTrue( params.isParallelMethods() ); - assertThat( concurrency.capacity, is( 6 * cpu ) ); - assertThat( concurrency.suites, is( 2 * cpu ) ); - assertThat( concurrency.classes, is( 0 ) ); - assertThat( concurrency.methods, is( Integer.MAX_VALUE ) ); + properties.put(PARALLEL_KEY, "suitesAndMethods"); + properties.put(THREADCOUNT_KEY, "6"); + properties.put(THREADCOUNTSUITES_KEY, "2"); + JUnitCoreParameters params = new JUnitCoreParameters(properties); + Concurrency concurrency = resolveConcurrency(params, null); + assertTrue(params.isParallelSuites()); + assertFalse(params.isParallelClasses()); + assertTrue(params.isParallelMethods()); + assertThat(concurrency.capacity, is(6 * cpu)); + assertThat(concurrency.suites, is(2 * cpu)); + assertThat(concurrency.classes, is(0)); + assertThat(concurrency.methods, is(Integer.MAX_VALUE)); } @Theory - public void reusableThreadCountClassesAndMethods( int cpu ) throws TestSetFailedException - { + public void reusableThreadCountClassesAndMethods(int cpu) throws TestSetFailedException { // 4 * cpu to 5 * cpu threads to run test methods - ParallelComputerUtil.overrideAvailableProcessors( cpu ); + ParallelComputerUtil.overrideAvailableProcessors(cpu); Map properties = new HashMap<>(); - properties.put( PARALLEL_KEY, "classesAndMethods" ); - properties.put( THREADCOUNT_KEY, "6" ); - properties.put( THREADCOUNTCLASSES_KEY, "2" ); - JUnitCoreParameters params = new JUnitCoreParameters( properties ); - Concurrency concurrency = resolveConcurrency( params, null ); - assertFalse( params.isParallelSuites() ); - assertTrue( params.isParallelClasses() ); - assertTrue( params.isParallelMethods() ); - assertThat( concurrency.capacity, is( 6 * cpu ) ); - assertThat( concurrency.suites, is( 0 ) ); - assertThat( concurrency.classes, is( 2 * cpu ) ); - assertThat( concurrency.methods, is( Integer.MAX_VALUE ) ); + properties.put(PARALLEL_KEY, "classesAndMethods"); + properties.put(THREADCOUNT_KEY, "6"); + properties.put(THREADCOUNTCLASSES_KEY, "2"); + JUnitCoreParameters params = new JUnitCoreParameters(properties); + Concurrency concurrency = resolveConcurrency(params, null); + assertFalse(params.isParallelSuites()); + assertTrue(params.isParallelClasses()); + assertTrue(params.isParallelMethods()); + assertThat(concurrency.capacity, is(6 * cpu)); + assertThat(concurrency.suites, is(0)); + assertThat(concurrency.classes, is(2 * cpu)); + assertThat(concurrency.methods, is(Integer.MAX_VALUE)); } @Theory - public void reusableThreadCountAll( int cpu ) throws TestSetFailedException - { + public void reusableThreadCountAll(int cpu) throws TestSetFailedException { // 8 * cpu to 13 * cpu threads to run test methods - ParallelComputerUtil.overrideAvailableProcessors( cpu ); + ParallelComputerUtil.overrideAvailableProcessors(cpu); Map properties = new HashMap<>(); - properties.put( PARALLEL_KEY, "all" ); - properties.put( THREADCOUNT_KEY, "14" ); - properties.put( THREADCOUNTSUITES_KEY, "2" ); - properties.put( THREADCOUNTCLASSES_KEY, "4" ); - JUnitCoreParameters params = new JUnitCoreParameters( properties ); - Concurrency concurrency = resolveConcurrency( params, null ); - assertTrue( params.isParallelSuites() ); - assertTrue( params.isParallelClasses() ); - assertTrue( params.isParallelMethods() ); - assertThat( concurrency.capacity, is( 14 * cpu ) ); - assertThat( concurrency.suites, is( 2 * cpu ) ); - assertThat( concurrency.classes, is( 4 * cpu ) ); - assertThat( concurrency.methods, is( Integer.MAX_VALUE ) ); + properties.put(PARALLEL_KEY, "all"); + properties.put(THREADCOUNT_KEY, "14"); + properties.put(THREADCOUNTSUITES_KEY, "2"); + properties.put(THREADCOUNTCLASSES_KEY, "4"); + JUnitCoreParameters params = new JUnitCoreParameters(properties); + Concurrency concurrency = resolveConcurrency(params, null); + assertTrue(params.isParallelSuites()); + assertTrue(params.isParallelClasses()); + assertTrue(params.isParallelMethods()); + assertThat(concurrency.capacity, is(14 * cpu)); + assertThat(concurrency.suites, is(2 * cpu)); + assertThat(concurrency.classes, is(4 * cpu)); + assertThat(concurrency.methods, is(Integer.MAX_VALUE)); } @Theory - public void suites( int cpu ) throws TestSetFailedException - { - ParallelComputerUtil.overrideAvailableProcessors( cpu ); + public void suites(int cpu) throws TestSetFailedException { + ParallelComputerUtil.overrideAvailableProcessors(cpu); Map properties = new HashMap<>(); - properties.put( PARALLEL_KEY, "suites" ); - properties.put( THREADCOUNTSUITES_KEY, "5" ); - JUnitCoreParameters params = new JUnitCoreParameters( properties ); - Concurrency concurrency = resolveConcurrency( params, null ); - assertTrue( params.isParallelSuites() ); - assertFalse( params.isParallelClasses() ); - assertFalse( params.isParallelMethods() ); - assertThat( concurrency.capacity, is( 5 * cpu ) ); - assertThat( concurrency.suites, is( 5 * cpu ) ); - assertThat( concurrency.classes, is( 0 ) ); - assertThat( concurrency.methods, is( 0 ) ); + properties.put(PARALLEL_KEY, "suites"); + properties.put(THREADCOUNTSUITES_KEY, "5"); + JUnitCoreParameters params = new JUnitCoreParameters(properties); + Concurrency concurrency = resolveConcurrency(params, null); + assertTrue(params.isParallelSuites()); + assertFalse(params.isParallelClasses()); + assertFalse(params.isParallelMethods()); + assertThat(concurrency.capacity, is(5 * cpu)); + assertThat(concurrency.suites, is(5 * cpu)); + assertThat(concurrency.classes, is(0)); + assertThat(concurrency.methods, is(0)); } @Theory - public void classes( int cpu ) throws TestSetFailedException - { - ParallelComputerUtil.overrideAvailableProcessors( cpu ); + public void classes(int cpu) throws TestSetFailedException { + ParallelComputerUtil.overrideAvailableProcessors(cpu); Map properties = new HashMap<>(); - properties.put( PARALLEL_KEY, "classes" ); - properties.put( THREADCOUNTCLASSES_KEY, "5" ); - JUnitCoreParameters params = new JUnitCoreParameters( properties ); - Concurrency concurrency = resolveConcurrency( params, null ); - assertFalse( params.isParallelSuites() ); - assertTrue( params.isParallelClasses() ); - assertFalse( params.isParallelMethods() ); - assertThat( concurrency.capacity, is( 5 * cpu ) ); - assertThat( concurrency.suites, is( 0 ) ); - assertThat( concurrency.classes, is( 5 * cpu ) ); - assertThat( concurrency.methods, is( 0 ) ); + properties.put(PARALLEL_KEY, "classes"); + properties.put(THREADCOUNTCLASSES_KEY, "5"); + JUnitCoreParameters params = new JUnitCoreParameters(properties); + Concurrency concurrency = resolveConcurrency(params, null); + assertFalse(params.isParallelSuites()); + assertTrue(params.isParallelClasses()); + assertFalse(params.isParallelMethods()); + assertThat(concurrency.capacity, is(5 * cpu)); + assertThat(concurrency.suites, is(0)); + assertThat(concurrency.classes, is(5 * cpu)); + assertThat(concurrency.methods, is(0)); } @Theory - public void methods( int cpu ) throws TestSetFailedException - { - ParallelComputerUtil.overrideAvailableProcessors( cpu ); + public void methods(int cpu) throws TestSetFailedException { + ParallelComputerUtil.overrideAvailableProcessors(cpu); Map properties = new HashMap<>(); - properties.put( PARALLEL_KEY, "methods" ); - properties.put( THREADCOUNTMETHODS_KEY, "5" ); - JUnitCoreParameters params = new JUnitCoreParameters( properties ); - Concurrency concurrency = resolveConcurrency( params, null ); - assertFalse( params.isParallelSuites() ); - assertFalse( params.isParallelClasses() ); - assertTrue( params.isParallelMethods() ); - assertThat( concurrency.capacity, is( 5 * cpu ) ); - assertThat( concurrency.suites, is( 0 ) ); - assertThat( concurrency.classes, is( 0 ) ); - assertThat( concurrency.methods, is( 5 * cpu ) ); + properties.put(PARALLEL_KEY, "methods"); + properties.put(THREADCOUNTMETHODS_KEY, "5"); + JUnitCoreParameters params = new JUnitCoreParameters(properties); + Concurrency concurrency = resolveConcurrency(params, null); + assertFalse(params.isParallelSuites()); + assertFalse(params.isParallelClasses()); + assertTrue(params.isParallelMethods()); + assertThat(concurrency.capacity, is(5 * cpu)); + assertThat(concurrency.suites, is(0)); + assertThat(concurrency.classes, is(0)); + assertThat(concurrency.methods, is(5 * cpu)); } @Theory - public void suitesAndClasses( int cpu ) throws TestSetFailedException - { - ParallelComputerUtil.overrideAvailableProcessors( cpu ); + public void suitesAndClasses(int cpu) throws TestSetFailedException { + ParallelComputerUtil.overrideAvailableProcessors(cpu); Map properties = new HashMap<>(); - properties.put( PARALLEL_KEY, "suitesAndClasses" ); - properties.put( THREADCOUNTSUITES_KEY, "5" ); - properties.put( THREADCOUNTCLASSES_KEY, "15" ); - JUnitCoreParameters params = new JUnitCoreParameters( properties ); - Concurrency concurrency = resolveConcurrency( params, null ); - assertTrue( params.isParallelSuites() ); - assertTrue( params.isParallelClasses() ); - assertFalse( params.isParallelMethods() ); - assertThat( concurrency.capacity, is( 20 * cpu ) ); - assertThat( concurrency.suites, is( 5 * cpu ) ); - assertThat( concurrency.classes, is( 15 * cpu ) ); - assertThat( concurrency.methods, is( 0 ) ); + properties.put(PARALLEL_KEY, "suitesAndClasses"); + properties.put(THREADCOUNTSUITES_KEY, "5"); + properties.put(THREADCOUNTCLASSES_KEY, "15"); + JUnitCoreParameters params = new JUnitCoreParameters(properties); + Concurrency concurrency = resolveConcurrency(params, null); + assertTrue(params.isParallelSuites()); + assertTrue(params.isParallelClasses()); + assertFalse(params.isParallelMethods()); + assertThat(concurrency.capacity, is(20 * cpu)); + assertThat(concurrency.suites, is(5 * cpu)); + assertThat(concurrency.classes, is(15 * cpu)); + assertThat(concurrency.methods, is(0)); // Warning: this case works but is not enabled in AbstractSurefireMojo // Instead use the 'useUnlimitedThreads' parameter. properties = new HashMap<>(); - properties.put( PARALLEL_KEY, "suitesAndClasses" ); - properties.put( THREADCOUNTSUITES_KEY, "5" ); - params = new JUnitCoreParameters( properties ); - concurrency = resolveConcurrency( params, null ); - assertTrue( params.isParallelSuites() ); - assertTrue( params.isParallelClasses() ); - assertFalse( params.isParallelMethods() ); - assertThat( concurrency.capacity, is( Integer.MAX_VALUE ) ); - assertThat( concurrency.suites, is( 5 * cpu ) ); - assertThat( concurrency.classes, is( Integer.MAX_VALUE ) ); - assertThat( concurrency.methods, is( 0 ) ); + properties.put(PARALLEL_KEY, "suitesAndClasses"); + properties.put(THREADCOUNTSUITES_KEY, "5"); + params = new JUnitCoreParameters(properties); + concurrency = resolveConcurrency(params, null); + assertTrue(params.isParallelSuites()); + assertTrue(params.isParallelClasses()); + assertFalse(params.isParallelMethods()); + assertThat(concurrency.capacity, is(Integer.MAX_VALUE)); + assertThat(concurrency.suites, is(5 * cpu)); + assertThat(concurrency.classes, is(Integer.MAX_VALUE)); + assertThat(concurrency.methods, is(0)); } @Theory - public void suitesAndMethods( int cpu ) throws TestSetFailedException - { - ParallelComputerUtil.overrideAvailableProcessors( cpu ); + public void suitesAndMethods(int cpu) throws TestSetFailedException { + ParallelComputerUtil.overrideAvailableProcessors(cpu); Map properties = new HashMap<>(); - properties.put( PARALLEL_KEY, "suitesAndMethods" ); - properties.put( THREADCOUNTSUITES_KEY, "5" ); - properties.put( THREADCOUNTMETHODS_KEY, "15" ); - JUnitCoreParameters params = new JUnitCoreParameters( properties ); - Concurrency concurrency = resolveConcurrency( params, null ); - assertTrue( params.isParallelSuites() ); - assertFalse( params.isParallelClasses() ); - assertTrue( params.isParallelMethods() ); - assertThat( concurrency.capacity, is( 20 * cpu ) ); - assertThat( concurrency.suites, is( 5 * cpu ) ); - assertThat( concurrency.classes, is( 0 ) ); - assertThat( concurrency.methods, is( 15 * cpu ) ); + properties.put(PARALLEL_KEY, "suitesAndMethods"); + properties.put(THREADCOUNTSUITES_KEY, "5"); + properties.put(THREADCOUNTMETHODS_KEY, "15"); + JUnitCoreParameters params = new JUnitCoreParameters(properties); + Concurrency concurrency = resolveConcurrency(params, null); + assertTrue(params.isParallelSuites()); + assertFalse(params.isParallelClasses()); + assertTrue(params.isParallelMethods()); + assertThat(concurrency.capacity, is(20 * cpu)); + assertThat(concurrency.suites, is(5 * cpu)); + assertThat(concurrency.classes, is(0)); + assertThat(concurrency.methods, is(15 * cpu)); // Warning: this case works but is not enabled in AbstractSurefireMojo // Instead use the 'useUnlimitedThreads' parameter. properties = new HashMap<>(); - properties.put( PARALLEL_KEY, "suitesAndMethods" ); - properties.put( THREADCOUNTSUITES_KEY, "5" ); - params = new JUnitCoreParameters( properties ); - concurrency = resolveConcurrency( params, null ); - assertTrue( params.isParallelSuites() ); - assertFalse( params.isParallelClasses() ); - assertTrue( params.isParallelMethods() ); - assertThat( concurrency.capacity, is( Integer.MAX_VALUE ) ); - assertThat( concurrency.suites, is( 5 * cpu ) ); - assertThat( concurrency.classes, is( 0 ) ); - assertThat( concurrency.methods, is( Integer.MAX_VALUE ) ); + properties.put(PARALLEL_KEY, "suitesAndMethods"); + properties.put(THREADCOUNTSUITES_KEY, "5"); + params = new JUnitCoreParameters(properties); + concurrency = resolveConcurrency(params, null); + assertTrue(params.isParallelSuites()); + assertFalse(params.isParallelClasses()); + assertTrue(params.isParallelMethods()); + assertThat(concurrency.capacity, is(Integer.MAX_VALUE)); + assertThat(concurrency.suites, is(5 * cpu)); + assertThat(concurrency.classes, is(0)); + assertThat(concurrency.methods, is(Integer.MAX_VALUE)); } @Theory - public void classesAndMethods( int cpu ) throws TestSetFailedException - { - ParallelComputerUtil.overrideAvailableProcessors( cpu ); + public void classesAndMethods(int cpu) throws TestSetFailedException { + ParallelComputerUtil.overrideAvailableProcessors(cpu); Map properties = new HashMap<>(); - properties.put( PARALLEL_KEY, "classesAndMethods" ); - properties.put( THREADCOUNTCLASSES_KEY, "5" ); - properties.put( THREADCOUNTMETHODS_KEY, "15" ); - JUnitCoreParameters params = new JUnitCoreParameters( properties ); - Concurrency concurrency = resolveConcurrency( params, null ); - assertFalse( params.isParallelSuites() ); - assertTrue( params.isParallelClasses() ); - assertTrue( params.isParallelMethods() ); - assertThat( concurrency.capacity, is( 20 * cpu ) ); - assertThat( concurrency.suites, is( 0 ) ); - assertThat( concurrency.classes, is( 5 * cpu ) ); - assertThat( concurrency.methods, is( 15 * cpu ) ); + properties.put(PARALLEL_KEY, "classesAndMethods"); + properties.put(THREADCOUNTCLASSES_KEY, "5"); + properties.put(THREADCOUNTMETHODS_KEY, "15"); + JUnitCoreParameters params = new JUnitCoreParameters(properties); + Concurrency concurrency = resolveConcurrency(params, null); + assertFalse(params.isParallelSuites()); + assertTrue(params.isParallelClasses()); + assertTrue(params.isParallelMethods()); + assertThat(concurrency.capacity, is(20 * cpu)); + assertThat(concurrency.suites, is(0)); + assertThat(concurrency.classes, is(5 * cpu)); + assertThat(concurrency.methods, is(15 * cpu)); // Warning: this case works but is not enabled in AbstractSurefireMojo // Instead use the 'useUnlimitedThreads' parameter. properties = new HashMap<>(); - properties.put( PARALLEL_KEY, "classesAndMethods" ); - properties.put( THREADCOUNTCLASSES_KEY, "5" ); - params = new JUnitCoreParameters( properties ); - concurrency = resolveConcurrency( params, null ); - assertFalse( params.isParallelSuites() ); - assertTrue( params.isParallelClasses() ); - assertTrue( params.isParallelMethods() ); - assertThat( concurrency.capacity, is( Integer.MAX_VALUE ) ); - assertThat( concurrency.suites, is( 0 ) ); - assertThat( concurrency.classes, is( 5 * cpu ) ); - assertThat( concurrency.methods, is( Integer.MAX_VALUE ) ); + properties.put(PARALLEL_KEY, "classesAndMethods"); + properties.put(THREADCOUNTCLASSES_KEY, "5"); + params = new JUnitCoreParameters(properties); + concurrency = resolveConcurrency(params, null); + assertFalse(params.isParallelSuites()); + assertTrue(params.isParallelClasses()); + assertTrue(params.isParallelMethods()); + assertThat(concurrency.capacity, is(Integer.MAX_VALUE)); + assertThat(concurrency.suites, is(0)); + assertThat(concurrency.classes, is(5 * cpu)); + assertThat(concurrency.methods, is(Integer.MAX_VALUE)); } @Theory - public void all( int cpu ) throws TestSetFailedException - { - ParallelComputerUtil.overrideAvailableProcessors( cpu ); + public void all(int cpu) throws TestSetFailedException { + ParallelComputerUtil.overrideAvailableProcessors(cpu); Map properties = new HashMap<>(); - properties.put( PARALLEL_KEY, "all" ); - properties.put( THREADCOUNTSUITES_KEY, "5" ); - properties.put( THREADCOUNTCLASSES_KEY, "15" ); - properties.put( THREADCOUNTMETHODS_KEY, "30" ); - JUnitCoreParameters params = new JUnitCoreParameters( properties ); - Concurrency concurrency = resolveConcurrency( params, null ); - assertTrue( params.isParallelSuites() ); - assertTrue( params.isParallelClasses() ); - assertTrue( params.isParallelMethods() ); - assertThat( concurrency.capacity, is( 50 * cpu ) ); - assertThat( concurrency.suites, is( 5 * cpu ) ); - assertThat( concurrency.classes, is( 15 * cpu ) ); - assertThat( concurrency.methods, is( 30 * cpu ) ); + properties.put(PARALLEL_KEY, "all"); + properties.put(THREADCOUNTSUITES_KEY, "5"); + properties.put(THREADCOUNTCLASSES_KEY, "15"); + properties.put(THREADCOUNTMETHODS_KEY, "30"); + JUnitCoreParameters params = new JUnitCoreParameters(properties); + Concurrency concurrency = resolveConcurrency(params, null); + assertTrue(params.isParallelSuites()); + assertTrue(params.isParallelClasses()); + assertTrue(params.isParallelMethods()); + assertThat(concurrency.capacity, is(50 * cpu)); + assertThat(concurrency.suites, is(5 * cpu)); + assertThat(concurrency.classes, is(15 * cpu)); + assertThat(concurrency.methods, is(30 * cpu)); // Warning: these cases work but they are not enabled in AbstractSurefireMojo // Instead use the 'useUnlimitedThreads' parameter. properties = new HashMap<>(); - properties.put( PARALLEL_KEY, "all" ); - properties.put( THREADCOUNTSUITES_KEY, "5" ); - properties.put( THREADCOUNTCLASSES_KEY, "15" ); - params = new JUnitCoreParameters( properties ); - concurrency = resolveConcurrency( params, null ); - assertTrue( params.isParallelSuites() ); - assertTrue( params.isParallelClasses() ); - assertTrue( params.isParallelMethods() ); - assertThat( concurrency.capacity, is( Integer.MAX_VALUE ) ); - assertThat( concurrency.suites, is( 5 * cpu ) ); - assertThat( concurrency.classes, is( 15 * cpu ) ); - assertThat( concurrency.methods, is( Integer.MAX_VALUE ) ); + properties.put(PARALLEL_KEY, "all"); + properties.put(THREADCOUNTSUITES_KEY, "5"); + properties.put(THREADCOUNTCLASSES_KEY, "15"); + params = new JUnitCoreParameters(properties); + concurrency = resolveConcurrency(params, null); + assertTrue(params.isParallelSuites()); + assertTrue(params.isParallelClasses()); + assertTrue(params.isParallelMethods()); + assertThat(concurrency.capacity, is(Integer.MAX_VALUE)); + assertThat(concurrency.suites, is(5 * cpu)); + assertThat(concurrency.classes, is(15 * cpu)); + assertThat(concurrency.methods, is(Integer.MAX_VALUE)); properties = new HashMap<>(); - properties.put( PARALLEL_KEY, "all" ); - properties.put( THREADCOUNTCLASSES_KEY, "15" ); - params = new JUnitCoreParameters( properties ); - concurrency = resolveConcurrency( params, null ); - assertTrue( params.isParallelSuites() ); - assertTrue( params.isParallelClasses() ); - assertTrue( params.isParallelMethods() ); - assertThat( concurrency.capacity, is( Integer.MAX_VALUE ) ); - assertThat( concurrency.suites, is( Integer.MAX_VALUE ) ); - assertThat( concurrency.classes, is( 15 * cpu ) ); - assertThat( concurrency.methods, is( Integer.MAX_VALUE ) ); + properties.put(PARALLEL_KEY, "all"); + properties.put(THREADCOUNTCLASSES_KEY, "15"); + params = new JUnitCoreParameters(properties); + concurrency = resolveConcurrency(params, null); + assertTrue(params.isParallelSuites()); + assertTrue(params.isParallelClasses()); + assertTrue(params.isParallelMethods()); + assertThat(concurrency.capacity, is(Integer.MAX_VALUE)); + assertThat(concurrency.suites, is(Integer.MAX_VALUE)); + assertThat(concurrency.classes, is(15 * cpu)); + assertThat(concurrency.methods, is(Integer.MAX_VALUE)); } @Test - public void withoutShutdown() - { + public void withoutShutdown() { Map properties = new HashMap<>(); - properties.put( PARALLEL_KEY, "methods" ); - properties.put( THREADCOUNTMETHODS_KEY, "2" ); - JUnitCoreParameters params = new JUnitCoreParameters( properties ); - ParallelComputerBuilder pcBuilder = new ParallelComputerBuilder( LOGGER, params ); + properties.put(PARALLEL_KEY, "methods"); + properties.put(THREADCOUNTMETHODS_KEY, "2"); + JUnitCoreParameters params = new JUnitCoreParameters(properties); + ParallelComputerBuilder pcBuilder = new ParallelComputerBuilder(LOGGER, params); ParallelComputer pc = pcBuilder.buildComputer(); final JUnitCore core = new JUnitCore(); final long t1 = systemMillis(); - final Result result = core.run( pc, TestClass.class ); + final Result result = core.run(pc, TestClass.class); final long t2 = systemMillis(); long timeSpent = t2 - t1; final long deltaTime = 500L; - assertTrue( result.wasSuccessful() ); - assertThat( result.getRunCount(), is( 3 ) ); - assertThat( result.getFailureCount(), is( 0 ) ); - assertThat( result.getIgnoreCount(), is( 0 ) ); - //assertThat( timeSpent, between (timeSpent - deltaTime, timeSpent + deltaTime + 2000L ) ); - assertEquals( 10000L, timeSpent, deltaTime ); + assertTrue(result.wasSuccessful()); + assertThat(result.getRunCount(), is(3)); + assertThat(result.getFailureCount(), is(0)); + assertThat(result.getIgnoreCount(), is(0)); + // assertThat( timeSpent, between (timeSpent - deltaTime, timeSpent + deltaTime + 2000L ) ); + assertEquals(10000L, timeSpent, deltaTime); } @Test - public void shutdown() throws TestSetFailedException - { + public void shutdown() throws TestSetFailedException { // The JUnitCore returns after 2.5s. // The test-methods in TestClass are NOT interrupted, and return normally after 5s. Map properties = new HashMap<>(); - properties.put( PARALLEL_KEY, "methods" ); - properties.put( THREADCOUNTMETHODS_KEY, "2" ); - properties.put( PARALLEL_TIMEOUT_KEY, Double.toString( 2.5d ) ); - JUnitCoreParameters params = new JUnitCoreParameters( properties ); - ParallelComputerBuilder pcBuilder = new ParallelComputerBuilder( LOGGER, params ); + properties.put(PARALLEL_KEY, "methods"); + properties.put(THREADCOUNTMETHODS_KEY, "2"); + properties.put(PARALLEL_TIMEOUT_KEY, Double.toString(2.5d)); + JUnitCoreParameters params = new JUnitCoreParameters(properties); + ParallelComputerBuilder pcBuilder = new ParallelComputerBuilder(LOGGER, params); ParallelComputer pc = pcBuilder.buildComputer(); final JUnitCore core = new JUnitCore(); final long t1 = systemMillis(); - core.run( pc, TestClass.class ); + core.run(pc, TestClass.class); final long t2 = systemMillis(); final long timeSpent = t2 - t1; final long deltaTime = 500L; - assertEquals( 5000L, timeSpent, deltaTime ); + assertEquals(5000L, timeSpent, deltaTime); String description = pc.describeElapsedTimeout(); - assertTrue( description.contains( "The test run has finished abruptly after timeout of 2.5 seconds." ) ); - assertTrue( description.contains( - "These tests were executed in prior to the shutdown operation:\n" + TestClass.class.getName() ) ); + assertTrue(description.contains("The test run has finished abruptly after timeout of 2.5 seconds.")); + assertTrue(description.contains( + "These tests were executed in prior to the shutdown operation:\n" + TestClass.class.getName())); } @Test - public void forcedShutdown() throws TestSetFailedException - { + public void forcedShutdown() throws TestSetFailedException { // The JUnitCore returns after 2.5s, and the test-methods in TestClass are interrupted. Map properties = new HashMap<>(); - properties.put( PARALLEL_KEY, "methods" ); - properties.put( THREADCOUNTMETHODS_KEY, "2" ); - properties.put( PARALLEL_TIMEOUTFORCED_KEY, Double.toString( 2.5d ) ); - JUnitCoreParameters params = new JUnitCoreParameters( properties ); - ParallelComputerBuilder pcBuilder = new ParallelComputerBuilder( LOGGER, params ); + properties.put(PARALLEL_KEY, "methods"); + properties.put(THREADCOUNTMETHODS_KEY, "2"); + properties.put(PARALLEL_TIMEOUTFORCED_KEY, Double.toString(2.5d)); + JUnitCoreParameters params = new JUnitCoreParameters(properties); + ParallelComputerBuilder pcBuilder = new ParallelComputerBuilder(LOGGER, params); ParallelComputer pc = pcBuilder.buildComputer(); final JUnitCore core = new JUnitCore(); final long t1 = systemMillis(); - core.run( pc, TestClass.class ); + core.run(pc, TestClass.class); final long t2 = systemMillis(); final long timeSpent = t2 - t1; final long deltaTime = 500L; - assertEquals( 2500L, timeSpent, deltaTime ); + assertEquals(2500L, timeSpent, deltaTime); String description = pc.describeElapsedTimeout(); - assertTrue( description.contains( "The test run has finished abruptly after timeout of 2.5 seconds." ) ); - assertTrue( description.contains( - "These tests were executed in prior to the shutdown operation:\n" + TestClass.class.getName() ) ); + assertTrue(description.contains("The test run has finished abruptly after timeout of 2.5 seconds.")); + assertTrue(description.contains( + "These tests were executed in prior to the shutdown operation:\n" + TestClass.class.getName())); } @Test - public void timeoutAndForcedShutdown() throws TestSetFailedException - { + public void timeoutAndForcedShutdown() throws TestSetFailedException { // The JUnitCore returns after 3.5s and the test-methods in TestClass are timed out after 2.5s. // No new test methods are scheduled for execution after 2.5s. // Interruption of test methods after 3.5s. Map properties = new HashMap<>(); - properties.put( PARALLEL_KEY, "methods" ); - properties.put( THREADCOUNTMETHODS_KEY, "2" ); - properties.put( PARALLEL_TIMEOUT_KEY, Double.toString( 2.5d ) ); - properties.put( PARALLEL_TIMEOUTFORCED_KEY, Double.toString( 3.5d ) ); - JUnitCoreParameters params = new JUnitCoreParameters( properties ); - ParallelComputerBuilder pcBuilder = new ParallelComputerBuilder( LOGGER, params ); + properties.put(PARALLEL_KEY, "methods"); + properties.put(THREADCOUNTMETHODS_KEY, "2"); + properties.put(PARALLEL_TIMEOUT_KEY, Double.toString(2.5d)); + properties.put(PARALLEL_TIMEOUTFORCED_KEY, Double.toString(3.5d)); + JUnitCoreParameters params = new JUnitCoreParameters(properties); + ParallelComputerBuilder pcBuilder = new ParallelComputerBuilder(LOGGER, params); ParallelComputer pc = pcBuilder.buildComputer(); final JUnitCore core = new JUnitCore(); final long t1 = systemMillis(); - core.run( pc, TestClass.class ); + core.run(pc, TestClass.class); final long t2 = systemMillis(); final long timeSpent = t2 - t1; final long deltaTime = 500L; - assertEquals( 3500L, timeSpent, deltaTime ); + assertEquals(3500L, timeSpent, deltaTime); String description = pc.describeElapsedTimeout(); - assertTrue( description.contains( "The test run has finished abruptly after timeout of 2.5 seconds." ) ); - assertTrue( description.contains( - "These tests were executed in prior to the shutdown operation:\n" + TestClass.class.getName() ) ); + assertTrue(description.contains("The test run has finished abruptly after timeout of 2.5 seconds.")); + assertTrue(description.contains( + "These tests were executed in prior to the shutdown operation:\n" + TestClass.class.getName())); } @Test - public void forcedTimeoutAndShutdown() throws Exception - { + public void forcedTimeoutAndShutdown() throws Exception { // The JUnitCore returns after 3.5s and the test-methods in TestClass are interrupted after 3.5s. Map properties = new HashMap<>(); - properties.put( PARALLEL_KEY, "methods" ); - properties.put( THREADCOUNTMETHODS_KEY, "2" ); - properties.put( PARALLEL_TIMEOUTFORCED_KEY, Double.toString( 3.5d ) ); - properties.put( PARALLEL_TIMEOUT_KEY, Double.toString( 4.0d ) ); - JUnitCoreParameters params = new JUnitCoreParameters( properties ); - ParallelComputerBuilder pcBuilder = new ParallelComputerBuilder( LOGGER, params ); + properties.put(PARALLEL_KEY, "methods"); + properties.put(THREADCOUNTMETHODS_KEY, "2"); + properties.put(PARALLEL_TIMEOUTFORCED_KEY, Double.toString(3.5d)); + properties.put(PARALLEL_TIMEOUT_KEY, Double.toString(4.0d)); + JUnitCoreParameters params = new JUnitCoreParameters(properties); + ParallelComputerBuilder pcBuilder = new ParallelComputerBuilder(LOGGER, params); ParallelComputer pc = pcBuilder.buildComputer(); final JUnitCore core = new JUnitCore(); final long t1 = systemMillis(); - core.run( pc, TestClass.class ); + core.run(pc, TestClass.class); final long t2 = systemMillis(); final long timeSpent = t2 - t1; final long deltaTime = 500L; - assertEquals( 3500L, timeSpent, deltaTime ); + assertEquals(3500L, timeSpent, deltaTime); String description = pc.describeElapsedTimeout(); - assertTrue( description.contains( "The test run has finished abruptly after timeout of 3.5 seconds." ) ); - assertTrue( description.contains( - "These tests were executed in prior to the shutdown operation:\n" + TestClass.class.getName() ) ); + assertTrue(description.contains("The test run has finished abruptly after timeout of 3.5 seconds.")); + assertTrue(description.contains( + "These tests were executed in prior to the shutdown operation:\n" + TestClass.class.getName())); } /** * */ - public static class TestClass - { + public static class TestClass { @Test - public void a() throws InterruptedException - { + public void a() throws InterruptedException { long t1 = systemMillis(); - try - { - Thread.sleep( 5000L ); - } - finally - { - System.out.println( getClass().getSimpleName() + "#a() spent " + ( systemMillis() - t1 ) ); + try { + Thread.sleep(5000L); + } finally { + System.out.println(getClass().getSimpleName() + "#a() spent " + (systemMillis() - t1)); } } @Test - public void b() throws InterruptedException - { + public void b() throws InterruptedException { long t1 = systemMillis(); - try - { - Thread.sleep( 5000L ); - } - finally - { - System.out.println( getClass().getSimpleName() + "#b() spent " + ( systemMillis() - t1 ) ); + try { + Thread.sleep(5000L); + } finally { + System.out.println(getClass().getSimpleName() + "#b() spent " + (systemMillis() - t1)); } } @Test - public void c() throws InterruptedException - { + public void c() throws InterruptedException { long t1 = systemMillis(); - try - { - Thread.sleep( 5000L ); - } - finally - { - System.out.println( getClass().getSimpleName() + "#c() spent " + ( systemMillis() - t1 ) ); + try { + Thread.sleep(5000L); + } finally { + System.out.println(getClass().getSimpleName() + "#c() spent " + (systemMillis() - t1)); } } } - private static long systemMillis() - { - return TimeUnit.NANOSECONDS.toMillis( System.nanoTime() ); + private static long systemMillis() { + return TimeUnit.NANOSECONDS.toMillis(System.nanoTime()); } } diff --git a/surefire-providers/surefire-junit47/src/test/java/org/apache/maven/surefire/junitcore/pc/RangeMatcher.java b/surefire-providers/surefire-junit47/src/test/java/org/apache/maven/surefire/junitcore/pc/RangeMatcher.java index 0ee8033fd3..1a5e35a6c5 100644 --- a/surefire-providers/surefire-junit47/src/test/java/org/apache/maven/surefire/junitcore/pc/RangeMatcher.java +++ b/surefire-providers/surefire-junit47/src/test/java/org/apache/maven/surefire/junitcore/pc/RangeMatcher.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.junitcore.pc; /* @@ -27,34 +45,28 @@ * @author Tibor Digana (tibor17) * @since 2.16 */ -final class RangeMatcher - extends BaseMatcher -{ +final class RangeMatcher extends BaseMatcher { private final long from; private final long to; - private RangeMatcher( long from, long to ) - { + private RangeMatcher(long from, long to) { this.from = from; this.to = to; } - public static Matcher between( long from, long to ) - { - return new RangeMatcher( from, to ); + public static Matcher between(long from, long to) { + return new RangeMatcher(from, to); } @Override - public void describeTo( Description description ) - { - description.appendValueList( "between ", " and ", "", from, to ); + public void describeTo(Description description) { + description.appendValueList("between ", " and ", "", from, to); } @Override - public boolean matches( Object o ) - { + public boolean matches(Object o) { long actual = (Long) o; return actual >= from && actual <= to; } -} \ No newline at end of file +} diff --git a/surefire-providers/surefire-junit47/src/test/java/org/apache/maven/surefire/junitcore/pc/SchedulingStrategiesTest.java b/surefire-providers/surefire-junit47/src/test/java/org/apache/maven/surefire/junitcore/pc/SchedulingStrategiesTest.java index 489868a195..1656733927 100644 --- a/surefire-providers/surefire-junit47/src/test/java/org/apache/maven/surefire/junitcore/pc/SchedulingStrategiesTest.java +++ b/surefire-providers/surefire-junit47/src/test/java/org/apache/maven/surefire/junitcore/pc/SchedulingStrategiesTest.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.junitcore.pc; /* @@ -19,13 +37,13 @@ * under the License. */ -import org.apache.maven.plugin.surefire.log.api.ConsoleLogger; -import org.junit.Test; - import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; +import org.apache.maven.plugin.surefire.log.api.ConsoleLogger; +import org.junit.Test; + import static org.apache.maven.surefire.api.util.internal.DaemonThreadFactory.newDaemonThreadFactory; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; @@ -45,130 +63,117 @@ * @see SchedulingStrategy * @since 2.16 */ -public class SchedulingStrategiesTest -{ +public class SchedulingStrategiesTest { private static final ThreadFactory DAEMON_THREAD_FACTORY = newDaemonThreadFactory(); - private final ConsoleLogger logger = mock( ConsoleLogger.class ); + private final ConsoleLogger logger = mock(ConsoleLogger.class); @Test - public void invokerStrategy() - throws InterruptedException - { - SchedulingStrategy strategy = SchedulingStrategies.createInvokerStrategy( logger ); - assertFalse( strategy.hasSharedThreadPool() ); - assertTrue( strategy.canSchedule() ); + public void invokerStrategy() throws InterruptedException { + SchedulingStrategy strategy = SchedulingStrategies.createInvokerStrategy(logger); + assertFalse(strategy.hasSharedThreadPool()); + assertTrue(strategy.canSchedule()); Task task = new Task(); - strategy.schedule( task ); + strategy.schedule(task); - assertTrue( strategy.canSchedule() ); + assertTrue(strategy.canSchedule()); - assertTrue( task.result ); + assertTrue(task.result); - assertTrue( strategy.finished() ); - assertFalse( strategy.canSchedule() ); + assertTrue(strategy.finished()); + assertFalse(strategy.canSchedule()); } @Test - public void nonSharedPoolStrategy() - throws InterruptedException - { - SchedulingStrategy strategy = SchedulingStrategies.createParallelStrategy( logger, 2 ); - assertFalse( strategy.hasSharedThreadPool() ); - assertTrue( strategy.canSchedule() ); + public void nonSharedPoolStrategy() throws InterruptedException { + SchedulingStrategy strategy = SchedulingStrategies.createParallelStrategy(logger, 2); + assertFalse(strategy.hasSharedThreadPool()); + assertTrue(strategy.canSchedule()); Task task1 = new Task(); Task task2 = new Task(); - strategy.schedule( task1 ); - strategy.schedule( task2 ); + strategy.schedule(task1); + strategy.schedule(task2); - assertTrue( strategy.canSchedule() ); + assertTrue(strategy.canSchedule()); - assertTrue( strategy.finished() ); - assertFalse( strategy.canSchedule() ); + assertTrue(strategy.finished()); + assertFalse(strategy.canSchedule()); - assertTrue( task1.result ); - assertTrue( task2.result ); + assertTrue(task1.result); + assertTrue(task2.result); } - @Test( expected = NullPointerException.class ) - public void sharedPoolStrategyNullPool() - { - SchedulingStrategies.createParallelSharedStrategy( logger, null ); + @Test(expected = NullPointerException.class) + public void sharedPoolStrategyNullPool() { + SchedulingStrategies.createParallelSharedStrategy(logger, null); } @Test - public void sharedPoolStrategy() - throws InterruptedException - { - ExecutorService sharedPool = Executors.newCachedThreadPool( DAEMON_THREAD_FACTORY ); + public void sharedPoolStrategy() throws InterruptedException { + ExecutorService sharedPool = Executors.newCachedThreadPool(DAEMON_THREAD_FACTORY); - SchedulingStrategy strategy1 = SchedulingStrategies.createParallelSharedStrategy( logger, sharedPool ); - assertTrue( strategy1.hasSharedThreadPool() ); - assertTrue( strategy1.canSchedule() ); + SchedulingStrategy strategy1 = SchedulingStrategies.createParallelSharedStrategy(logger, sharedPool); + assertTrue(strategy1.hasSharedThreadPool()); + assertTrue(strategy1.canSchedule()); - SchedulingStrategy strategy2 = SchedulingStrategies.createParallelSharedStrategy( logger, sharedPool ); - assertTrue( strategy2.hasSharedThreadPool() ); - assertTrue( strategy2.canSchedule() ); + SchedulingStrategy strategy2 = SchedulingStrategies.createParallelSharedStrategy(logger, sharedPool); + assertTrue(strategy2.hasSharedThreadPool()); + assertTrue(strategy2.canSchedule()); Task task1 = new Task(); Task task2 = new Task(); Task task3 = new Task(); Task task4 = new Task(); - strategy1.schedule( task1 ); - strategy2.schedule( task2 ); - strategy1.schedule( task3 ); - strategy2.schedule( task4 ); + strategy1.schedule(task1); + strategy2.schedule(task2); + strategy1.schedule(task3); + strategy2.schedule(task4); - assertTrue( strategy1.canSchedule() ); - assertTrue( strategy2.canSchedule() ); + assertTrue(strategy1.canSchedule()); + assertTrue(strategy2.canSchedule()); - assertTrue( strategy1.finished() ); - assertFalse( strategy1.canSchedule() ); + assertTrue(strategy1.finished()); + assertFalse(strategy1.canSchedule()); - assertTrue( strategy2.finished() ); - assertFalse( strategy2.canSchedule() ); + assertTrue(strategy2.finished()); + assertFalse(strategy2.canSchedule()); - assertTrue( task1.result ); - assertTrue( task2.result ); - assertTrue( task3.result ); - assertTrue( task4.result ); + assertTrue(task1.result); + assertTrue(task2.result); + assertTrue(task3.result); + assertTrue(task4.result); } @Test - public void infinitePoolStrategy() - throws InterruptedException - { - SchedulingStrategy strategy = SchedulingStrategies.createParallelStrategyUnbounded( logger ); - assertFalse( strategy.hasSharedThreadPool() ); - assertTrue( strategy.canSchedule() ); + public void infinitePoolStrategy() throws InterruptedException { + SchedulingStrategy strategy = SchedulingStrategies.createParallelStrategyUnbounded(logger); + assertFalse(strategy.hasSharedThreadPool()); + assertTrue(strategy.canSchedule()); Task task1 = new Task(); Task task2 = new Task(); - strategy.schedule( task1 ); - strategy.schedule( task2 ); + strategy.schedule(task1); + strategy.schedule(task2); - assertTrue( strategy.canSchedule() ); + assertTrue(strategy.canSchedule()); - assertTrue( strategy.finished() ); - assertFalse( strategy.canSchedule() ); + assertTrue(strategy.finished()); + assertFalse(strategy.canSchedule()); - assertTrue( task1.result ); - assertTrue( task2.result ); + assertTrue(task1.result); + assertTrue(task2.result); } - static class Task - implements Runnable - { + static class Task implements Runnable { volatile boolean result = false; @Override - public void run() - { + public void run() { result = true; } } diff --git a/surefire-providers/surefire-testng-utils/pom.xml b/surefire-providers/surefire-testng-utils/pom.xml index 80d69339a6..100197bab5 100644 --- a/surefire-providers/surefire-testng-utils/pom.xml +++ b/surefire-providers/surefire-testng-utils/pom.xml @@ -1,4 +1,4 @@ - + + 3.0.0-M7 + - - - surefire-3.0.0-M8 - diff --git a/surefire-providers/surefire-testng-utils/src/main/java/org/apache/maven/surefire/testng/utils/FailFastEventsSingleton.java b/surefire-providers/surefire-testng-utils/src/main/java/org/apache/maven/surefire/testng/utils/FailFastEventsSingleton.java index 523ce8ffbf..de780a052a 100644 --- a/surefire-providers/surefire-testng-utils/src/main/java/org/apache/maven/surefire/testng/utils/FailFastEventsSingleton.java +++ b/surefire-providers/surefire-testng-utils/src/main/java/org/apache/maven/surefire/testng/utils/FailFastEventsSingleton.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.testng.utils; /* @@ -26,28 +44,22 @@ * @author Tibor Digana (tibor17) * @since 2.19 */ -public final class FailFastEventsSingleton -{ +public final class FailFastEventsSingleton { private static final FailFastEventsSingleton INSTANCE = new FailFastEventsSingleton(); private volatile boolean skipAfterFailure; - private FailFastEventsSingleton() - { - } + private FailFastEventsSingleton() {} - public static FailFastEventsSingleton getInstance() - { + public static FailFastEventsSingleton getInstance() { return INSTANCE; } - public boolean isSkipAfterFailure() - { + public boolean isSkipAfterFailure() { return skipAfterFailure; } - public void setSkipOnNextTest() - { + public void setSkipOnNextTest() { this.skipAfterFailure = true; } } diff --git a/surefire-providers/surefire-testng-utils/src/main/java/org/apache/maven/surefire/testng/utils/FailFastListener.java b/surefire-providers/surefire-testng-utils/src/main/java/org/apache/maven/surefire/testng/utils/FailFastListener.java index b85826ff44..b6c873e26a 100644 --- a/surefire-providers/surefire-testng-utils/src/main/java/org/apache/maven/surefire/testng/utils/FailFastListener.java +++ b/surefire-providers/surefire-testng-utils/src/main/java/org/apache/maven/surefire/testng/utils/FailFastListener.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.testng.utils; /* @@ -29,55 +47,33 @@ * @author Tibor Digana (tibor17) * @since 2.19 */ -public class FailFastListener - implements ITestListener -{ +public class FailFastListener implements ITestListener { private final Stoppable stoppable; - public FailFastListener( Stoppable stoppable ) - { + public FailFastListener(Stoppable stoppable) { this.stoppable = stoppable; } @Override - public void onTestStart( ITestResult result ) - { - - } + public void onTestStart(ITestResult result) {} @Override - public void onTestSuccess( ITestResult result ) - { - - } + public void onTestSuccess(ITestResult result) {} @Override - public void onTestFailure( ITestResult result ) - { + public void onTestFailure(ITestResult result) { stoppable.fireStopEvent(); } @Override - public void onTestSkipped( ITestResult result ) - { - - } + public void onTestSkipped(ITestResult result) {} @Override - public void onTestFailedButWithinSuccessPercentage( ITestResult result ) - { - - } + public void onTestFailedButWithinSuccessPercentage(ITestResult result) {} @Override - public void onStart( ITestContext context ) - { - - } + public void onStart(ITestContext context) {} @Override - public void onFinish( ITestContext context ) - { - - } + public void onFinish(ITestContext context) {} } diff --git a/surefire-providers/surefire-testng-utils/src/main/java/org/apache/maven/surefire/testng/utils/FailFastNotifier.java b/surefire-providers/surefire-testng-utils/src/main/java/org/apache/maven/surefire/testng/utils/FailFastNotifier.java index d9d7307759..ffea24de1d 100644 --- a/surefire-providers/surefire-testng-utils/src/main/java/org/apache/maven/surefire/testng/utils/FailFastNotifier.java +++ b/surefire-providers/surefire-testng-utils/src/main/java/org/apache/maven/surefire/testng/utils/FailFastNotifier.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.testng.utils; /* @@ -30,23 +48,16 @@ * @author Tibor Digana (tibor17) * @since 2.19 */ -public class FailFastNotifier - implements IInvokedMethodListener -{ +public class FailFastNotifier implements IInvokedMethodListener { @Override - public void beforeInvocation( IInvokedMethod iInvokedMethod, ITestResult iTestResult ) - { - if ( FailFastEventsSingleton.getInstance().isSkipAfterFailure() ) - { - throw new SkipException( "Skipped after failure. See parameter [skipAfterFailureCount] " - + "in surefire or failsafe plugin." ); + public void beforeInvocation(IInvokedMethod iInvokedMethod, ITestResult iTestResult) { + if (FailFastEventsSingleton.getInstance().isSkipAfterFailure()) { + throw new SkipException("Skipped after failure. See parameter [skipAfterFailureCount] " + + "in surefire or failsafe plugin."); } } @Override - public void afterInvocation( IInvokedMethod iInvokedMethod, ITestResult iTestResult ) - { - - } + public void afterInvocation(IInvokedMethod iInvokedMethod, ITestResult iTestResult) {} } diff --git a/surefire-providers/surefire-testng-utils/src/main/java/org/apache/maven/surefire/testng/utils/GroupMatcherMethodSelector.java b/surefire-providers/surefire-testng-utils/src/main/java/org/apache/maven/surefire/testng/utils/GroupMatcherMethodSelector.java index 3ba0ec1df2..49d6ddc249 100644 --- a/surefire-providers/surefire-testng-utils/src/main/java/org/apache/maven/surefire/testng/utils/GroupMatcherMethodSelector.java +++ b/surefire-providers/surefire-testng-utils/src/main/java/org/apache/maven/surefire/testng/utils/GroupMatcherMethodSelector.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.testng.utils; /* @@ -19,6 +37,10 @@ * under the License. */ +import java.util.HashMap; +import java.util.List; +import java.util.Map; + import org.apache.maven.surefire.group.match.AndGroupMatcher; import org.apache.maven.surefire.group.match.GroupMatcher; import org.apache.maven.surefire.group.match.InverseGroupMatcher; @@ -28,17 +50,11 @@ import org.testng.IMethodSelectorContext; import org.testng.ITestNGMethod; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - /** * Method selector delegating to {@link GroupMatcher} to decide if a method is included or not. * */ -public class GroupMatcherMethodSelector - implements IMethodSelector -{ +public class GroupMatcherMethodSelector implements IMethodSelector { private static final long serialVersionUID = 1L; @@ -47,76 +63,61 @@ public class GroupMatcherMethodSelector private Map answers = new HashMap<>(); @Override - public boolean includeMethod( IMethodSelectorContext context, ITestNGMethod method, boolean isTestMethod ) - { - Boolean result = answers.get( method ); - if ( result != null ) - { + public boolean includeMethod(IMethodSelectorContext context, ITestNGMethod method, boolean isTestMethod) { + Boolean result = answers.get(method); + if (result != null) { return result; } - if ( matcher == null ) - { + if (matcher == null) { return true; } String[] groups = method.getGroups(); - result = matcher.enabled( groups ); - answers.put( method, result ); + result = matcher.enabled(groups); + answers.put(method, result); return result; } @Override - public void setTestMethods( List testMethods ) - { - } + public void setTestMethods(List testMethods) {} - public static void setGroups( String groups, String excludedGroups ) - { + public static void setGroups(String groups, String excludedGroups) { // System.out.println( "Processing group includes: '" + groups + "'\nExcludes: '" + excludedGroups + "'" ); - try - { + try { AndGroupMatcher matcher = new AndGroupMatcher(); GroupMatcher in = null; - if ( groups != null && !groups.trim().isEmpty() ) - { - in = new GroupMatcherParser( groups ).parse(); + if (groups != null && !groups.trim().isEmpty()) { + in = new GroupMatcherParser(groups).parse(); } - if ( in != null ) - { - matcher.addMatcher( in ); + if (in != null) { + matcher.addMatcher(in); } GroupMatcher ex = null; - if ( excludedGroups != null && !excludedGroups.trim().isEmpty() ) - { - ex = new GroupMatcherParser( excludedGroups ).parse(); + if (excludedGroups != null && !excludedGroups.trim().isEmpty()) { + ex = new GroupMatcherParser(excludedGroups).parse(); } - if ( ex != null ) - { - matcher.addMatcher( new InverseGroupMatcher( ex ) ); + if (ex != null) { + matcher.addMatcher(new InverseGroupMatcher(ex)); } - if ( in != null || ex != null ) - { + if (in != null || ex != null) { // System.out.println( "Group matcher: " + matcher ); GroupMatcherMethodSelector.matcher = matcher; } - } - catch ( ParseException e ) - { + } catch (ParseException e) { throw new IllegalArgumentException( - "Cannot parse group includes/excludes expression(s):\nIncludes: " + groups + "\nExcludes: " - + excludedGroups, e ); + "Cannot parse group includes/excludes expression(s):\nIncludes: " + groups + "\nExcludes: " + + excludedGroups, + e); } } - public static void setGroupMatcher( GroupMatcher matcher ) - { + public static void setGroupMatcher(GroupMatcher matcher) { GroupMatcherMethodSelector.matcher = matcher; } - } diff --git a/surefire-providers/surefire-testng-utils/src/main/java/org/apache/maven/surefire/testng/utils/MethodSelector.java b/surefire-providers/surefire-testng-utils/src/main/java/org/apache/maven/surefire/testng/utils/MethodSelector.java index 4143448f2f..1636ed514f 100644 --- a/surefire-providers/surefire-testng-utils/src/main/java/org/apache/maven/surefire/testng/utils/MethodSelector.java +++ b/surefire-providers/surefire-testng-utils/src/main/java/org/apache/maven/surefire/testng/utils/MethodSelector.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.testng.utils; /* @@ -32,42 +50,38 @@ * @author Olivier Lamy * @since 2.7.3 */ -public class MethodSelector - implements IMethodSelector -{ +public class MethodSelector implements IMethodSelector { private static volatile TestListResolver testListResolver = null; @Override - public void setTestMethods( List arg0 ) - { - } + public void setTestMethods(List arg0) {} @Override - public boolean includeMethod( IMethodSelectorContext context, ITestNGMethod testngMethod, boolean isTestMethod ) - { - return testngMethod.isBeforeClassConfiguration() || testngMethod.isBeforeGroupsConfiguration() - || testngMethod.isBeforeMethodConfiguration() || testngMethod.isBeforeSuiteConfiguration() - || testngMethod.isBeforeTestConfiguration() || testngMethod.isAfterClassConfiguration() - || testngMethod.isAfterGroupsConfiguration() || testngMethod.isAfterMethodConfiguration() - || testngMethod.isAfterSuiteConfiguration() || testngMethod.isAfterTestConfiguration() - || shouldRun( testngMethod ); + public boolean includeMethod(IMethodSelectorContext context, ITestNGMethod testngMethod, boolean isTestMethod) { + return testngMethod.isBeforeClassConfiguration() + || testngMethod.isBeforeGroupsConfiguration() + || testngMethod.isBeforeMethodConfiguration() + || testngMethod.isBeforeSuiteConfiguration() + || testngMethod.isBeforeTestConfiguration() + || testngMethod.isAfterClassConfiguration() + || testngMethod.isAfterGroupsConfiguration() + || testngMethod.isAfterMethodConfiguration() + || testngMethod.isAfterSuiteConfiguration() + || testngMethod.isAfterTestConfiguration() + || shouldRun(testngMethod); } - public static void setTestListResolver( TestListResolver testListResolver ) - { + public static void setTestListResolver(TestListResolver testListResolver) { MethodSelector.testListResolver = testListResolver; } - private static boolean shouldRun( ITestNGMethod test ) - { + private static boolean shouldRun(ITestNGMethod test) { TestListResolver resolver = testListResolver; boolean hasTestResolver = resolver != null && !resolver.isEmpty(); - if ( hasTestResolver ) - { + if (hasTestResolver) { boolean run = false; - for ( Class clazz = test.getRealClass(); !run && clazz != Object.class; clazz = clazz.getSuperclass() ) - { - run = resolver.shouldRun( clazz, test.getMethodName() ); + for (Class clazz = test.getRealClass(); !run && clazz != Object.class; clazz = clazz.getSuperclass()) { + run = resolver.shouldRun(clazz, test.getMethodName()); } return run; } diff --git a/surefire-providers/surefire-testng-utils/src/main/java/org/apache/maven/surefire/testng/utils/Stoppable.java b/surefire-providers/surefire-testng-utils/src/main/java/org/apache/maven/surefire/testng/utils/Stoppable.java index febc39b4e0..ead6333000 100644 --- a/surefire-providers/surefire-testng-utils/src/main/java/org/apache/maven/surefire/testng/utils/Stoppable.java +++ b/surefire-providers/surefire-testng-utils/src/main/java/org/apache/maven/surefire/testng/utils/Stoppable.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.testng.utils; /* @@ -27,8 +45,7 @@ * @author Tibor Digana (tibor17) * @since 2.19 */ -public interface Stoppable -{ +public interface Stoppable { /** * Delegates this call to {@link RunListener#testExecutionSkippedByUser()}. */ diff --git a/surefire-providers/surefire-testng-utils/src/test/java/testng/utils/BaseClassSample.java b/surefire-providers/surefire-testng-utils/src/test/java/testng/utils/BaseClassSample.java index 01487a05f5..79ec0e3e03 100644 --- a/surefire-providers/surefire-testng-utils/src/test/java/testng/utils/BaseClassSample.java +++ b/surefire-providers/surefire-testng-utils/src/test/java/testng/utils/BaseClassSample.java @@ -1,3 +1,21 @@ +/* + * 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 testng.utils; /* @@ -22,10 +40,6 @@ /** * */ -public abstract class BaseClassSample -{ - public void baseClassMethodToBeIncluded() - { - - } +public abstract class BaseClassSample { + public void baseClassMethodToBeIncluded() {} } diff --git a/surefire-providers/surefire-testng-utils/src/test/java/testng/utils/ChildClassSample.java b/surefire-providers/surefire-testng-utils/src/test/java/testng/utils/ChildClassSample.java index 28d40c54ee..dc04e38a64 100644 --- a/surefire-providers/surefire-testng-utils/src/test/java/testng/utils/ChildClassSample.java +++ b/surefire-providers/surefire-testng-utils/src/test/java/testng/utils/ChildClassSample.java @@ -1,3 +1,21 @@ +/* + * 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 testng.utils; /* @@ -22,11 +40,6 @@ /** * */ -public class ChildClassSample - extends BaseClassSample -{ - public void subClassMethod() - { - - } +public class ChildClassSample extends BaseClassSample { + public void subClassMethod() {} } diff --git a/surefire-providers/surefire-testng-utils/src/test/java/testng/utils/MethodSelectorTest.java b/surefire-providers/surefire-testng-utils/src/test/java/testng/utils/MethodSelectorTest.java index 24d89dea13..88ac0aa1e6 100644 --- a/surefire-providers/surefire-testng-utils/src/test/java/testng/utils/MethodSelectorTest.java +++ b/surefire-providers/surefire-testng-utils/src/test/java/testng/utils/MethodSelectorTest.java @@ -1,3 +1,21 @@ +/* + * 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 testng.utils; /* @@ -19,385 +37,298 @@ * under the License. */ +import java.lang.reflect.Method; + import junit.framework.TestCase; -import org.apache.maven.surefire.testng.utils.MethodSelector; import org.apache.maven.surefire.api.testset.TestListResolver; +import org.apache.maven.surefire.testng.utils.MethodSelector; import org.testng.IClass; import org.testng.IRetryAnalyzer; import org.testng.ITestClass; import org.testng.ITestNGMethod; import org.testng.internal.DefaultMethodSelectorContext; -import java.lang.reflect.Method; - /** * */ -public class MethodSelectorTest - extends TestCase -{ - public void testInclusionOfMethodFromBaseClass() - { +public class MethodSelectorTest extends TestCase { + public void testInclusionOfMethodFromBaseClass() { MethodSelector selector = new MethodSelector(); DefaultMethodSelectorContext context = new DefaultMethodSelectorContext(); - ITestNGMethod testngMethod = new FakeTestNGMethod( ChildClassSample.class, "baseClassMethodToBeIncluded" ); + ITestNGMethod testngMethod = new FakeTestNGMethod(ChildClassSample.class, "baseClassMethodToBeIncluded"); TestListResolver resolver = - new TestListResolver( BaseClassSample.class.getName() + "#baseClassMethodToBeIncluded" ); - MethodSelector.setTestListResolver( resolver ); - boolean include = selector.includeMethod( context, testngMethod, true ); - assertTrue( include ); + new TestListResolver(BaseClassSample.class.getName() + "#baseClassMethodToBeIncluded"); + MethodSelector.setTestListResolver(resolver); + boolean include = selector.includeMethod(context, testngMethod, true); + assertTrue(include); } - public void testNoInclusionOfMethodFromBaseClass() - { + public void testNoInclusionOfMethodFromBaseClass() { MethodSelector selector = new MethodSelector(); DefaultMethodSelectorContext context = new DefaultMethodSelectorContext(); - ITestNGMethod testngMethod = new FakeTestNGMethod( ChildClassSample.class, "baseClassMethodToBeIncluded" ); - TestListResolver resolver = new TestListResolver( BaseClassSample.class.getName() + "#nonExistedMethod" ); - MethodSelector.setTestListResolver( resolver ); - boolean include = selector.includeMethod( context, testngMethod, true ); - assertFalse( include ); + ITestNGMethod testngMethod = new FakeTestNGMethod(ChildClassSample.class, "baseClassMethodToBeIncluded"); + TestListResolver resolver = new TestListResolver(BaseClassSample.class.getName() + "#nonExistedMethod"); + MethodSelector.setTestListResolver(resolver); + boolean include = selector.includeMethod(context, testngMethod, true); + assertFalse(include); } - public void testInclusionOfMethodFromSubClass() - { + public void testInclusionOfMethodFromSubClass() { MethodSelector selector = new MethodSelector(); DefaultMethodSelectorContext context = new DefaultMethodSelectorContext(); - ITestNGMethod testngMethod = new FakeTestNGMethod( ChildClassSample.class, "subClassMethod" ); - TestListResolver resolver = new TestListResolver( ChildClassSample.class.getName() + "#sub*" ); - MethodSelector.setTestListResolver( resolver ); - boolean include = selector.includeMethod( context, testngMethod, true ); - assertTrue( include ); + ITestNGMethod testngMethod = new FakeTestNGMethod(ChildClassSample.class, "subClassMethod"); + TestListResolver resolver = new TestListResolver(ChildClassSample.class.getName() + "#sub*"); + MethodSelector.setTestListResolver(resolver); + boolean include = selector.includeMethod(context, testngMethod, true); + assertTrue(include); } - private static class FakeTestNGMethod - implements ITestNGMethod - { + private static class FakeTestNGMethod implements ITestNGMethod { private final Class clazz; private final String methodName; - FakeTestNGMethod( Class clazz, String methodName ) - { + FakeTestNGMethod(Class clazz, String methodName) { this.clazz = clazz; this.methodName = methodName; } @Override - public Class getRealClass() - { + public Class getRealClass() { return clazz; } @Override - public ITestClass getTestClass() - { + public ITestClass getTestClass() { return null; } @Override - public void setTestClass( ITestClass iTestClass ) - { - - } + public void setTestClass(ITestClass iTestClass) {} @Override - public Method getMethod() - { + public Method getMethod() { return null; } @Override - public String getMethodName() - { + public String getMethodName() { return methodName; } @Override - public Object[] getInstances() - { + public Object[] getInstances() { return new Object[0]; } @Override - public long[] getInstanceHashCodes() - { + public long[] getInstanceHashCodes() { return new long[0]; } @Override - public String[] getGroups() - { + public String[] getGroups() { return new String[0]; } @Override - public String[] getGroupsDependedUpon() - { + public String[] getGroupsDependedUpon() { return new String[0]; } @Override - public String getMissingGroup() - { + public String getMissingGroup() { return null; } @Override - public void setMissingGroup( String s ) - { - - } + public void setMissingGroup(String s) {} @Override - public String[] getBeforeGroups() - { + public String[] getBeforeGroups() { return new String[0]; } @Override - public String[] getAfterGroups() - { + public String[] getAfterGroups() { return new String[0]; } @Override - public String[] getMethodsDependedUpon() - { + public String[] getMethodsDependedUpon() { return new String[0]; } @Override - public void addMethodDependedUpon( String s ) - { - - } + public void addMethodDependedUpon(String s) {} @Override - public boolean isTest() - { + public boolean isTest() { return false; } @Override - public boolean isBeforeMethodConfiguration() - { + public boolean isBeforeMethodConfiguration() { return false; } @Override - public boolean isAfterMethodConfiguration() - { + public boolean isAfterMethodConfiguration() { return false; } @Override - public boolean isBeforeClassConfiguration() - { + public boolean isBeforeClassConfiguration() { return false; } @Override - public boolean isAfterClassConfiguration() - { + public boolean isAfterClassConfiguration() { return false; } @Override - public boolean isBeforeSuiteConfiguration() - { + public boolean isBeforeSuiteConfiguration() { return false; } @Override - public boolean isAfterSuiteConfiguration() - { + public boolean isAfterSuiteConfiguration() { return false; } @Override - public boolean isBeforeTestConfiguration() - { + public boolean isBeforeTestConfiguration() { return false; } @Override - public boolean isAfterTestConfiguration() - { + public boolean isAfterTestConfiguration() { return false; } @Override - public boolean isBeforeGroupsConfiguration() - { + public boolean isBeforeGroupsConfiguration() { return false; } @Override - public boolean isAfterGroupsConfiguration() - { + public boolean isAfterGroupsConfiguration() { return false; } @Override - public long getTimeOut() - { + public long getTimeOut() { return 0; } @Override - public int getInvocationCount() - { + public int getInvocationCount() { return 0; } @Override - public void setInvocationCount( int i ) - { - - } + public void setInvocationCount(int i) {} @Override - public int getSuccessPercentage() - { + public int getSuccessPercentage() { return 0; } @Override - public String getId() - { + public String getId() { return null; } @Override - public void setId( String s ) - { - - } + public void setId(String s) {} @Override - public long getDate() - { + public long getDate() { return 0; } @Override - public void setDate( long l ) - { - - } + public void setDate(long l) {} @Override - public boolean canRunFromClass( IClass iClass ) - { + public boolean canRunFromClass(IClass iClass) { return false; } @Override - public boolean isAlwaysRun() - { + public boolean isAlwaysRun() { return false; } @Override - public int getThreadPoolSize() - { + public int getThreadPoolSize() { return 0; } @Override - public void setThreadPoolSize( int i ) - { - - } + public void setThreadPoolSize(int i) {} @Override - public String getDescription() - { + public String getDescription() { return null; } @Override - public void incrementCurrentInvocationCount() - { - - } + public void incrementCurrentInvocationCount() {} @Override - public int getCurrentInvocationCount() - { + public int getCurrentInvocationCount() { return 0; } @Override - public void setParameterInvocationCount( int i ) - { - - } + public void setParameterInvocationCount(int i) {} @Override - public int getParameterInvocationCount() - { + public int getParameterInvocationCount() { return 0; } @Override - public ITestNGMethod clone() - { - try - { - return ( ITestNGMethod ) super.clone(); - } - catch ( CloneNotSupportedException e ) - { - throw new RuntimeException( e ); + public ITestNGMethod clone() { + try { + return (ITestNGMethod) super.clone(); + } catch (CloneNotSupportedException e) { + throw new RuntimeException(e); } } @Override - public IRetryAnalyzer getRetryAnalyzer() - { + public IRetryAnalyzer getRetryAnalyzer() { return null; } @Override - public void setRetryAnalyzer( IRetryAnalyzer iRetryAnalyzer ) - { - - } + public void setRetryAnalyzer(IRetryAnalyzer iRetryAnalyzer) {} @Override - public boolean skipFailedInvocations() - { + public boolean skipFailedInvocations() { return false; } @Override - public void setSkipFailedInvocations( boolean b ) - { - - } + public void setSkipFailedInvocations(boolean b) {} @Override - public long getInvocationTimeOut() - { + public long getInvocationTimeOut() { return 0; } @Override - public boolean ignoreMissingDependencies() - { + public boolean ignoreMissingDependencies() { return false; } @Override - public void setIgnoreMissingDependencies( boolean b ) - { - - } + public void setIgnoreMissingDependencies(boolean b) {} @Override - public int compareTo( Object o ) - { + public int compareTo(Object o) { return 0; } } diff --git a/surefire-providers/surefire-testng/pom.xml b/surefire-providers/surefire-testng/pom.xml index ad62cd78b4..92bf1c8315 100644 --- a/surefire-providers/surefire-testng/pom.xml +++ b/surefire-providers/surefire-testng/pom.xml @@ -1,3 +1,4 @@ + - - 4.0.0 - - - org.apache.maven.surefire - surefire-providers - 3.0.0-M10-SNAPSHOT - + 4.0.0 - surefire-testng + + org.apache.maven.surefire + surefire-providers + 3.0.0-M10-SNAPSHOT + - SureFire TestNG Runner - SureFire TestNG Runner - - - - junit - junit - 3.8.2 - provided - - - org.apache.maven.surefire - common-java5 - ${project.version} - - - org.apache.maven.surefire - surefire-testng-utils - ${project.version} - - - org.testng - testng - 5.10 - jdk15 - provided - - - org.mockito - mockito-core - test - - - org.powermock - powermock-reflect - test - - + surefire-testng - - - - org.jacoco - jacoco-maven-plugin - - - jacoco-agent - - prepare-agent - - - - - jacoco.agent - - - - maven-surefire-plugin - - ${jvm.args.tests} ${jacoco.agent} - - - - org.apache.maven.surefire - surefire-shadefire - - 3.0.0-M7 - - - - - + SureFire TestNG Runner + SureFire TestNG Runner surefire-3.0.0-M8 + + + + junit + junit + 3.8.2 + provided + + + org.apache.maven.surefire + common-java5 + ${project.version} + + + org.apache.maven.surefire + surefire-testng-utils + ${project.version} + + + org.testng + testng + 5.10 + jdk15 + provided + + + org.mockito + mockito-core + test + + + org.powermock + powermock-reflect + test + + + + + + + org.jacoco + jacoco-maven-plugin + + jacoco.agent + + + + jacoco-agent + + prepare-agent + + + + + + maven-surefire-plugin + + ${jvm.args.tests} ${jacoco.agent} + + + + org.apache.maven.surefire + surefire-shadefire + + 3.0.0-M7 + + + + + diff --git a/surefire-providers/surefire-testng/src/main/java/org/apache/maven/surefire/testng/ConfigurationAwareTestNGReporter.java b/surefire-providers/surefire-testng/src/main/java/org/apache/maven/surefire/testng/ConfigurationAwareTestNGReporter.java index 319eed41d9..213c8a1d02 100644 --- a/surefire-providers/surefire-testng/src/main/java/org/apache/maven/surefire/testng/ConfigurationAwareTestNGReporter.java +++ b/surefire-providers/surefire-testng/src/main/java/org/apache/maven/surefire/testng/ConfigurationAwareTestNGReporter.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.testng; /* @@ -28,14 +46,9 @@ * * @author Dan Fabulich */ -public class ConfigurationAwareTestNGReporter - extends TestNGReporter - implements IResultListener -{ +public class ConfigurationAwareTestNGReporter extends TestNGReporter implements IResultListener { - public ConfigurationAwareTestNGReporter( TestReportListener reportManager ) - { - super( reportManager ); + public ConfigurationAwareTestNGReporter(TestReportListener reportManager) { + super(reportManager); } - } diff --git a/surefire-providers/surefire-testng/src/main/java/org/apache/maven/surefire/testng/TestNGDirectoryTestSuite.java b/surefire-providers/surefire-testng/src/main/java/org/apache/maven/surefire/testng/TestNGDirectoryTestSuite.java index e9ede9d153..9050be131e 100644 --- a/surefire-providers/surefire-testng/src/main/java/org/apache/maven/surefire/testng/TestNGDirectoryTestSuite.java +++ b/surefire-providers/surefire-testng/src/main/java/org/apache/maven/surefire/testng/TestNGDirectoryTestSuite.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.testng; /* @@ -33,8 +51,8 @@ import org.apache.maven.surefire.api.util.TestsToRun; import static java.util.Collections.singleton; -import static org.apache.maven.surefire.testng.TestNGExecutor.run; import static org.apache.maven.surefire.shared.utils.StringUtils.isBlank; +import static org.apache.maven.surefire.testng.TestNGExecutor.run; /** * Test suite for TestNG based on a directory of Java test classes. Can also execute JUnit tests. @@ -42,9 +60,7 @@ * @author Brett Porter * @author Alex Popescu */ -final class TestNGDirectoryTestSuite - extends TestSuite -{ +final class TestNGDirectoryTestSuite extends TestSuite { private final Map options; private final Map junitOptions; @@ -65,10 +81,13 @@ final class TestNGDirectoryTestSuite private final int skipAfterFailureCount; - TestNGDirectoryTestSuite( String testSourceDirectory, Map confOptions, File reportsDirectory, - TestListResolver methodFilter, List mainCliOptions, - int skipAfterFailureCount ) - { + TestNGDirectoryTestSuite( + String testSourceDirectory, + Map confOptions, + File reportsDirectory, + TestListResolver methodFilter, + List mainCliOptions, + int skipAfterFailureCount) { this.options = confOptions; this.testSourceDirectory = testSourceDirectory; this.reportsDirectory = reportsDirectory; @@ -81,149 +100,132 @@ final class TestNGDirectoryTestSuite this.skipAfterFailureCount = skipAfterFailureCount; } - void execute( TestsToRun testsToRun, TestNGReporter testNGReporter ) - throws TestSetFailedException - { - if ( !testsToRun.allowEagerReading() ) - { - executeLazy( testsToRun, testNGReporter ); - } - else if ( testsToRun.containsAtLeast( 2 ) ) - { - executeMulti( testsToRun, testNGReporter ); - } - else if ( testsToRun.containsAtLeast( 1 ) ) - { + void execute(TestsToRun testsToRun, TestNGReporter testNGReporter) throws TestSetFailedException { + if (!testsToRun.allowEagerReading()) { + executeLazy(testsToRun, testNGReporter); + } else if (testsToRun.containsAtLeast(2)) { + executeMulti(testsToRun, testNGReporter); + } else if (testsToRun.containsAtLeast(1)) { Class testClass = testsToRun.iterator().next(); - executeSingleClass( testNGReporter, testClass ); + executeSingleClass(testNGReporter, testClass); } } - private void executeSingleClass( TestNGReporter testNGReporter, Class testClass ) - throws TestSetFailedException - { - options.put( "suitename", testClass.getName() ); + private void executeSingleClass(TestNGReporter testNGReporter, Class testClass) throws TestSetFailedException { + options.put("suitename", testClass.getName()); - startTestSuite( testNGReporter.getRunListener() ); + startTestSuite(testNGReporter.getRunListener()); - Map optionsToUse = isJUnitTest( testClass ) ? junitOptions : options; + Map optionsToUse = isJUnitTest(testClass) ? junitOptions : options; - run( singleton( testClass ), testSourceDirectory, optionsToUse, testNGReporter, - reportsDirectory, methodFilter, mainCliOptions, skipAfterFailureCount ); + run( + singleton(testClass), + testSourceDirectory, + optionsToUse, + testNGReporter, + reportsDirectory, + methodFilter, + mainCliOptions, + skipAfterFailureCount); - finishTestSuite( testNGReporter.getRunListener() ); + finishTestSuite(testNGReporter.getRunListener()); } - private void executeLazy( TestsToRun testsToRun, TestNGReporter testNGReporter ) - throws TestSetFailedException - { - for ( Class testToRun : testsToRun ) - { - executeSingleClass( testNGReporter, testToRun ); + private void executeLazy(TestsToRun testsToRun, TestNGReporter testNGReporter) throws TestSetFailedException { + for (Class testToRun : testsToRun) { + executeSingleClass(testNGReporter, testToRun); } } - private static Class findJUnitTestClass() - { - return lookupClass( "junit.framework.Test" ); + private static Class findJUnitTestClass() { + return lookupClass("junit.framework.Test"); } - private static Class findJUnitRunWithAnnotation() - { - return lookupAnnotation( "org.junit.runner.RunWith" ); + private static Class findJUnitRunWithAnnotation() { + return lookupAnnotation("org.junit.runner.RunWith"); } - private static Class findJUnitTestAnnotation() - { - return lookupAnnotation( "org.junit.Test" ); + private static Class findJUnitTestAnnotation() { + return lookupAnnotation("org.junit.Test"); } - @SuppressWarnings( "unchecked" ) - private static Class lookupAnnotation( String className ) - { - try - { - return (Class) Class.forName( className ); - } - catch ( ClassNotFoundException e ) - { + @SuppressWarnings("unchecked") + private static Class lookupAnnotation(String className) { + try { + return (Class) Class.forName(className); + } catch (ClassNotFoundException e) { return null; } } - private static Class lookupClass( String className ) - { - try - { - return Class.forName( className ); - } - catch ( ClassNotFoundException e ) - { + private static Class lookupClass(String className) { + try { + return Class.forName(className); + } catch (ClassNotFoundException e) { return null; } } - private void executeMulti( TestsToRun testsToRun, TestNGReporter testNGReporter ) - throws TestSetFailedException - { + private void executeMulti(TestsToRun testsToRun, TestNGReporter testNGReporter) throws TestSetFailedException { List> testNgTestClasses = new ArrayList<>(); List> junitTestClasses = new ArrayList<>(); - for ( Class testToRun : testsToRun ) - { - if ( isJUnitTest( testToRun ) ) - { - junitTestClasses.add( testToRun ); - } - else - { - testNgTestClasses.add( testToRun ); + for (Class testToRun : testsToRun) { + if (isJUnitTest(testToRun)) { + junitTestClasses.add(testToRun); + } else { + testNgTestClasses.add(testToRun); } } File testNgReportsDirectory = reportsDirectory, junitReportsDirectory = reportsDirectory; - if ( !junitTestClasses.isEmpty() && !testNgTestClasses.isEmpty() ) - { - testNgReportsDirectory = new File( reportsDirectory, "testng-native-results" ); - junitReportsDirectory = new File( reportsDirectory, "testng-junit-results" ); + if (!junitTestClasses.isEmpty() && !testNgTestClasses.isEmpty()) { + testNgReportsDirectory = new File(reportsDirectory, "testng-native-results"); + junitReportsDirectory = new File(reportsDirectory, "testng-junit-results"); } - startTestSuite( testNGReporter.getRunListener() ); - - run( testNgTestClasses, testSourceDirectory, options, testNGReporter, - testNgReportsDirectory, methodFilter, mainCliOptions, skipAfterFailureCount ); - - if ( !junitTestClasses.isEmpty() ) - { - run( junitTestClasses, testSourceDirectory, junitOptions, testNGReporter, - junitReportsDirectory, methodFilter, mainCliOptions, skipAfterFailureCount ); + startTestSuite(testNGReporter.getRunListener()); + + run( + testNgTestClasses, + testSourceDirectory, + options, + testNGReporter, + testNgReportsDirectory, + methodFilter, + mainCliOptions, + skipAfterFailureCount); + + if (!junitTestClasses.isEmpty()) { + run( + junitTestClasses, + testSourceDirectory, + junitOptions, + testNGReporter, + junitReportsDirectory, + methodFilter, + mainCliOptions, + skipAfterFailureCount); } - finishTestSuite( testNGReporter.getRunListener() ); + finishTestSuite(testNGReporter.getRunListener()); } - private boolean isJUnitTest( Class c ) - { - return isJunit3Test( c ) || isJunit4Test( c ); + private boolean isJUnitTest(Class c) { + return isJunit3Test(c) || isJunit4Test(c); } - private boolean isJunit4Test( Class c ) - { - return hasJunit4RunWithAnnotation( c ) || hasJunit4TestAnnotation( c ); + private boolean isJunit4Test(Class c) { + return hasJunit4RunWithAnnotation(c) || hasJunit4TestAnnotation(c); } - private boolean hasJunit4RunWithAnnotation( Class c ) - { - return junitRunWithAnnotation != null && c.getAnnotation( junitRunWithAnnotation ) != null; + private boolean hasJunit4RunWithAnnotation(Class c) { + return junitRunWithAnnotation != null && c.getAnnotation(junitRunWithAnnotation) != null; } - private boolean hasJunit4TestAnnotation( Class c ) - { - if ( junitTestAnnotation != null ) - { - for ( Method m : c.getMethods() ) - { - if ( m.getAnnotation( junitTestAnnotation ) != null ) - { + private boolean hasJunit4TestAnnotation(Class c) { + if (junitTestAnnotation != null) { + for (Method m : c.getMethods()) { + if (m.getAnnotation(junitTestAnnotation) != null) { return true; } } @@ -232,26 +234,22 @@ private boolean hasJunit4TestAnnotation( Class c ) return false; } - private boolean isJunit3Test( Class c ) - { - return junitTestClass != null && junitTestClass.isAssignableFrom( c ); + private boolean isJunit3Test(Class c) { + return junitTestClass != null && junitTestClass.isAssignableFrom(c); } - private Map createJUnitOptions() - { - Map junitOptions = new HashMap<>( options ); - String onlyJUnit = options.get( "junit" ); - if ( isBlank( onlyJUnit ) ) - { + private Map createJUnitOptions() { + Map junitOptions = new HashMap<>(options); + String onlyJUnit = options.get("junit"); + if (isBlank(onlyJUnit)) { onlyJUnit = "true"; } - junitOptions.put( "junit", onlyJUnit ); + junitOptions.put("junit", onlyJUnit); return junitOptions; } @Override - Map getOptions() - { + Map getOptions() { return options; } } diff --git a/surefire-providers/surefire-testng/src/main/java/org/apache/maven/surefire/testng/TestNGExecutor.java b/surefire-providers/surefire-testng/src/main/java/org/apache/maven/surefire/testng/TestNGExecutor.java index 7ed1719a86..6b8fbe9a22 100644 --- a/surefire-providers/surefire-testng/src/main/java/org/apache/maven/surefire/testng/TestNGExecutor.java +++ b/surefire-providers/surefire-testng/src/main/java/org/apache/maven/surefire/testng/TestNGExecutor.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.testng; /* @@ -19,17 +37,27 @@ * under the License. */ +import java.io.File; +import java.lang.annotation.Annotation; +import java.lang.reflect.Constructor; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.atomic.AtomicInteger; + import org.apache.maven.surefire.api.booter.ProviderParameterNames; import org.apache.maven.surefire.api.cli.CommandLineOption; import org.apache.maven.surefire.api.report.RunListener; +import org.apache.maven.surefire.api.testset.TestListResolver; +import org.apache.maven.surefire.api.testset.TestSetFailedException; +import org.apache.maven.surefire.shared.utils.StringUtils; import org.apache.maven.surefire.testng.conf.Configurator; import org.apache.maven.surefire.testng.utils.FailFastEventsSingleton; import org.apache.maven.surefire.testng.utils.FailFastListener; import org.apache.maven.surefire.testng.utils.FailFastNotifier; import org.apache.maven.surefire.testng.utils.Stoppable; -import org.apache.maven.surefire.api.testset.TestListResolver; -import org.apache.maven.surefire.api.testset.TestSetFailedException; -import org.apache.maven.surefire.shared.utils.StringUtils; import org.testng.ITestNGListener; import org.testng.TestNG; import org.testng.annotations.Test; @@ -38,16 +66,6 @@ import org.testng.xml.XmlSuite; import org.testng.xml.XmlTest; -import java.io.File; -import java.lang.annotation.Annotation; -import java.lang.reflect.Constructor; -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.atomic.AtomicInteger; - import static org.apache.maven.surefire.api.cli.CommandLineOption.LOGGING_LEVEL_DEBUG; import static org.apache.maven.surefire.api.cli.CommandLineOption.SHOW_ERRORS; import static org.apache.maven.surefire.api.util.ReflectionUtils.instantiate; @@ -64,8 +82,7 @@ * @author Brett Porter * @author Alex Popescu */ -final class TestNGExecutor -{ +final class TestNGExecutor { /** The default name for a suite launched from the maven surefire plugin */ private static final String DEFAULT_SUREFIRE_SUITE_NAME = "Surefire suite"; @@ -73,86 +90,91 @@ final class TestNGExecutor private static final String DEFAULT_SUREFIRE_TEST_NAME = "Surefire test"; private static final boolean HAS_TEST_ANNOTATION_ON_CLASSPATH = - tryLoadClass( TestNGExecutor.class.getClassLoader(), "org.testng.annotations.Test" ) != null; + tryLoadClass(TestNGExecutor.class.getClassLoader(), "org.testng.annotations.Test") != null; // Using reflection because XmlClass.setIndex is available since TestNG 6.3 // XmlClass.m_index field is available since TestNG 5.13, but prior to 6.3 required invoking constructor // and constructor XmlClass constructor signatures evolved over time. - private static final Method XML_CLASS_SET_INDEX = tryGetMethod( XmlClass.class, "setIndex", int.class ); + private static final Method XML_CLASS_SET_INDEX = tryGetMethod(XmlClass.class, "setIndex", int.class); // For TestNG versions [5.13, 6.3) where XmlClass.setIndex is not available, invoke XmlClass(String, boolean, int) // constructor. Note that XmlClass(String, boolean, int) was replaced with XmlClass(String, int) when // XmlClass.setIndex already existed. private static final Constructor XML_CLASS_CONSTRUCTOR_WITH_INDEX = - tryGetConstructor( XmlClass.class, String.class, boolean.class, int.class ); + tryGetConstructor(XmlClass.class, String.class, boolean.class, int.class); - private TestNGExecutor() - { - throw new IllegalStateException( "not instantiable constructor" ); + private TestNGExecutor() { + throw new IllegalStateException("not instantiable constructor"); } - @SuppressWarnings( "checkstyle:parameternumbercheck" ) - static void run( Iterable> testClasses, String testSourceDirectory, - Map options, // string,string because TestNGMapConfigurator#configure() - TestNGReporter testNGReporter, File reportsDirectory, - TestListResolver methodFilter, List mainCliOptions, - int skipAfterFailureCount ) - throws TestSetFailedException - { - TestNG testng = new TestNG( true ); - - Configurator configurator = getConfigurator( options.get( "testng.configurator" ) ); - - if ( isCliDebugOrShowErrors( mainCliOptions ) ) - { - System.out.println( "Configuring TestNG with: " + configurator.getClass().getSimpleName() ); + @SuppressWarnings("checkstyle:parameternumbercheck") + static void run( + Iterable> testClasses, + String testSourceDirectory, + Map options, // string,string because TestNGMapConfigurator#configure() + TestNGReporter testNGReporter, + File reportsDirectory, + TestListResolver methodFilter, + List mainCliOptions, + int skipAfterFailureCount) + throws TestSetFailedException { + TestNG testng = new TestNG(true); + + Configurator configurator = getConfigurator(options.get("testng.configurator")); + + if (isCliDebugOrShowErrors(mainCliOptions)) { + System.out.println( + "Configuring TestNG with: " + configurator.getClass().getSimpleName()); } - XmlMethodSelector groupMatchingSelector = createGroupMatchingSelector( options ); - XmlMethodSelector methodNameFilteringSelector = createMethodNameFilteringSelector( methodFilter ); + XmlMethodSelector groupMatchingSelector = createGroupMatchingSelector(options); + XmlMethodSelector methodNameFilteringSelector = createMethodNameFilteringSelector(methodFilter); Map suitesNames = new HashMap<>(); List xmlSuites = new ArrayList<>(); - for ( Class testClass : testClasses ) - { - TestMetadata metadata = findTestMetadata( testClass ); + for (Class testClass : testClasses) { + TestMetadata metadata = findTestMetadata(testClass); - SuiteAndNamedTests suiteAndNamedTests = suitesNames.get( metadata.suiteName ); - if ( suiteAndNamedTests == null ) - { + SuiteAndNamedTests suiteAndNamedTests = suitesNames.get(metadata.suiteName); + if (suiteAndNamedTests == null) { suiteAndNamedTests = new SuiteAndNamedTests(); - suiteAndNamedTests.xmlSuite.setName( metadata.suiteName ); - configurator.configure( suiteAndNamedTests.xmlSuite, options ); - xmlSuites.add( suiteAndNamedTests.xmlSuite ); + suiteAndNamedTests.xmlSuite.setName(metadata.suiteName); + configurator.configure(suiteAndNamedTests.xmlSuite, options); + xmlSuites.add(suiteAndNamedTests.xmlSuite); - suitesNames.put( metadata.suiteName, suiteAndNamedTests ); + suitesNames.put(metadata.suiteName, suiteAndNamedTests); } - XmlTest xmlTest = suiteAndNamedTests.testNameToTest.get( metadata.testName ); - if ( xmlTest == null ) - { - xmlTest = new XmlTest( suiteAndNamedTests.xmlSuite ); - xmlTest.setName( metadata.testName ); - addSelector( xmlTest, groupMatchingSelector ); - addSelector( xmlTest, methodNameFilteringSelector ); - xmlTest.setXmlClasses( new ArrayList<>() ); + XmlTest xmlTest = suiteAndNamedTests.testNameToTest.get(metadata.testName); + if (xmlTest == null) { + xmlTest = new XmlTest(suiteAndNamedTests.xmlSuite); + xmlTest.setName(metadata.testName); + addSelector(xmlTest, groupMatchingSelector); + addSelector(xmlTest, methodNameFilteringSelector); + xmlTest.setXmlClasses(new ArrayList<>()); - suiteAndNamedTests.testNameToTest.put( metadata.testName, xmlTest ); + suiteAndNamedTests.testNameToTest.put(metadata.testName, xmlTest); } - xmlTest.getXmlClasses().add( newXmlClassInstance( testClass.getName(), xmlTest.getXmlClasses().size() ) ); + xmlTest.getXmlClasses() + .add(newXmlClassInstance( + testClass.getName(), xmlTest.getXmlClasses().size())); } - testng.setXmlSuites( xmlSuites ); - configurator.configure( testng, options ); - postConfigure( testng, testSourceDirectory, testNGReporter, reportsDirectory, skipAfterFailureCount, - extractVerboseLevel( options ) ); + testng.setXmlSuites(xmlSuites); + configurator.configure(testng, options); + postConfigure( + testng, + testSourceDirectory, + testNGReporter, + reportsDirectory, + skipAfterFailureCount, + extractVerboseLevel(options)); testng.run(); } - private static XmlClass newXmlClassInstance( String testClassName, int index ) - { + private static XmlClass newXmlClassInstance(String testClassName, int index) { // In case of parallel test execution with parallel="methods", TestNG orders test execution // by XmlClass.m_index field. When unset (equal for all XmlClass instances), TestNG can // invoke `@BeforeClass` setup methods on many instances, without invoking `@AfterClass` @@ -162,40 +184,32 @@ private static XmlClass newXmlClassInstance( String testClassName, int index ) // #thread-count many test classes being initialized at given point in time. // Note: XmlClass.m_index field is set automatically by TestNG when it reads a suite file. - if ( XML_CLASS_SET_INDEX != null ) - { - XmlClass xmlClass = new XmlClass( testClassName ); - invokeSetter( xmlClass, XML_CLASS_SET_INDEX, index ); + if (XML_CLASS_SET_INDEX != null) { + XmlClass xmlClass = new XmlClass(testClassName); + invokeSetter(xmlClass, XML_CLASS_SET_INDEX, index); return xmlClass; } - if ( XML_CLASS_CONSTRUCTOR_WITH_INDEX != null ) - { + if (XML_CLASS_CONSTRUCTOR_WITH_INDEX != null) { boolean loadClass = true; // this is the default - return newInstance( XML_CLASS_CONSTRUCTOR_WITH_INDEX, testClassName, loadClass, index ); + return newInstance(XML_CLASS_CONSTRUCTOR_WITH_INDEX, testClassName, loadClass, index); } - return new XmlClass( testClassName ); + return new XmlClass(testClassName); } - private static boolean isCliDebugOrShowErrors( List mainCliOptions ) - { - return mainCliOptions.contains( LOGGING_LEVEL_DEBUG ) || mainCliOptions.contains( SHOW_ERRORS ); + private static boolean isCliDebugOrShowErrors(List mainCliOptions) { + return mainCliOptions.contains(LOGGING_LEVEL_DEBUG) || mainCliOptions.contains(SHOW_ERRORS); } - private static TestMetadata findTestMetadata( Class testClass ) - { + private static TestMetadata findTestMetadata(Class testClass) { TestMetadata result = new TestMetadata(); - if ( HAS_TEST_ANNOTATION_ON_CLASSPATH ) - { - Test testAnnotation = findAnnotation( testClass, Test.class ); - if ( null != testAnnotation ) - { - if ( !StringUtils.isBlank( testAnnotation.suiteName() ) ) - { + if (HAS_TEST_ANNOTATION_ON_CLASSPATH) { + Test testAnnotation = findAnnotation(testClass, Test.class); + if (null != testAnnotation) { + if (!StringUtils.isBlank(testAnnotation.suiteName())) { result.suiteName = testAnnotation.suiteName(); } - if ( !StringUtils.isBlank( testAnnotation.testName() ) ) - { + if (!StringUtils.isBlank(testAnnotation.testName())) { result.testName = testAnnotation.testName(); } } @@ -203,186 +217,168 @@ private static TestMetadata findTestMetadata( Class testClass ) return result; } - private static T findAnnotation( Class clazz, Class annotationType ) - { - if ( clazz == null ) - { + private static T findAnnotation(Class clazz, Class annotationType) { + if (clazz == null) { return null; } - T result = clazz.getAnnotation( annotationType ); - if ( result != null ) - { + T result = clazz.getAnnotation(annotationType); + if (result != null) { return result; } - return findAnnotation( clazz.getSuperclass(), annotationType ); + return findAnnotation(clazz.getSuperclass(), annotationType); } - private static class TestMetadata - { + private static class TestMetadata { private String testName = DEFAULT_SUREFIRE_TEST_NAME; private String suiteName = DEFAULT_SUREFIRE_SUITE_NAME; } - private static class SuiteAndNamedTests - { + private static class SuiteAndNamedTests { private final XmlSuite xmlSuite = new XmlSuite(); private final Map testNameToTest = new HashMap<>(); } - private static void addSelector( XmlTest xmlTest, XmlMethodSelector selector ) - { - if ( selector != null ) - { - xmlTest.getMethodSelectors().add( selector ); + private static void addSelector(XmlTest xmlTest, XmlMethodSelector selector) { + if (selector != null) { + xmlTest.getMethodSelectors().add(selector); } } - @SuppressWarnings( "checkstyle:magicnumber" ) - private static XmlMethodSelector createMethodNameFilteringSelector( TestListResolver methodFilter ) - throws TestSetFailedException - { - if ( methodFilter != null && !methodFilter.isEmpty() ) - { + @SuppressWarnings("checkstyle:magicnumber") + private static XmlMethodSelector createMethodNameFilteringSelector(TestListResolver methodFilter) + throws TestSetFailedException { + if (methodFilter != null && !methodFilter.isEmpty()) { // the class is available in the testClassPath String clazzName = "org.apache.maven.surefire.testng.utils.MethodSelector"; - try - { - Class clazz = Class.forName( clazzName ); - Method method = clazz.getMethod( "setTestListResolver", TestListResolver.class ); - method.invoke( null, methodFilter ); - } - catch ( Exception e ) - { - throw new TestSetFailedException( e.getMessage(), e ); + try { + Class clazz = Class.forName(clazzName); + Method method = clazz.getMethod("setTestListResolver", TestListResolver.class); + method.invoke(null, methodFilter); + } catch (Exception e) { + throw new TestSetFailedException(e.getMessage(), e); } XmlMethodSelector xms = new XmlMethodSelector(); - xms.setName( clazzName ); + xms.setName(clazzName); // looks to need a high value - xms.setPriority( 10000 ); + xms.setPriority(10000); return xms; - } - else - { + } else { return null; } } - @SuppressWarnings( "checkstyle:magicnumber" ) - private static XmlMethodSelector createGroupMatchingSelector( Map options ) - throws TestSetFailedException - { - final String groups = options.get( ProviderParameterNames.TESTNG_GROUPS_PROP ); - final String excludedGroups = options.get( ProviderParameterNames.TESTNG_EXCLUDEDGROUPS_PROP ); + @SuppressWarnings("checkstyle:magicnumber") + private static XmlMethodSelector createGroupMatchingSelector(Map options) + throws TestSetFailedException { + final String groups = options.get(ProviderParameterNames.TESTNG_GROUPS_PROP); + final String excludedGroups = options.get(ProviderParameterNames.TESTNG_EXCLUDEDGROUPS_PROP); - if ( groups == null && excludedGroups == null ) - { + if (groups == null && excludedGroups == null) { return null; } // the class is available in the testClassPath final String clazzName = "org.apache.maven.surefire.testng.utils.GroupMatcherMethodSelector"; - try - { - Class clazz = Class.forName( clazzName ); + try { + Class clazz = Class.forName(clazzName); // HORRIBLE hack, but TNG doesn't allow us to setup a method selector instance directly. - Method method = clazz.getMethod( "setGroups", String.class, String.class ); - method.invoke( null, groups, excludedGroups ); - } - catch ( Exception e ) - { - throw new TestSetFailedException( e.getMessage(), e ); + Method method = clazz.getMethod("setGroups", String.class, String.class); + method.invoke(null, groups, excludedGroups); + } catch (Exception e) { + throw new TestSetFailedException(e.getMessage(), e); } XmlMethodSelector xms = new XmlMethodSelector(); - xms.setName( clazzName ); + xms.setName(clazzName); // looks to need a high value - xms.setPriority( 9999 ); + xms.setPriority(9999); return xms; } - static void run( List suiteFiles, String testSourceDirectory, - Map options, // string,string because TestNGMapConfigurator#configure() - TestNGReporter testNGReporter, File reportsDirectory, int skipAfterFailureCount ) - throws TestSetFailedException - { - TestNG testng = new TestNG( true ); - Configurator configurator = getConfigurator( options.get( "testng.configurator" ) ); - configurator.configure( testng, options ); - postConfigure( testng, testSourceDirectory, testNGReporter, reportsDirectory, skipAfterFailureCount, - extractVerboseLevel( options ) ); - testng.setTestSuites( suiteFiles ); + static void run( + List suiteFiles, + String testSourceDirectory, + Map options, // string,string because TestNGMapConfigurator#configure() + TestNGReporter testNGReporter, + File reportsDirectory, + int skipAfterFailureCount) + throws TestSetFailedException { + TestNG testng = new TestNG(true); + Configurator configurator = getConfigurator(options.get("testng.configurator")); + configurator.configure(testng, options); + postConfigure( + testng, + testSourceDirectory, + testNGReporter, + reportsDirectory, + skipAfterFailureCount, + extractVerboseLevel(options)); + testng.setTestSuites(suiteFiles); testng.run(); } - private static Configurator getConfigurator( String className ) - { - try - { - return (Configurator) Class.forName( className ).newInstance(); - } - catch ( ReflectiveOperationException e ) - { - throw new RuntimeException( e ); + private static Configurator getConfigurator(String className) { + try { + return (Configurator) Class.forName(className).newInstance(); + } catch (ReflectiveOperationException e) { + throw new RuntimeException(e); } } - private static void postConfigure( TestNG testNG, String sourcePath, TestNGReporter testNGReporter, - File reportsDirectory, int skipAfterFailureCount, int verboseLevel ) - { + private static void postConfigure( + TestNG testNG, + String sourcePath, + TestNGReporter testNGReporter, + File reportsDirectory, + int skipAfterFailureCount, + int verboseLevel) { // 0 (default): turn off all TestNG output - testNG.setVerbose( verboseLevel ); - testNG.addListener( (ITestNGListener) testNGReporter ); + testNG.setVerbose(verboseLevel); + testNG.addListener((ITestNGListener) testNGReporter); - if ( skipAfterFailureCount > 0 ) - { + if (skipAfterFailureCount > 0) { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); - testNG.addListener( instantiate( classLoader, FailFastNotifier.class.getName(), Object.class ) ); + testNG.addListener(instantiate(classLoader, FailFastNotifier.class.getName(), Object.class)); testNG.addListener( - new FailFastListener( createStoppable( testNGReporter.getRunListener(), skipAfterFailureCount ) ) ); + new FailFastListener(createStoppable(testNGReporter.getRunListener(), skipAfterFailureCount))); } // FIXME: use classifier to decide if we need to pass along the source dir (only for JDK14) - if ( sourcePath != null ) - { - testNG.setSourcePath( sourcePath ); + if (sourcePath != null) { + testNG.setSourcePath(sourcePath); } - testNG.setOutputDirectory( reportsDirectory.getAbsolutePath() ); + testNG.setOutputDirectory(reportsDirectory.getAbsolutePath()); } - private static Stoppable createStoppable( final RunListener reportManager, int skipAfterFailureCount ) - { - final AtomicInteger currentFaultCount = new AtomicInteger( skipAfterFailureCount ); + private static Stoppable createStoppable(final RunListener reportManager, int skipAfterFailureCount) { + final AtomicInteger currentFaultCount = new AtomicInteger(skipAfterFailureCount); - return () -> - { - runIfZeroCountDown( () -> FailFastEventsSingleton.getInstance().setSkipOnNextTest(), currentFaultCount ); + return () -> { + runIfZeroCountDown(() -> FailFastEventsSingleton.getInstance().setSkipOnNextTest(), currentFaultCount); reportManager.testExecutionSkippedByUser(); }; } - private static int extractVerboseLevel( Map options ) - throws TestSetFailedException - { - try - { - String verbose = options.get( "surefire.testng.verbose" ); - return verbose == null ? 0 : Integer.parseInt( verbose ); - } - catch ( NumberFormatException e ) - { - throw new TestSetFailedException( "Provider property 'surefire.testng.verbose' should refer to " - + "number -1 (debug mode), 0, 1 .. 10 (most detailed).", e ); + private static int extractVerboseLevel(Map options) throws TestSetFailedException { + try { + String verbose = options.get("surefire.testng.verbose"); + return verbose == null ? 0 : Integer.parseInt(verbose); + } catch (NumberFormatException e) { + throw new TestSetFailedException( + "Provider property 'surefire.testng.verbose' should refer to " + + "number -1 (debug mode), 0, 1 .. 10 (most detailed).", + e); } } } diff --git a/surefire-providers/surefire-testng/src/main/java/org/apache/maven/surefire/testng/TestNGProvider.java b/surefire-providers/surefire-testng/src/main/java/org/apache/maven/surefire/testng/TestNGProvider.java index 0ca1403a83..350f36c698 100644 --- a/surefire-providers/surefire-testng/src/main/java/org/apache/maven/surefire/testng/TestNGProvider.java +++ b/surefire-providers/surefire-testng/src/main/java/org/apache/maven/surefire/testng/TestNGProvider.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.testng; /* @@ -54,9 +72,7 @@ /** * @author Kristian Rosenvold */ -public class TestNGProvider - extends AbstractProvider -{ +public class TestNGProvider extends AbstractProvider { private final Map providerProperties; private final ReporterConfiguration reporterConfiguration; @@ -75,8 +91,7 @@ public class TestNGProvider private final CommandChainReader commandsReader; - public TestNGProvider( ProviderParameters bootParams ) - { + public TestNGProvider(ProviderParameters bootParams) { // don't start a thread in CommandReader while we are in in-plugin process commandsReader = bootParams.isInsideFork() ? bootParams.getCommandReader() : null; providerParameters = bootParams; @@ -90,11 +105,8 @@ public TestNGProvider( ProviderParameters bootParams ) } @Override - public RunResult invoke( Object forkTestSet ) - throws TestSetFailedException - { - if ( isFailFast() && commandsReader != null ) - { + public RunResult invoke(Object forkTestSet) throws TestSetFailedException { + if (isFailFast() && commandsReader != null) { registerPleaseStopListener(); } @@ -102,182 +114,146 @@ public RunResult invoke( Object forkTestSet ) TestReportListener reporter = reporterFactory.createTestReportListener(); RunResult runResult; - try - { - if ( isTestNGXmlTestSuite( testRequest ) ) - { - TestNGReporter testNGReporter = createTestNGReporter( reporter ); - testNGReporter.setRunMode( NORMAL_RUN ); + try { + if (isTestNGXmlTestSuite(testRequest)) { + TestNGReporter testNGReporter = createTestNGReporter(reporter); + testNGReporter.setRunMode(NORMAL_RUN); /* * {@link org.apache.maven.surefire.api.report.ConsoleOutputCapture#startCapture(ConsoleOutputReceiver)} * called in prior to initializing variable {@link #testsToRun} */ - startCapture( testNGReporter ); + startCapture(testNGReporter); - if ( commandsReader != null ) - { + if (commandsReader != null) { commandsReader.awaitStarted(); } TestNGXmlTestSuite testNGXmlTestSuite = newXmlSuite(); testNGXmlTestSuite.locateTestSets(); - testNGXmlTestSuite.execute( testNGReporter ); - } - else - { - TestNGReporter testNGReporter = createTestNGReporter( reporter ); - testNGReporter.setRunMode( NORMAL_RUN ); + testNGXmlTestSuite.execute(testNGReporter); + } else { + TestNGReporter testNGReporter = createTestNGReporter(reporter); + testNGReporter.setRunMode(NORMAL_RUN); /* * {@link org.apache.maven.surefire.api.report.ConsoleOutputCapture#startCapture(ConsoleOutputReceiver)} * called in prior to initializing variable {@link #testsToRun} */ - startCapture( testNGReporter ); + startCapture(testNGReporter); final TestsToRun testsToRun; - if ( forkTestSet instanceof TestsToRun ) - { + if (forkTestSet instanceof TestsToRun) { testsToRun = (TestsToRun) forkTestSet; - } - else if ( forkTestSet instanceof Class ) - { - testsToRun = fromClass( (Class) forkTestSet ); - } - else - { + } else if (forkTestSet instanceof Class) { + testsToRun = fromClass((Class) forkTestSet); + } else { testsToRun = scanClassPath(); } - if ( commandsReader != null ) - { - registerShutdownListener( testsToRun ); + if (commandsReader != null) { + registerShutdownListener(testsToRun); commandsReader.awaitStarted(); } TestNGDirectoryTestSuite suite = newDirectorySuite(); - suite.execute( testsToRun, testNGReporter ); + suite.execute(testsToRun, testNGReporter); } - } - finally - { + } finally { runResult = reporterFactory.close(); } return runResult; } - boolean isTestNGXmlTestSuite( TestRequest testSuiteDefinition ) - { + boolean isTestNGXmlTestSuite(TestRequest testSuiteDefinition) { Collection suiteXmlFiles = testSuiteDefinition.getSuiteXmlFiles(); return !suiteXmlFiles.isEmpty() && !hasSpecificTests(); } - private boolean isFailFast() - { + private boolean isFailFast() { return providerParameters.getSkipAfterFailureCount() > 0; } - private int getSkipAfterFailureCount() - { + private int getSkipAfterFailureCount() { return isFailFast() ? providerParameters.getSkipAfterFailureCount() : 0; } - private void registerShutdownListener( final TestsToRun testsToRun ) - { - commandsReader.addShutdownListener( new CommandListener() - { + private void registerShutdownListener(final TestsToRun testsToRun) { + commandsReader.addShutdownListener(new CommandListener() { @Override - public void update( Command command ) - { + public void update(Command command) { testsToRun.markTestSetFinished(); } - } ); + }); } - private void registerPleaseStopListener() - { - commandsReader.addSkipNextTestsListener( new CommandListener() - { + private void registerPleaseStopListener() { + commandsReader.addSkipNextTestsListener(new CommandListener() { @Override - public void update( Command command ) - { + public void update(Command command) { FailFastEventsSingleton.getInstance().setSkipOnNextTest(); } - } ); + }); } - private TestNGDirectoryTestSuite newDirectorySuite() - { - return new TestNGDirectoryTestSuite( testRequest.getTestSourceDirectory().toString(), providerProperties, - reporterConfiguration.getReportsDirectory(), getTestFilter(), - mainCliOptions, getSkipAfterFailureCount() ); + private TestNGDirectoryTestSuite newDirectorySuite() { + return new TestNGDirectoryTestSuite( + testRequest.getTestSourceDirectory().toString(), + providerProperties, + reporterConfiguration.getReportsDirectory(), + getTestFilter(), + mainCliOptions, + getSkipAfterFailureCount()); } - private TestNGXmlTestSuite newXmlSuite() - { - return new TestNGXmlTestSuite( testRequest.getSuiteXmlFiles(), - testRequest.getTestSourceDirectory().toString(), - providerProperties, - reporterConfiguration.getReportsDirectory(), getSkipAfterFailureCount() ); + private TestNGXmlTestSuite newXmlSuite() { + return new TestNGXmlTestSuite( + testRequest.getSuiteXmlFiles(), + testRequest.getTestSourceDirectory().toString(), + providerProperties, + reporterConfiguration.getReportsDirectory(), + getSkipAfterFailureCount()); } @Override - @SuppressWarnings( "unchecked" ) - public Iterable> getSuites() - { - if ( isTestNGXmlTestSuite( testRequest ) ) - { - try - { + @SuppressWarnings("unchecked") + public Iterable> getSuites() { + if (isTestNGXmlTestSuite(testRequest)) { + try { return newXmlSuite().locateTestSets(); + } catch (TestSetFailedException e) { + throw new RuntimeException(e); } - catch ( TestSetFailedException e ) - { - throw new RuntimeException( e ); - } - } - else - { + } else { return scanClassPath(); } } - private TestsToRun scanClassPath() - { - final TestsToRun scanned = scanResult.applyFilter( null, testClassLoader ); - return runOrderCalculator.orderTestClasses( scanned ); + private TestsToRun scanClassPath() { + final TestsToRun scanned = scanResult.applyFilter(null, testClassLoader); + return runOrderCalculator.orderTestClasses(scanned); } - private boolean hasSpecificTests() - { + private boolean hasSpecificTests() { TestListResolver specificTestPatterns = testRequest.getTestListResolver(); return !specificTestPatterns.isEmpty() && !specificTestPatterns.isWildcard(); } - private TestListResolver getTestFilter() - { - TestListResolver filter = optionallyWildcardFilter( testRequest.getTestListResolver() ); + private TestListResolver getTestFilter() { + TestListResolver filter = optionallyWildcardFilter(testRequest.getTestListResolver()); return filter.isWildcard() ? getEmptyTestListResolver() : filter; } // If we have access to IResultListener, return a ConfigurationAwareTestNGReporter. // But don't cause NoClassDefFoundErrors if it isn't available; just return a regular TestNGReporter instead. - private static TestNGReporter createTestNGReporter( TestReportListener reportManager ) - { - try - { - Class.forName( "org.testng.internal.IResultListener" ); - Class c = Class.forName( "org.apache.maven.surefire.testng.ConfigurationAwareTestNGReporter" ); - Constructor ctor = c.getConstructor( TestReportListener.class ); - return (TestNGReporter) ctor.newInstance( reportManager ); - } - catch ( InvocationTargetException e ) - { - throw new RuntimeException( "Bug in ConfigurationAwareTestNGReporter", e.getCause() ); - } - catch ( ClassNotFoundException e ) - { - return new TestNGReporter( reportManager ); - } - catch ( Exception e ) - { - throw new RuntimeException( "Bug in ConfigurationAwareTestNGReporter", e ); + private static TestNGReporter createTestNGReporter(TestReportListener reportManager) { + try { + Class.forName("org.testng.internal.IResultListener"); + Class c = Class.forName("org.apache.maven.surefire.testng.ConfigurationAwareTestNGReporter"); + Constructor ctor = c.getConstructor(TestReportListener.class); + return (TestNGReporter) ctor.newInstance(reportManager); + } catch (InvocationTargetException e) { + throw new RuntimeException("Bug in ConfigurationAwareTestNGReporter", e.getCause()); + } catch (ClassNotFoundException e) { + return new TestNGReporter(reportManager); + } catch (Exception e) { + throw new RuntimeException("Bug in ConfigurationAwareTestNGReporter", e); } } } diff --git a/surefire-providers/surefire-testng/src/main/java/org/apache/maven/surefire/testng/TestNGReporter.java b/surefire-providers/surefire-testng/src/main/java/org/apache/maven/surefire/testng/TestNGReporter.java index 4e34f73b17..b4c54b224f 100644 --- a/surefire-providers/surefire-testng/src/main/java/org/apache/maven/surefire/testng/TestNGReporter.java +++ b/surefire-providers/surefire-testng/src/main/java/org/apache/maven/surefire/testng/TestNGReporter.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.testng; /* @@ -19,19 +37,20 @@ * under the License. */ +import java.util.Arrays; + import org.apache.maven.surefire.api.report.CategorizedReportEntry; import org.apache.maven.surefire.api.report.OutputReportEntry; +import org.apache.maven.surefire.api.report.ReportEntry; +import org.apache.maven.surefire.api.report.RunListener; import org.apache.maven.surefire.api.report.RunMode; +import org.apache.maven.surefire.api.report.SimpleReportEntry; import org.apache.maven.surefire.api.report.StackTraceWriter; import org.apache.maven.surefire.api.report.TestOutputReceiver; import org.apache.maven.surefire.api.report.TestOutputReportEntry; import org.apache.maven.surefire.api.report.TestReportListener; import org.apache.maven.surefire.report.ClassMethodIndexer; import org.apache.maven.surefire.report.PojoStackTraceWriter; -import org.apache.maven.surefire.api.report.ReportEntry; -import org.apache.maven.surefire.api.report.RunListener; -import org.apache.maven.surefire.api.report.SimpleReportEntry; - import org.apache.maven.surefire.report.RunModeSetter; import org.testng.IClass; import org.testng.ISuite; @@ -40,8 +59,6 @@ import org.testng.ITestListener; import org.testng.ITestResult; -import java.util.Arrays; - import static org.apache.maven.surefire.api.report.SimpleReportEntry.ignored; import static org.apache.maven.surefire.api.report.SimpleReportEntry.withException; @@ -53,8 +70,7 @@ * @author jkuhnert */ public class TestNGReporter - implements TestOutputReceiver, ITestListener, ISuiteListener, RunModeSetter -{ + implements TestOutputReceiver, ITestListener, ISuiteListener, RunModeSetter { private final ClassMethodIndexer classMethodIndexer = new ClassMethodIndexer(); private final TestReportListener reporter; private volatile RunMode runMode; @@ -69,101 +85,81 @@ public class TestNGReporter * * @param reportManager Instance to report suite status to */ - public TestNGReporter( TestReportListener reportManager ) - { + public TestNGReporter(TestReportListener reportManager) { this.reporter = reportManager; } - protected final RunListener getRunListener() - { + protected final RunListener getRunListener() { return reporter; } @Override - public void onTestStart( ITestResult result ) - { + public void onTestStart(ITestResult result) { String className = result.getTestClass().getName(); - String methodName = testName( result ); - long testRunId = classMethodIndexer.indexClassMethod( className, methodName ); - String group = groupString( result.getMethod().getGroups(), className ); - reporter.testStarting( new CategorizedReportEntry( runMode, testRunId, className, methodName, group ) ); + String methodName = testName(result); + long testRunId = classMethodIndexer.indexClassMethod(className, methodName); + String group = groupString(result.getMethod().getGroups(), className); + reporter.testStarting(new CategorizedReportEntry(runMode, testRunId, className, methodName, group)); } @Override - public void onTestSuccess( ITestResult result ) - { + public void onTestSuccess(ITestResult result) { String className = result.getTestClass().getName(); - String methodName = testName( result ); - long testRunId = classMethodIndexer.indexClassMethod( className, methodName ); - ReportEntry report = new SimpleReportEntry( runMode, testRunId, className, null, methodName, null ); - reporter.testSucceeded( report ); + String methodName = testName(result); + long testRunId = classMethodIndexer.indexClassMethod(className, methodName); + ReportEntry report = new SimpleReportEntry(runMode, testRunId, className, null, methodName, null); + reporter.testSucceeded(report); } @Override - public void onTestFailure( ITestResult result ) - { + public void onTestFailure(ITestResult result) { IClass clazz = result.getTestClass(); String className = clazz.getName(); - String methodName = testName( result ); - long testRunId = classMethodIndexer.indexClassMethod( className, methodName ); - StackTraceWriter stackTraceWriter = new PojoStackTraceWriter( clazz.getRealClass().getName(), - result.getMethod().getMethodName(), result.getThrowable() ); - ReportEntry report = withException( runMode, testRunId, clazz.getName(), null, methodName, - null, stackTraceWriter ); - - reporter.testFailed( report ); + String methodName = testName(result); + long testRunId = classMethodIndexer.indexClassMethod(className, methodName); + StackTraceWriter stackTraceWriter = new PojoStackTraceWriter( + clazz.getRealClass().getName(), result.getMethod().getMethodName(), result.getThrowable()); + ReportEntry report = + withException(runMode, testRunId, clazz.getName(), null, methodName, null, stackTraceWriter); + + reporter.testFailed(report); } @Override - public void onTestSkipped( ITestResult result ) - { + public void onTestSkipped(ITestResult result) { String className = result.getTestClass().getName(); - String methodName = testName( result ); - long testRunId = classMethodIndexer.indexClassMethod( className, methodName ); + String methodName = testName(result); + long testRunId = classMethodIndexer.indexClassMethod(className, methodName); //noinspection ThrowableResultOfMethodCallIgnored Throwable t = result.getThrowable(); String reason = t == null ? null : t.getMessage(); - ReportEntry report = ignored( runMode, testRunId, className, null, methodName, null, reason ); - reporter.testSkipped( report ); + ReportEntry report = ignored(runMode, testRunId, className, null, methodName, null, reason); + reporter.testSkipped(report); } @Override - public void onTestFailedButWithinSuccessPercentage( ITestResult result ) - { + public void onTestFailedButWithinSuccessPercentage(ITestResult result) { IClass clazz = result.getTestClass(); String className = clazz.getName(); - String methodName = testName( result ); - long testRunId = classMethodIndexer.indexClassMethod( className, methodName ); - StackTraceWriter stackTraceWriter = new PojoStackTraceWriter( clazz.getRealClass().getName(), - result.getMethod().getMethodName(), result.getThrowable() ); - ReportEntry report = withException( runMode, testRunId, className, null, methodName, null, stackTraceWriter ); - reporter.testSucceeded( report ); + String methodName = testName(result); + long testRunId = classMethodIndexer.indexClassMethod(className, methodName); + StackTraceWriter stackTraceWriter = new PojoStackTraceWriter( + clazz.getRealClass().getName(), result.getMethod().getMethodName(), result.getThrowable()); + ReportEntry report = withException(runMode, testRunId, className, null, methodName, null, stackTraceWriter); + reporter.testSucceeded(report); } @Override - public void onStart( ITestContext context ) - { - - } + public void onStart(ITestContext context) {} @Override - public void onFinish( ITestContext context ) - { - - } - + public void onFinish(ITestContext context) {} @Override - public void onStart( ISuite suite ) - { - - } + public void onStart(ISuite suite) {} @Override - public void onFinish( ISuite suite ) - { - - } + public void onFinish(ISuite suite) {} /** * Creates a string out of the list of testng groups in the @@ -173,43 +169,34 @@ public void onFinish( ISuite suite ) * @param defaultValue The default to use if no groups * @return a string describing the groups */ - private static String groupString( String[] groups, String defaultValue ) - { + private static String groupString(String[] groups, String defaultValue) { String retVal; - if ( groups != null && groups.length > 0 ) - { + if (groups != null && groups.length > 0) { StringBuilder str = new StringBuilder(); - for ( int i = 0; i < groups.length; i++ ) - { - str.append( groups[i] ); - if ( i + 1 < groups.length ) - { - str.append( "," ); + for (int i = 0; i < groups.length; i++) { + str.append(groups[i]); + if (i + 1 < groups.length) { + str.append(","); } } retVal = str.toString(); - } - else - { + } else { retVal = defaultValue; } return retVal; } - public void onConfigurationFailure( ITestResult result ) - { - onTestFailure( result ); + public void onConfigurationFailure(ITestResult result) { + onTestFailure(result); } - public void onConfigurationSkip( ITestResult result ) - { - onTestSkipped( result ); + public void onConfigurationSkip(ITestResult result) { + onTestSkipped(result); } - public void onConfigurationSuccess( ITestResult result ) - { + public void onConfigurationSuccess(ITestResult result) { // DGF Don't record configuration successes as separate tests - //onTestSuccess( result ); + // onTestSuccess( result ); } /** @@ -219,24 +206,22 @@ public void onConfigurationSuccess( ITestResult result ) * @param result the test result to extract from * @return a descriptive name for the test */ - private static String testName( ITestResult result ) - { + private static String testName(ITestResult result) { Object[] parameters = result.getParameters(); String name = result.getName(); return parameters == null || parameters.length == 0 - ? name : name + Arrays.toString( parameters ) + "(" + result.getMethod().getCurrentInvocationCount() + ")"; + ? name + : name + Arrays.toString(parameters) + "(" + result.getMethod().getCurrentInvocationCount() + ")"; } @Override - public void setRunMode( RunMode runMode ) - { + public void setRunMode(RunMode runMode) { this.runMode = runMode; } @Override - public void writeTestOutput( OutputReportEntry reportEntry ) - { + public void writeTestOutput(OutputReportEntry reportEntry) { Long testRunId = classMethodIndexer.getLocalIndex(); - reporter.writeTestOutput( new TestOutputReportEntry( reportEntry, runMode, testRunId ) ); + reporter.writeTestOutput(new TestOutputReportEntry(reportEntry, runMode, testRunId)); } } diff --git a/surefire-providers/surefire-testng/src/main/java/org/apache/maven/surefire/testng/TestNGXmlTestSuite.java b/surefire-providers/surefire-testng/src/main/java/org/apache/maven/surefire/testng/TestNGXmlTestSuite.java index 53f6801b26..f2c7c4acc4 100644 --- a/surefire-providers/surefire-testng/src/main/java/org/apache/maven/surefire/testng/TestNGXmlTestSuite.java +++ b/surefire-providers/surefire-testng/src/main/java/org/apache/maven/surefire/testng/TestNGXmlTestSuite.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.testng; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.testng; import java.io.File; import java.util.ArrayList; @@ -34,9 +33,7 @@ * @author jkuhnert * @author Alex Popescu */ -final class TestNGXmlTestSuite - extends TestSuite -{ +final class TestNGXmlTestSuite extends TestSuite { private final List suiteFiles; private List suiteFilePaths; @@ -53,9 +50,12 @@ final class TestNGXmlTestSuite * Creates a testng testset to be configured by the specified * xml file(s). The XML files are suite definitions files according to TestNG DTD. */ - TestNGXmlTestSuite( List suiteFiles, String testSourceDirectory, Map confOptions, - File reportsDirectory, int skipAfterFailureCount ) - { + TestNGXmlTestSuite( + List suiteFiles, + String testSourceDirectory, + Map confOptions, + File reportsDirectory, + int skipAfterFailureCount) { this.suiteFiles = suiteFiles; this.options = confOptions; this.testSourceDirectory = testSourceDirectory; @@ -63,49 +63,39 @@ final class TestNGXmlTestSuite this.skipAfterFailureCount = skipAfterFailureCount; } - void execute( TestNGReporter testNGReporter ) - throws TestSetFailedException - { - if ( suiteFilePaths == null ) - { - throw new IllegalStateException( "You must call locateTestSets before calling execute" ); + void execute(TestNGReporter testNGReporter) throws TestSetFailedException { + if (suiteFilePaths == null) { + throw new IllegalStateException("You must call locateTestSets before calling execute"); } - startTestSuite( testNGReporter.getRunListener() ); - run( suiteFilePaths, testSourceDirectory, options, testNGReporter, reportsDirectory, skipAfterFailureCount ); - finishTestSuite( testNGReporter.getRunListener() ); + startTestSuite(testNGReporter.getRunListener()); + run(suiteFilePaths, testSourceDirectory, options, testNGReporter, reportsDirectory, skipAfterFailureCount); + finishTestSuite(testNGReporter.getRunListener()); } - Iterable locateTestSets() - throws TestSetFailedException - { - if ( suiteFilePaths != null ) - { - throw new IllegalStateException( "You can't call locateTestSets twice" ); + Iterable locateTestSets() throws TestSetFailedException { + if (suiteFilePaths != null) { + throw new IllegalStateException("You can't call locateTestSets twice"); } - if ( suiteFiles.isEmpty() ) - { - throw new IllegalStateException( "No suite files were specified" ); + if (suiteFiles.isEmpty()) { + throw new IllegalStateException("No suite files were specified"); } - suiteFilePaths = new ArrayList<>( suiteFiles.size() ); - ArrayList testSets = new ArrayList<>( suiteFiles.size() ); + suiteFilePaths = new ArrayList<>(suiteFiles.size()); + ArrayList testSets = new ArrayList<>(suiteFiles.size()); - for ( File suiteFile : suiteFiles ) - { - if ( !suiteFile.isFile() ) - { - throw new TestSetFailedException( "Suite file " + suiteFile + " is not a valid file" ); + for (File suiteFile : suiteFiles) { + if (!suiteFile.isFile()) { + throw new TestSetFailedException("Suite file " + suiteFile + " is not a valid file"); } - testSets.add( suiteFile ); - suiteFilePaths.add( suiteFile.getAbsolutePath() ); + testSets.add(suiteFile); + suiteFilePaths.add(suiteFile.getAbsolutePath()); } return testSets; } @Override - Map getOptions() - { + Map getOptions() { return options; } } diff --git a/surefire-providers/surefire-testng/src/main/java/org/apache/maven/surefire/testng/TestSuite.java b/surefire-providers/surefire-testng/src/main/java/org/apache/maven/surefire/testng/TestSuite.java index 73ddf8404d..eec406f29a 100644 --- a/surefire-providers/surefire-testng/src/main/java/org/apache/maven/surefire/testng/TestSuite.java +++ b/surefire-providers/surefire-testng/src/main/java/org/apache/maven/surefire/testng/TestSuite.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.testng; /* @@ -19,44 +37,36 @@ * under the License. */ +import java.util.Map; + import org.apache.maven.surefire.api.report.ReporterException; import org.apache.maven.surefire.api.report.RunListener; import org.apache.maven.surefire.api.report.SimpleReportEntry; -import java.util.Map; - import static org.apache.maven.surefire.api.report.RunMode.NORMAL_RUN; import static org.apache.maven.surefire.api.util.internal.ObjectUtils.systemProps; /** * Abstract class which implements common functions. */ -abstract class TestSuite -{ +abstract class TestSuite { abstract Map getOptions(); - private String getSuiteName() - { - String result = getOptions().get( "suitename" ); + private String getSuiteName() { + String result = getOptions().get("suitename"); return result == null ? "TestSuite" : result; } - final void startTestSuite( RunListener reporterManager ) - { - try - { - reporterManager.testSetStarting( - new SimpleReportEntry( NORMAL_RUN, 0L, getSuiteName(), null, null, null ) ); - } - catch ( ReporterException e ) - { + final void startTestSuite(RunListener reporterManager) { + try { + reporterManager.testSetStarting(new SimpleReportEntry(NORMAL_RUN, 0L, getSuiteName(), null, null, null)); + } catch (ReporterException e) { // TODO: remove this exception from the report manager } } - final void finishTestSuite( RunListener reporterManager ) - { + final void finishTestSuite(RunListener reporterManager) { reporterManager.testSetCompleted( - new SimpleReportEntry( NORMAL_RUN, 0L, getSuiteName(), null, null, null, systemProps() ) ); + new SimpleReportEntry(NORMAL_RUN, 0L, getSuiteName(), null, null, null, systemProps())); } } diff --git a/surefire-providers/surefire-testng/src/main/java/org/apache/maven/surefire/testng/conf/AbstractDirectConfigurator.java b/surefire-providers/surefire-testng/src/main/java/org/apache/maven/surefire/testng/conf/AbstractDirectConfigurator.java index ed918f538c..e18d7985b2 100644 --- a/surefire-providers/surefire-testng/src/main/java/org/apache/maven/surefire/testng/conf/AbstractDirectConfigurator.java +++ b/surefire-providers/surefire-testng/src/main/java/org/apache/maven/surefire/testng/conf/AbstractDirectConfigurator.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.testng.conf; /* @@ -34,112 +52,87 @@ * Configurator that relies on reflection to set parameters in TestNG * */ -public abstract class AbstractDirectConfigurator - implements Configurator -{ +public abstract class AbstractDirectConfigurator implements Configurator { final Map setters; - AbstractDirectConfigurator() - { + AbstractDirectConfigurator() { Map options = new HashMap<>(); // options.put( ProviderParameterNames.TESTNG_GROUPS_PROP, new Setter( "setGroups", String.class ) ); // options.put( ProviderParameterNames.TESTNG_EXCLUDEDGROUPS_PROP, new Setter( "setExcludedGroups", String.class // ) ); - options.put( "junit", new Setter( "setJUnit", Boolean.class ) ); - options.put( ProviderParameterNames.THREADCOUNT_PROP, new Setter( "setThreadCount", int.class ) ); - options.put( "usedefaultlisteners", new Setter( "setUseDefaultListeners", boolean.class ) ); + options.put("junit", new Setter("setJUnit", Boolean.class)); + options.put(ProviderParameterNames.THREADCOUNT_PROP, new Setter("setThreadCount", int.class)); + options.put("usedefaultlisteners", new Setter("setUseDefaultListeners", boolean.class)); this.setters = options; } @Override - public void configure( TestNG testng, Map options ) - throws TestSetFailedException - { - System.out.println( "\n\n\n\nCONFIGURING TESTNG\n\n\n\n" ); + public void configure(TestNG testng, Map options) throws TestSetFailedException { + System.out.println("\n\n\n\nCONFIGURING TESTNG\n\n\n\n"); // kind of ugly, but listeners are configured differently - final String listeners = options.remove( "listener" ); + final String listeners = options.remove("listener"); // DGF In 4.7, default listeners dump XML files in the surefire-reports directory, // confusing the report plugin. This was fixed in later versions. - testng.setUseDefaultListeners( false ); - configureInstance( testng, options ); + testng.setUseDefaultListeners(false); + configureInstance(testng, options); // TODO: we should have the Profile so that we can decide if this is needed or not - testng.setListenerClasses( loadListenerClasses( listeners ) ); + testng.setListenerClasses(loadListenerClasses(listeners)); } @Override - public void configure( XmlSuite suite, Map options ) - throws TestSetFailedException - { - Map filtered = filterForSuite( options ); - configureInstance( suite, filtered ); + public void configure(XmlSuite suite, Map options) throws TestSetFailedException { + Map filtered = filterForSuite(options); + configureInstance(suite, filtered); } - protected Map filterForSuite( Map options ) - { + protected Map filterForSuite(Map options) { Map result = new HashMap<>(); - addPropIfNotNull( options, result, ProviderParameterNames.PARALLEL_PROP ); - addPropIfNotNull( options, result, ProviderParameterNames.THREADCOUNT_PROP ); + addPropIfNotNull(options, result, ProviderParameterNames.PARALLEL_PROP); + addPropIfNotNull(options, result, ProviderParameterNames.THREADCOUNT_PROP); return result; } - private void addPropIfNotNull( Map options, Map result, String prop ) - { - if ( options.containsKey( prop ) ) - { - result.put( prop, options.get( prop ) ); + private void addPropIfNotNull(Map options, Map result, String prop) { + if (options.containsKey(prop)) { + result.put(prop, options.get(prop)); } } - private void configureInstance( Object testngInstance, Map options ) - { - for ( Map.Entry entry : options.entrySet() ) - { + private void configureInstance(Object testngInstance, Map options) { + for (Map.Entry entry : options.entrySet()) { String key = entry.getKey(); String val = entry.getValue(); - Setter setter = setters.get( key ); - if ( setter != null ) - { - try - { - setter.invoke( testngInstance, val ); - } - catch ( Exception e ) - { - throw new RuntimeException( "Cannot set option " + key + " with value " + val, e ); + Setter setter = setters.get(key); + if (setter != null) { + try { + setter.invoke(testngInstance, val); + } catch (Exception e) { + throw new RuntimeException("Cannot set option " + key + " with value " + val, e); } } } } - static List loadListenerClasses( String listenerClasses ) - throws TestSetFailedException - { - if ( listenerClasses == null || listenerClasses.trim().isEmpty() ) - { + static List loadListenerClasses(String listenerClasses) throws TestSetFailedException { + if (listenerClasses == null || listenerClasses.trim().isEmpty()) { return new ArrayList<>(); } List classes = new ArrayList<>(); - String[] classNames = listenerClasses.split( "\\s*,\\s*(\\r?\\n)?\\s*" ); - for ( String className : classNames ) - { - Class clazz = loadClass( className ); - classes.add( clazz ); + String[] classNames = listenerClasses.split("\\s*,\\s*(\\r?\\n)?\\s*"); + for (String className : classNames) { + Class clazz = loadClass(className); + classes.add(clazz); } return classes; } - static Class loadClass( String className ) - throws TestSetFailedException - { - try - { - return Class.forName( className ); - } - catch ( Exception ex ) - { - throw new TestSetFailedException( "Cannot find listener class " + className, ex ); + static Class loadClass(String className) throws TestSetFailedException { + try { + return Class.forName(className); + } catch (Exception ex) { + throw new TestSetFailedException("Cannot find listener class " + className, ex); } } @@ -147,46 +140,36 @@ static Class loadClass( String className ) * Describes a property setter by method name and parameter class * */ - public static final class Setter - { + public static final class Setter { private final String setterName; private final Class paramClass; - public Setter( String name, Class clazz ) - { + public Setter(String name, Class clazz) { setterName = name; paramClass = clazz; } - public void invoke( Object target, String value ) - throws Exception - { - Method setter = target.getClass().getMethod( setterName, paramClass ); - if ( setter != null ) - { - setter.invoke( target, convertValue( value ) ); + public void invoke(Object target, String value) throws Exception { + Method setter = target.getClass().getMethod(setterName, paramClass); + if (setter != null) { + setter.invoke(target, convertValue(value)); } } - private Object convertValue( String value ) - { - if ( value == null ) - { + private Object convertValue(String value) { + if (value == null) { return null; } - if ( paramClass.isAssignableFrom( value.getClass() ) ) - { + if (paramClass.isAssignableFrom(value.getClass())) { return value; } - if ( Boolean.class.equals( paramClass ) || boolean.class.equals( paramClass ) ) - { - return Boolean.valueOf( value ); + if (Boolean.class.equals(paramClass) || boolean.class.equals(paramClass)) { + return Boolean.valueOf(value); } - if ( Integer.class.equals( paramClass ) || int.class.equals( paramClass ) ) - { - return Integer.valueOf( value ); + if (Integer.class.equals(paramClass) || int.class.equals(paramClass)) { + return Integer.valueOf(value); } return value; diff --git a/surefire-providers/surefire-testng/src/main/java/org/apache/maven/surefire/testng/conf/Configurator.java b/surefire-providers/surefire-testng/src/main/java/org/apache/maven/surefire/testng/conf/Configurator.java index af5143de89..f40b9878bc 100644 --- a/surefire-providers/surefire-testng/src/main/java/org/apache/maven/surefire/testng/conf/Configurator.java +++ b/surefire-providers/surefire-testng/src/main/java/org/apache/maven/surefire/testng/conf/Configurator.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.testng.conf; /* @@ -29,11 +47,8 @@ * Configurator for passing configuration properties to TestNG * */ -public interface Configurator -{ - void configure( TestNG testng, Map options ) - throws TestSetFailedException; +public interface Configurator { + void configure(TestNG testng, Map options) throws TestSetFailedException; - void configure ( XmlSuite suite, Map options ) - throws TestSetFailedException; + void configure(XmlSuite suite, Map options) throws TestSetFailedException; } diff --git a/surefire-providers/surefire-testng/src/main/java/org/apache/maven/surefire/testng/conf/TestNG4751Configurator.java b/surefire-providers/surefire-testng/src/main/java/org/apache/maven/surefire/testng/conf/TestNG4751Configurator.java index f55ab487ae..e2b2283b07 100644 --- a/surefire-providers/surefire-testng/src/main/java/org/apache/maven/surefire/testng/conf/TestNG4751Configurator.java +++ b/surefire-providers/surefire-testng/src/main/java/org/apache/maven/surefire/testng/conf/TestNG4751Configurator.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.testng.conf; /* @@ -34,11 +52,8 @@ * * @author Alex Popescu */ -public class TestNG4751Configurator - extends AbstractDirectConfigurator -{ - public TestNG4751Configurator() - { - setters.put( ProviderParameterNames.PARALLEL_PROP, new Setter( "setParallel", boolean.class ) ); +public class TestNG4751Configurator extends AbstractDirectConfigurator { + public TestNG4751Configurator() { + setters.put(ProviderParameterNames.PARALLEL_PROP, new Setter("setParallel", boolean.class)); } } diff --git a/surefire-providers/surefire-testng/src/main/java/org/apache/maven/surefire/testng/conf/TestNG510Configurator.java b/surefire-providers/surefire-testng/src/main/java/org/apache/maven/surefire/testng/conf/TestNG510Configurator.java index 7bbacf92a0..d9990dbd44 100644 --- a/surefire-providers/surefire-testng/src/main/java/org/apache/maven/surefire/testng/conf/TestNG510Configurator.java +++ b/surefire-providers/surefire-testng/src/main/java/org/apache/maven/surefire/testng/conf/TestNG510Configurator.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.testng.conf; /* @@ -19,30 +37,25 @@ * under the License. */ +import java.util.Map; + import org.apache.maven.surefire.api.testset.TestSetFailedException; import org.testng.xml.XmlSuite; -import java.util.Map; - /** * TestNG 5.10 configurator. Added support of dataproviderthreadcount. * * @since 2.19 */ -public class TestNG510Configurator - extends TestNGMapConfigurator -{ +public class TestNG510Configurator extends TestNGMapConfigurator { @Override - public void configure( XmlSuite suite, Map options ) - throws TestSetFailedException - { - super.configure( suite, options ); + public void configure(XmlSuite suite, Map options) throws TestSetFailedException { + super.configure(suite, options); - String dataProviderThreadCount = options.get( "dataproviderthreadcount" ); - if ( dataProviderThreadCount != null ) - { - suite.setDataProviderThreadCount( Integer.parseInt( dataProviderThreadCount ) ); + String dataProviderThreadCount = options.get("dataproviderthreadcount"); + if (dataProviderThreadCount != null) { + suite.setDataProviderThreadCount(Integer.parseInt(dataProviderThreadCount)); } } } diff --git a/surefire-providers/surefire-testng/src/main/java/org/apache/maven/surefire/testng/conf/TestNG513Configurator.java b/surefire-providers/surefire-testng/src/main/java/org/apache/maven/surefire/testng/conf/TestNG513Configurator.java index c201868871..edb8dedc09 100644 --- a/surefire-providers/surefire-testng/src/main/java/org/apache/maven/surefire/testng/conf/TestNG513Configurator.java +++ b/surefire-providers/surefire-testng/src/main/java/org/apache/maven/surefire/testng/conf/TestNG513Configurator.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.testng.conf; /* @@ -24,38 +42,30 @@ /** * TestNG 5.13 configurator. Changed: "reporterslist" need String instead of List<ReporterConfig>. */ -public class TestNG513Configurator - extends TestNG510Configurator -{ +public class TestNG513Configurator extends TestNG510Configurator { @Override - protected Object convertReporterConfig( Object val ) - { + protected Object convertReporterConfig(Object val) { return val; } @Override - protected Object convertListeners( String listenerClasses ) throws TestSetFailedException - { - return convertListenersString( listenerClasses ); + protected Object convertListeners(String listenerClasses) throws TestSetFailedException { + return convertListenersString(listenerClasses); } - static String convertListenersString( String listenerClasses ) - { - if ( listenerClasses == null || listenerClasses.trim().isEmpty() ) - { + static String convertListenersString(String listenerClasses) { + if (listenerClasses == null || listenerClasses.trim().isEmpty()) { return listenerClasses; } StringBuilder sb = new StringBuilder(); - String[] classNames = listenerClasses.split( "\\s*,\\s*(\\r?\\n)?\\s*" ); - for ( int i = 0; i < classNames.length; i++ ) - { + String[] classNames = listenerClasses.split("\\s*,\\s*(\\r?\\n)?\\s*"); + for (int i = 0; i < classNames.length; i++) { String className = classNames[i]; - sb.append( className ); - if ( i < classNames.length - 1 ) - { - sb.append( ',' ); + sb.append(className); + if (i < classNames.length - 1) { + sb.append(','); } } diff --git a/surefire-providers/surefire-testng/src/main/java/org/apache/maven/surefire/testng/conf/TestNG5141Configurator.java b/surefire-providers/surefire-testng/src/main/java/org/apache/maven/surefire/testng/conf/TestNG5141Configurator.java index c2bc1c6443..bab8fe7216 100644 --- a/surefire-providers/surefire-testng/src/main/java/org/apache/maven/surefire/testng/conf/TestNG5141Configurator.java +++ b/surefire-providers/surefire-testng/src/main/java/org/apache/maven/surefire/testng/conf/TestNG5141Configurator.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.testng.conf; /* @@ -24,15 +42,12 @@ /** * TestNG 5.14.1 configurator. Changed: "listener" use List instead of String. */ -public class TestNG5141Configurator - extends TestNG513Configurator -{ +public class TestNG5141Configurator extends TestNG513Configurator { @Override - protected Object convertListeners( String listenerClasses ) throws TestSetFailedException - { + protected Object convertListeners(String listenerClasses) throws TestSetFailedException { // TODO "configure(CommandLineArgs)", which should replace "configure(Map)", doesn't have the issue - throw new TestSetFailedException( "Due to an internal TestNG issue, " - + "the listener feature of TestNG is not supported with 5.14.1 and 5.14.2" ); + throw new TestSetFailedException("Due to an internal TestNG issue, " + + "the listener feature of TestNG is not supported with 5.14.1 and 5.14.2"); } } diff --git a/surefire-providers/surefire-testng/src/main/java/org/apache/maven/surefire/testng/conf/TestNG5143Configurator.java b/surefire-providers/surefire-testng/src/main/java/org/apache/maven/surefire/testng/conf/TestNG5143Configurator.java index a23ef52f1c..1c26ec4a7f 100644 --- a/surefire-providers/surefire-testng/src/main/java/org/apache/maven/surefire/testng/conf/TestNG5143Configurator.java +++ b/surefire-providers/surefire-testng/src/main/java/org/apache/maven/surefire/testng/conf/TestNG5143Configurator.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.testng.conf; /* @@ -20,39 +38,32 @@ */ import java.util.Map; + import org.apache.maven.surefire.api.testset.TestSetFailedException; /** * TestNG 5.14.3 configurator. Changed: "reporterslist" replaced by "reporter", * and "listener" can use String instead of List<Class>. */ -public class TestNG5143Configurator - extends TestNG5141Configurator -{ +public class TestNG5143Configurator extends TestNG5141Configurator { @Override - Map getConvertedOptions( Map options ) - throws TestSetFailedException - { - Map convertedOptions = super.getConvertedOptions( options ); - for ( Map.Entry entry : convertedOptions.entrySet() ) - { + Map getConvertedOptions(Map options) throws TestSetFailedException { + Map convertedOptions = super.getConvertedOptions(options); + for (Map.Entry entry : convertedOptions.entrySet()) { String key = entry.getKey(); - if ( "-reporterslist".equals( key ) ) - { - convertedOptions.remove( "-reporterslist" ); + if ("-reporterslist".equals(key)) { + convertedOptions.remove("-reporterslist"); Object value = entry.getValue(); - convertedOptions.put( "-reporter", value ); + convertedOptions.put("-reporter", value); break; } } return convertedOptions; } - @Override - protected Object convertListeners( String listenerClasses ) throws TestSetFailedException - { - return convertListenersString( listenerClasses ); + protected Object convertListeners(String listenerClasses) throws TestSetFailedException { + return convertListenersString(listenerClasses); } } diff --git a/surefire-providers/surefire-testng/src/main/java/org/apache/maven/surefire/testng/conf/TestNG52Configurator.java b/surefire-providers/surefire-testng/src/main/java/org/apache/maven/surefire/testng/conf/TestNG52Configurator.java index 55a77e914f..a83ff0fd6e 100644 --- a/surefire-providers/surefire-testng/src/main/java/org/apache/maven/surefire/testng/conf/TestNG52Configurator.java +++ b/surefire-providers/surefire-testng/src/main/java/org/apache/maven/surefire/testng/conf/TestNG52Configurator.java @@ -1,5 +1,3 @@ -package org.apache.maven.surefire.testng.conf; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.surefire.testng.conf; import org.apache.maven.surefire.api.booter.ProviderParameterNames; @@ -34,11 +33,8 @@ * * @author Alex Popescu */ -public class TestNG52Configurator - extends AbstractDirectConfigurator -{ - public TestNG52Configurator() - { - setters.put( ProviderParameterNames.PARALLEL_PROP, new Setter( "setParallel", String.class ) ); +public class TestNG52Configurator extends AbstractDirectConfigurator { + public TestNG52Configurator() { + setters.put(ProviderParameterNames.PARALLEL_PROP, new Setter("setParallel", String.class)); } } diff --git a/surefire-providers/surefire-testng/src/main/java/org/apache/maven/surefire/testng/conf/TestNG60Configurator.java b/surefire-providers/surefire-testng/src/main/java/org/apache/maven/surefire/testng/conf/TestNG60Configurator.java index 625a355738..3ef403acb4 100644 --- a/surefire-providers/surefire-testng/src/main/java/org/apache/maven/surefire/testng/conf/TestNG60Configurator.java +++ b/surefire-providers/surefire-testng/src/main/java/org/apache/maven/surefire/testng/conf/TestNG60Configurator.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.testng.conf; /* @@ -21,6 +39,7 @@ import java.util.Map; import java.util.Map.Entry; + import org.apache.maven.surefire.api.testset.TestSetFailedException; /** @@ -30,22 +49,16 @@ * @author Marvin Froeder * @since 2.13 */ -public class TestNG60Configurator - extends TestNG5143Configurator -{ +public class TestNG60Configurator extends TestNG5143Configurator { @Override - Map getConvertedOptions( Map options ) - throws TestSetFailedException - { - Map convertedOptions = super.getConvertedOptions( options ); - for ( Entry entry : convertedOptions.entrySet() ) - { + Map getConvertedOptions(Map options) throws TestSetFailedException { + Map convertedOptions = super.getConvertedOptions(options); + for (Entry entry : convertedOptions.entrySet()) { String key = entry.getKey(); - if ( "-objectfactory".equals( key ) || "-testrunfactory".equals( key ) ) - { + if ("-objectfactory".equals(key) || "-testrunfactory".equals(key)) { Class value = (Class) entry.getValue(); - convertedOptions.put( key, value.getName() ); + convertedOptions.put(key, value.getName()); break; } } diff --git a/surefire-providers/surefire-testng/src/main/java/org/apache/maven/surefire/testng/conf/TestNG740Configurator.java b/surefire-providers/surefire-testng/src/main/java/org/apache/maven/surefire/testng/conf/TestNG740Configurator.java index c6118b3249..b2d1f436b1 100644 --- a/surefire-providers/surefire-testng/src/main/java/org/apache/maven/surefire/testng/conf/TestNG740Configurator.java +++ b/surefire-providers/surefire-testng/src/main/java/org/apache/maven/surefire/testng/conf/TestNG740Configurator.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.testng.conf; /* @@ -19,11 +37,11 @@ * under the License. */ +import java.util.Map; + import org.apache.maven.surefire.api.testset.TestSetFailedException; import org.testng.xml.XmlSuite; -import java.util.Map; - import static org.apache.maven.surefire.api.booter.ProviderParameterNames.PARALLEL_PROP; import static org.apache.maven.surefire.api.util.ReflectionUtils.invokeSetter; import static org.apache.maven.surefire.api.util.ReflectionUtils.loadClass; @@ -35,36 +53,28 @@ * * @since 3.0.0-M6 */ -public class TestNG740Configurator - extends TestNG60Configurator -{ +public class TestNG740Configurator extends TestNG60Configurator { /** * Convert and apply the value of the [parallel] setting. *

    * NOTE: Since TestNG 7.4, the value of the {@code parallel} setting of the {@link XmlSuite} class has been * specified via a ParallelMode enumeration. This method converts the [parallel] setting specified in the * Surefire plugin configuration to its corresponding constant and applies this to the specified suite object. - * + * * @param suite TestNG {@link XmlSuite} object * @param options Surefire plugin configuration options * @throws TestSetFailedException if unable to convert specified [parallel] setting */ @Override - protected void configureParallel( XmlSuite suite, Map options ) - throws TestSetFailedException - { - String parallel = options.get( PARALLEL_PROP ); - if ( parallel != null ) - { - Class enumClass = loadClass( XmlSuite.class.getClassLoader(), "org.testng.xml.XmlSuite$ParallelMode" ); - try - { - Enum parallelEnum = Enum.valueOf( enumClass, parallel.toUpperCase() ); - invokeSetter( suite, "setParallel", enumClass, parallelEnum ); - } - catch ( IllegalArgumentException e ) - { - throw new TestSetFailedException( "Unsupported TestNG [parallel] setting: " + parallel, e ); + protected void configureParallel(XmlSuite suite, Map options) throws TestSetFailedException { + String parallel = options.get(PARALLEL_PROP); + if (parallel != null) { + Class enumClass = loadClass(XmlSuite.class.getClassLoader(), "org.testng.xml.XmlSuite$ParallelMode"); + try { + Enum parallelEnum = Enum.valueOf(enumClass, parallel.toUpperCase()); + invokeSetter(suite, "setParallel", enumClass, parallelEnum); + } catch (IllegalArgumentException e) { + throw new TestSetFailedException("Unsupported TestNG [parallel] setting: " + parallel, e); } } } diff --git a/surefire-providers/surefire-testng/src/main/java/org/apache/maven/surefire/testng/conf/TestNGMapConfigurator.java b/surefire-providers/surefire-testng/src/main/java/org/apache/maven/surefire/testng/conf/TestNGMapConfigurator.java index 874e7f1f3c..cf13f0b325 100755 --- a/surefire-providers/surefire-testng/src/main/java/org/apache/maven/surefire/testng/conf/TestNGMapConfigurator.java +++ b/surefire-providers/surefire-testng/src/main/java/org/apache/maven/surefire/testng/conf/TestNGMapConfigurator.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.testng.conf; /* @@ -45,155 +63,116 @@ * * @author Alex Popescu */ -public class TestNGMapConfigurator - implements Configurator -{ +public class TestNGMapConfigurator implements Configurator { @Override - public void configure( TestNG testng, Map options ) - throws TestSetFailedException - { - Map convertedOptions = getConvertedOptions( options ); - testng.configure( convertedOptions ); + public void configure(TestNG testng, Map options) throws TestSetFailedException { + Map convertedOptions = getConvertedOptions(options); + testng.configure(convertedOptions); } @Override - public void configure( XmlSuite suite, Map options ) - throws TestSetFailedException - { - configureThreadCount( suite, options ); - configureParallel( suite, options ); + public void configure(XmlSuite suite, Map options) throws TestSetFailedException { + configureThreadCount(suite, options); + configureParallel(suite, options); } - - protected void configureThreadCount( XmlSuite suite, Map options ) - throws TestSetFailedException - { - String threadCount = options.get( THREADCOUNT_PROP ); - if ( threadCount != null ) - { - try - { - suite.setThreadCount( Integer.parseInt( threadCount ) ); - } - catch ( NumberFormatException e ) - { - throw new TestSetFailedException( "Non-integer TestNG [threadcount] setting: " + threadCount, e ); + + protected void configureThreadCount(XmlSuite suite, Map options) throws TestSetFailedException { + String threadCount = options.get(THREADCOUNT_PROP); + if (threadCount != null) { + try { + suite.setThreadCount(Integer.parseInt(threadCount)); + } catch (NumberFormatException e) { + throw new TestSetFailedException("Non-integer TestNG [threadcount] setting: " + threadCount, e); } } } - - protected void configureParallel( XmlSuite suite, Map options ) - throws TestSetFailedException - { - String parallel = options.get( PARALLEL_PROP ); - if ( parallel != null ) - { - suite.setParallel( parallel ); + + protected void configureParallel(XmlSuite suite, Map options) throws TestSetFailedException { + String parallel = options.get(PARALLEL_PROP); + if (parallel != null) { + suite.setParallel(parallel); } } - Map getConvertedOptions( Map options ) - throws TestSetFailedException - { + Map getConvertedOptions(Map options) throws TestSetFailedException { Map convertedOptions = new HashMap<>(); - convertedOptions.put( "-mixed", false ); - for ( Map.Entry entry : options.entrySet() ) - { + convertedOptions.put("-mixed", false); + for (Map.Entry entry : options.entrySet()) { String key = entry.getKey(); Object val = entry.getValue(); - switch ( key ) - { + switch (key) { case "listener": - val = convertListeners( entry.getValue() ); + val = convertListeners(entry.getValue()); break; case "objectfactory": case "testrunfactory": - val = AbstractDirectConfigurator.loadClass( entry.getValue() ); + val = AbstractDirectConfigurator.loadClass(entry.getValue()); break; case "reporter": // for TestNG 5.6 or higher // TODO support multiple reporters? - val = convertReporterConfig( val ); + val = convertReporterConfig(val); key = "reporterslist"; break; case "junit": case "skipfailedinvocationcounts": case "mixed": case "group-by-instances": - val = convert( val, Boolean.class ); + val = convert(val, Boolean.class); break; case "configfailurepolicy": case THREADCOUNT_PROP: - val = convert( val, String.class ); + val = convert(val, String.class); break; - // for TestNG 6.9.7 or higher + // for TestNG 6.9.7 or higher case "suitethreadpoolsize": // for TestNG 5.10 or higher case "dataproviderthreadcount": - val = convert( val, Integer.class ); + val = convert(val, Integer.class); break; default: break; } - if ( key.startsWith( "-" ) ) - { - convertedOptions.put( key, val ); - } - else - { - convertedOptions.put( "-" + key, val ); + if (key.startsWith("-")) { + convertedOptions.put(key, val); + } else { + convertedOptions.put("-" + key, val); } } return convertedOptions; } // ReporterConfig only became available in later versions of TestNG - protected Object convertReporterConfig( Object val ) - { - try - { - Class reporterConfig = Class.forName( "org.testng.ReporterConfig" ); - Method deserialize = reporterConfig.getMethod( "deserialize", String.class ); - Object rc = deserialize.invoke( null, val ); + protected Object convertReporterConfig(Object val) { + try { + Class reporterConfig = Class.forName("org.testng.ReporterConfig"); + Method deserialize = reporterConfig.getMethod("deserialize", String.class); + Object rc = deserialize.invoke(null, val); ArrayList reportersList = new ArrayList<>(); - reportersList.add( rc ); + reportersList.add(rc); return reportersList; - } - catch ( Exception e ) - { + } catch (Exception e) { return val; } } - protected Object convertListeners( String listenerClasses ) throws TestSetFailedException - { - return loadListenerClasses( listenerClasses ); + protected Object convertListeners(String listenerClasses) throws TestSetFailedException { + return loadListenerClasses(listenerClasses); } - protected Object convert( Object val, Class type ) - { - if ( val == null ) - { + protected Object convert(Object val, Class type) { + if (val == null) { return null; - } - else if ( type.isAssignableFrom( val.getClass() ) ) - { + } else if (type.isAssignableFrom(val.getClass())) { return val; - } - else if ( ( type == Boolean.class || type == boolean.class ) && val.getClass() == String.class ) - { - return Boolean.valueOf( (String) val ); - } - else if ( ( type == Integer.class || type == int.class ) && val.getClass() == String.class ) - { - return Integer.valueOf( (String) val ); - } - else if ( type == String.class ) - { + } else if ((type == Boolean.class || type == boolean.class) && val.getClass() == String.class) { + return Boolean.valueOf((String) val); + } else if ((type == Integer.class || type == int.class) && val.getClass() == String.class) { + return Integer.valueOf((String) val); + } else if (type == String.class) { return val.toString(); - } - else - { + } else { return val; } } diff --git a/surefire-providers/surefire-testng/src/test/java/org/apache/maven/surefire/testng/TestNGReporterTest.java b/surefire-providers/surefire-testng/src/test/java/org/apache/maven/surefire/testng/TestNGReporterTest.java index 91068e7d23..59414776b9 100644 --- a/surefire-providers/surefire-testng/src/test/java/org/apache/maven/surefire/testng/TestNGReporterTest.java +++ b/surefire-providers/surefire-testng/src/test/java/org/apache/maven/surefire/testng/TestNGReporterTest.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.testng; /* @@ -39,219 +57,191 @@ /** * Tests for {@link TestNGReporter}. */ -@SuppressWarnings( "checkstyle:magicnumber" ) -public class TestNGReporterTest extends TestCase -{ - public void testParameterizedTestName() throws Exception - { - ITestNGMethod method = mock( ITestNGMethod.class ); - when( method.getCurrentInvocationCount() ).thenReturn( 3 ); - ITestResult testResult = mock( ITestResult.class ); - when( testResult.getName() ).thenReturn( "myTest" ); - when( testResult.getParameters() ).thenReturn( new String[] { "val1", "val2" } ); - when( testResult.getMethod() ).thenReturn( method ); - String testName = invokeMethod( TestNGReporter.class, "testName", testResult ); - assertThat( testName ) - .isEqualTo( "myTest[val1, val2](3)" ); +@SuppressWarnings("checkstyle:magicnumber") +public class TestNGReporterTest extends TestCase { + public void testParameterizedTestName() throws Exception { + ITestNGMethod method = mock(ITestNGMethod.class); + when(method.getCurrentInvocationCount()).thenReturn(3); + ITestResult testResult = mock(ITestResult.class); + when(testResult.getName()).thenReturn("myTest"); + when(testResult.getParameters()).thenReturn(new String[] {"val1", "val2"}); + when(testResult.getMethod()).thenReturn(method); + String testName = invokeMethod(TestNGReporter.class, "testName", testResult); + assertThat(testName).isEqualTo("myTest[val1, val2](3)"); } - public void testWithoutParameterizedTestName() throws Exception - { - ITestNGMethod method = mock( ITestNGMethod.class ); - ITestResult testResult = mock( ITestResult.class ); - when( testResult.getName() ).thenReturn( "myTest" ); - when( testResult.getMethod() ).thenReturn( method ); - String testName = invokeMethod( TestNGReporter.class, "testName", testResult ); - assertThat( testName ) - .isEqualTo( "myTest" ); + public void testWithoutParameterizedTestName() throws Exception { + ITestNGMethod method = mock(ITestNGMethod.class); + ITestResult testResult = mock(ITestResult.class); + when(testResult.getName()).thenReturn("myTest"); + when(testResult.getMethod()).thenReturn(method); + String testName = invokeMethod(TestNGReporter.class, "testName", testResult); + assertThat(testName).isEqualTo("myTest"); } - public void testOnTestStart() - { - ITestClass cls = mock( ITestClass.class ); - when( cls.getName() ).thenReturn( "pkg.MyClass" ); + public void testOnTestStart() { + ITestClass cls = mock(ITestClass.class); + when(cls.getName()).thenReturn("pkg.MyClass"); - ITestNGMethod method = mock( ITestNGMethod.class ); - when( method.getCurrentInvocationCount() ).thenReturn( 3 ); - when( method.getGroups() ).thenReturn( new String[0] ); + ITestNGMethod method = mock(ITestNGMethod.class); + when(method.getCurrentInvocationCount()).thenReturn(3); + when(method.getGroups()).thenReturn(new String[0]); - ITestResult testResult = mock( ITestResult.class ); - when( testResult.getTestClass() ).thenReturn( cls ); - when( testResult.getMethod() ).thenReturn( method ); - when( testResult.getName() ).thenReturn( "myTest" ); - when( testResult.getParameters() ).thenReturn( new String[] { "val1", "val2" } ); + ITestResult testResult = mock(ITestResult.class); + when(testResult.getTestClass()).thenReturn(cls); + when(testResult.getMethod()).thenReturn(method); + when(testResult.getName()).thenReturn("myTest"); + when(testResult.getParameters()).thenReturn(new String[] {"val1", "val2"}); - TestReportListener listener = mock( TestReportListener.class ); - TestNGReporter reporter = new TestNGReporter( listener ); - reporter.onTestStart( testResult ); + TestReportListener listener = mock(TestReportListener.class); + TestNGReporter reporter = new TestNGReporter(listener); + reporter.onTestStart(testResult); - ArgumentCaptor reportEntry = ArgumentCaptor.forClass( CategorizedReportEntry.class ); - verify( listener ).testStarting( reportEntry.capture() ); - verifyNoMoreInteractions( listener ); + ArgumentCaptor reportEntry = ArgumentCaptor.forClass(CategorizedReportEntry.class); + verify(listener).testStarting(reportEntry.capture()); + verifyNoMoreInteractions(listener); - assertThat( reportEntry.getValue().getTestRunId() ) - .isEqualTo( 0x0000000100000001L ); + assertThat(reportEntry.getValue().getTestRunId()).isEqualTo(0x0000000100000001L); - assertThat( reportEntry.getValue().getSourceName() ) - .isEqualTo( "pkg.MyClass" ); + assertThat(reportEntry.getValue().getSourceName()).isEqualTo("pkg.MyClass"); - assertThat( reportEntry.getValue().getName() ) - .isEqualTo( "myTest[val1, val2](3)" ); + assertThat(reportEntry.getValue().getName()).isEqualTo("myTest[val1, val2](3)"); } - public void testOnTestSuccess() - { - ITestClass cls = mock( ITestClass.class ); - when( cls.getName() ).thenReturn( "pkg.MyClass" ); + public void testOnTestSuccess() { + ITestClass cls = mock(ITestClass.class); + when(cls.getName()).thenReturn("pkg.MyClass"); - ITestNGMethod method = mock( ITestNGMethod.class ); - when( method.getCurrentInvocationCount() ).thenReturn( 3 ); + ITestNGMethod method = mock(ITestNGMethod.class); + when(method.getCurrentInvocationCount()).thenReturn(3); - ITestResult testResult = mock( ITestResult.class ); - when( testResult.getTestClass() ).thenReturn( cls ); - when( testResult.getMethod() ).thenReturn( method ); - when( testResult.getName() ).thenReturn( "myTest" ); - when( testResult.getParameters() ).thenReturn( new String[] { "val1", "val2" } ); + ITestResult testResult = mock(ITestResult.class); + when(testResult.getTestClass()).thenReturn(cls); + when(testResult.getMethod()).thenReturn(method); + when(testResult.getName()).thenReturn("myTest"); + when(testResult.getParameters()).thenReturn(new String[] {"val1", "val2"}); - TestReportListener listener = mock( TestReportListener.class ); - TestNGReporter reporter = new TestNGReporter( listener ); - reporter.onTestSuccess( testResult ); + TestReportListener listener = mock(TestReportListener.class); + TestNGReporter reporter = new TestNGReporter(listener); + reporter.onTestSuccess(testResult); - ArgumentCaptor reportEntry = ArgumentCaptor.forClass( SimpleReportEntry.class ); - verify( listener ).testSucceeded( reportEntry.capture() ); - verifyNoMoreInteractions( listener ); + ArgumentCaptor reportEntry = ArgumentCaptor.forClass(SimpleReportEntry.class); + verify(listener).testSucceeded(reportEntry.capture()); + verifyNoMoreInteractions(listener); - assertThat( reportEntry.getValue().getTestRunId() ) - .isEqualTo( 0x0000000100000001L ); + assertThat(reportEntry.getValue().getTestRunId()).isEqualTo(0x0000000100000001L); - assertThat( reportEntry.getValue().getSourceName() ) - .isEqualTo( "pkg.MyClass" ); + assertThat(reportEntry.getValue().getSourceName()).isEqualTo("pkg.MyClass"); - assertThat( reportEntry.getValue().getName() ) - .isEqualTo( "myTest[val1, val2](3)" ); + assertThat(reportEntry.getValue().getName()).isEqualTo("myTest[val1, val2](3)"); } - public void testOnTestFailure() - { + public void testOnTestFailure() { Exception stackTrace = new Exception(); - ITestClass cls = mock( ITestClass.class ); - when( cls.getName() ).thenReturn( getClass().getName() ); + ITestClass cls = mock(ITestClass.class); + when(cls.getName()).thenReturn(getClass().getName()); - ITestNGMethod method = mock( ITestNGMethod.class ); - when( method.getCurrentInvocationCount() ).thenReturn( 1 ); - when( method.getMethodName() ).thenReturn( "myTest" ); + ITestNGMethod method = mock(ITestNGMethod.class); + when(method.getCurrentInvocationCount()).thenReturn(1); + when(method.getMethodName()).thenReturn("myTest"); - ITestResult testResult = mock( ITestResult.class ); - when( testResult.getThrowable() ).thenReturn( stackTrace ); - when( cls.getRealClass() ).thenReturn( getClass() ); - when( testResult.getTestClass() ).thenReturn( cls ); - when( testResult.getMethod() ).thenReturn( method ); - when( testResult.getName() ).thenReturn( "myTest" ); - when( testResult.getParameters() ).thenReturn( new String[] { "val1", "val2" } ); + ITestResult testResult = mock(ITestResult.class); + when(testResult.getThrowable()).thenReturn(stackTrace); + when(cls.getRealClass()).thenReturn(getClass()); + when(testResult.getTestClass()).thenReturn(cls); + when(testResult.getMethod()).thenReturn(method); + when(testResult.getName()).thenReturn("myTest"); + when(testResult.getParameters()).thenReturn(new String[] {"val1", "val2"}); - TestReportListener listener = mock( TestReportListener.class ); - TestNGReporter reporter = new TestNGReporter( listener ); - reporter.onTestFailure( testResult ); + TestReportListener listener = mock(TestReportListener.class); + TestNGReporter reporter = new TestNGReporter(listener); + reporter.onTestFailure(testResult); - ArgumentCaptor reportEntry = ArgumentCaptor.forClass( SimpleReportEntry.class ); - verify( listener ).testFailed( reportEntry.capture() ); - verifyNoMoreInteractions( listener ); + ArgumentCaptor reportEntry = ArgumentCaptor.forClass(SimpleReportEntry.class); + verify(listener).testFailed(reportEntry.capture()); + verifyNoMoreInteractions(listener); - assertThat( reportEntry.getValue().getTestRunId() ) - .isEqualTo( 0x0000000100000001L ); + assertThat(reportEntry.getValue().getTestRunId()).isEqualTo(0x0000000100000001L); - assertThat( reportEntry.getValue().getSourceName() ) - .isEqualTo( getClass().getName() ); + assertThat(reportEntry.getValue().getSourceName()).isEqualTo(getClass().getName()); - assertThat( reportEntry.getValue().getName() ) - .isEqualTo( "myTest[val1, val2](1)" ); + assertThat(reportEntry.getValue().getName()).isEqualTo("myTest[val1, val2](1)"); - assertThat( reportEntry.getValue().getStackTraceWriter() ) - .isNotNull(); + assertThat(reportEntry.getValue().getStackTraceWriter()).isNotNull(); - assertThat( reportEntry.getValue().getStackTraceWriter().getThrowable().getTarget() ) - .isSameAs( stackTrace ); + assertThat(reportEntry.getValue().getStackTraceWriter().getThrowable().getTarget()) + .isSameAs(stackTrace); } - public void testOnSkippedTest() - { - Exception stackTrace = new Exception( "test skip reason" ); + public void testOnSkippedTest() { + Exception stackTrace = new Exception("test skip reason"); - ITestClass cls = mock( ITestClass.class ); - when( cls.getName() ).thenReturn( getClass().getName() ); + ITestClass cls = mock(ITestClass.class); + when(cls.getName()).thenReturn(getClass().getName()); - ITestNGMethod method = mock( ITestNGMethod.class ); - when( method.getCurrentInvocationCount() ).thenReturn( 1 ); + ITestNGMethod method = mock(ITestNGMethod.class); + when(method.getCurrentInvocationCount()).thenReturn(1); - ITestResult testResult = mock( ITestResult.class ); - when( testResult.getThrowable() ).thenReturn( stackTrace ); - when( testResult.getTestClass() ).thenReturn( cls ); - when( testResult.getMethod() ).thenReturn( method ); - when( testResult.getName() ).thenReturn( "myTest" ); - when( testResult.getParameters() ).thenReturn( new String[] { "val1", "val2" } ); + ITestResult testResult = mock(ITestResult.class); + when(testResult.getThrowable()).thenReturn(stackTrace); + when(testResult.getTestClass()).thenReturn(cls); + when(testResult.getMethod()).thenReturn(method); + when(testResult.getName()).thenReturn("myTest"); + when(testResult.getParameters()).thenReturn(new String[] {"val1", "val2"}); - TestReportListener listener = mock( TestReportListener.class ); - TestNGReporter reporter = new TestNGReporter( listener ); - reporter.onTestSkipped( testResult ); + TestReportListener listener = mock(TestReportListener.class); + TestNGReporter reporter = new TestNGReporter(listener); + reporter.onTestSkipped(testResult); - ArgumentCaptor reportEntry = ArgumentCaptor.forClass( SimpleReportEntry.class ); - verify( listener ).testSkipped( reportEntry.capture() ); - verifyNoMoreInteractions( listener ); + ArgumentCaptor reportEntry = ArgumentCaptor.forClass(SimpleReportEntry.class); + verify(listener).testSkipped(reportEntry.capture()); + verifyNoMoreInteractions(listener); - assertThat( reportEntry.getValue().getTestRunId() ) - .isEqualTo( 0x0000000100000001L ); + assertThat(reportEntry.getValue().getTestRunId()).isEqualTo(0x0000000100000001L); - assertThat( reportEntry.getValue().getSourceName() ) - .isEqualTo( getClass().getName() ); + assertThat(reportEntry.getValue().getSourceName()).isEqualTo(getClass().getName()); - assertThat( reportEntry.getValue().getName() ) - .isEqualTo( "myTest[val1, val2](1)" ); + assertThat(reportEntry.getValue().getName()).isEqualTo("myTest[val1, val2](1)"); - assertThat( reportEntry.getValue().getMessage() ) - .isEqualTo( stackTrace.getMessage() ); + assertThat(reportEntry.getValue().getMessage()).isEqualTo(stackTrace.getMessage()); } - public void testOnTestFailedButWithinSuccessPercentage() - { + public void testOnTestFailedButWithinSuccessPercentage() { Exception stackTrace = new Exception(); - ITestClass cls = mock( ITestClass.class ); - when( cls.getName() ).thenReturn( getClass().getName() ); + ITestClass cls = mock(ITestClass.class); + when(cls.getName()).thenReturn(getClass().getName()); - ITestNGMethod method = mock( ITestNGMethod.class ); - when( method.getCurrentInvocationCount() ).thenReturn( 1 ); - when( method.getMethodName() ).thenReturn( "myTest" ); + ITestNGMethod method = mock(ITestNGMethod.class); + when(method.getCurrentInvocationCount()).thenReturn(1); + when(method.getMethodName()).thenReturn("myTest"); - ITestResult testResult = mock( ITestResult.class ); - when( testResult.getThrowable() ).thenReturn( stackTrace ); - when( cls.getRealClass() ).thenReturn( getClass() ); - when( testResult.getTestClass() ).thenReturn( cls ); - when( testResult.getMethod() ).thenReturn( method ); - when( testResult.getName() ).thenReturn( "myTest" ); - when( testResult.getParameters() ).thenReturn( new String[] { "val1", "val2" } ); + ITestResult testResult = mock(ITestResult.class); + when(testResult.getThrowable()).thenReturn(stackTrace); + when(cls.getRealClass()).thenReturn(getClass()); + when(testResult.getTestClass()).thenReturn(cls); + when(testResult.getMethod()).thenReturn(method); + when(testResult.getName()).thenReturn("myTest"); + when(testResult.getParameters()).thenReturn(new String[] {"val1", "val2"}); - TestReportListener listener = mock( TestReportListener.class ); - TestNGReporter reporter = new TestNGReporter( listener ); - reporter.onTestFailedButWithinSuccessPercentage( testResult ); + TestReportListener listener = mock(TestReportListener.class); + TestNGReporter reporter = new TestNGReporter(listener); + reporter.onTestFailedButWithinSuccessPercentage(testResult); - ArgumentCaptor reportEntry = ArgumentCaptor.forClass( SimpleReportEntry.class ); - verify( listener ).testSucceeded( reportEntry.capture() ); - verifyNoMoreInteractions( listener ); + ArgumentCaptor reportEntry = ArgumentCaptor.forClass(SimpleReportEntry.class); + verify(listener).testSucceeded(reportEntry.capture()); + verifyNoMoreInteractions(listener); - assertThat( reportEntry.getValue().getTestRunId() ) - .isEqualTo( 0x0000000100000001L ); + assertThat(reportEntry.getValue().getTestRunId()).isEqualTo(0x0000000100000001L); - assertThat( reportEntry.getValue().getSourceName() ) - .isEqualTo( getClass().getName() ); + assertThat(reportEntry.getValue().getSourceName()).isEqualTo(getClass().getName()); - assertThat( reportEntry.getValue().getName() ) - .isEqualTo( "myTest[val1, val2](1)" ); + assertThat(reportEntry.getValue().getName()).isEqualTo("myTest[val1, val2](1)"); - assertThat( reportEntry.getValue().getStackTraceWriter() ) - .isNotNull(); + assertThat(reportEntry.getValue().getStackTraceWriter()).isNotNull(); - assertThat( reportEntry.getValue().getStackTraceWriter().getThrowable().getTarget() ) - .isSameAs( stackTrace ); + assertThat(reportEntry.getValue().getStackTraceWriter().getThrowable().getTarget()) + .isSameAs(stackTrace); } } diff --git a/surefire-providers/surefire-testng/src/test/java/org/apache/maven/surefire/testng/conf/TestNG513ConfiguratorTest.java b/surefire-providers/surefire-testng/src/test/java/org/apache/maven/surefire/testng/conf/TestNG513ConfiguratorTest.java index c6ef353672..23ad50fafc 100644 --- a/surefire-providers/surefire-testng/src/test/java/org/apache/maven/surefire/testng/conf/TestNG513ConfiguratorTest.java +++ b/surefire-providers/surefire-testng/src/test/java/org/apache/maven/surefire/testng/conf/TestNG513ConfiguratorTest.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.testng.conf; /* @@ -19,12 +37,12 @@ * under the License. */ -import junit.framework.TestCase; -import org.apache.maven.surefire.api.testset.TestSetFailedException; - import java.util.HashMap; import java.util.Map; +import junit.framework.TestCase; +import org.apache.maven.surefire.api.testset.TestSetFailedException; + import static org.apache.maven.surefire.testng.conf.TestNGMapConfiguratorTest.FIRST_LISTENER; import static org.apache.maven.surefire.testng.conf.TestNGMapConfiguratorTest.LISTENER_PROP; import static org.apache.maven.surefire.testng.conf.TestNGMapConfiguratorTest.SECOND_LISTENER; @@ -32,44 +50,32 @@ /** * */ -public class TestNG513ConfiguratorTest - extends TestCase -{ +public class TestNG513ConfiguratorTest extends TestCase { - public void testListenersOnSeparateLines() - throws Exception - { - String listenersOnSeveralLines = String.format( "%s , %n %s", - FIRST_LISTENER, SECOND_LISTENER ); - Map convertedOptions = getConvertedOptions( LISTENER_PROP, listenersOnSeveralLines ); - String listeners = (String) convertedOptions.get( String.format( "-%s", LISTENER_PROP ) ); - assertEquals( FIRST_LISTENER + "," + SECOND_LISTENER, listeners ); + public void testListenersOnSeparateLines() throws Exception { + String listenersOnSeveralLines = String.format("%s , %n %s", FIRST_LISTENER, SECOND_LISTENER); + Map convertedOptions = getConvertedOptions(LISTENER_PROP, listenersOnSeveralLines); + String listeners = (String) convertedOptions.get(String.format("-%s", LISTENER_PROP)); + assertEquals(FIRST_LISTENER + "," + SECOND_LISTENER, listeners); } - public void testListenersOnTheSameLine() - throws Exception - { - String listenersOnSeveralLines = String.format( "%s,%s", - FIRST_LISTENER, SECOND_LISTENER ); - Map convertedOptions = getConvertedOptions( LISTENER_PROP, listenersOnSeveralLines ); - String listeners = (String) convertedOptions.get( String.format( "-%s", LISTENER_PROP ) ); - assertEquals( FIRST_LISTENER + "," + SECOND_LISTENER, listeners ); + public void testListenersOnTheSameLine() throws Exception { + String listenersOnSeveralLines = String.format("%s,%s", FIRST_LISTENER, SECOND_LISTENER); + Map convertedOptions = getConvertedOptions(LISTENER_PROP, listenersOnSeveralLines); + String listeners = (String) convertedOptions.get(String.format("-%s", LISTENER_PROP)); + assertEquals(FIRST_LISTENER + "," + SECOND_LISTENER, listeners); } - public void testReporter() - throws Exception - { - Map convertedOptions = getConvertedOptions( "reporter", "classname" ); - String reporter = (String) convertedOptions.get( "-reporterslist" ); - assertEquals( "classname", reporter ); + public void testReporter() throws Exception { + Map convertedOptions = getConvertedOptions("reporter", "classname"); + String reporter = (String) convertedOptions.get("-reporterslist"); + assertEquals("classname", reporter); } - private Map getConvertedOptions( String key, String value ) - throws TestSetFailedException - { + private Map getConvertedOptions(String key, String value) throws TestSetFailedException { TestNGMapConfigurator testNGMapConfigurator = new TestNG513Configurator(); Map raw = new HashMap<>(); - raw.put( key, value ); - return testNGMapConfigurator.getConvertedOptions( raw ); + raw.put(key, value); + return testNGMapConfigurator.getConvertedOptions(raw); } } diff --git a/surefire-providers/surefire-testng/src/test/java/org/apache/maven/surefire/testng/conf/TestNG5141ConfiguratorTest.java b/surefire-providers/surefire-testng/src/test/java/org/apache/maven/surefire/testng/conf/TestNG5141ConfiguratorTest.java index 672735a0de..1658770926 100644 --- a/surefire-providers/surefire-testng/src/test/java/org/apache/maven/surefire/testng/conf/TestNG5141ConfiguratorTest.java +++ b/surefire-providers/surefire-testng/src/test/java/org/apache/maven/surefire/testng/conf/TestNG5141ConfiguratorTest.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.testng.conf; /* @@ -19,13 +37,13 @@ * under the License. */ -import junit.framework.TestCase; -import org.apache.maven.surefire.api.testset.TestSetFailedException; - import java.util.HashMap; import java.util.List; import java.util.Map; +import junit.framework.TestCase; +import org.apache.maven.surefire.api.testset.TestSetFailedException; + import static org.apache.maven.surefire.testng.conf.TestNGMapConfiguratorTest.FIRST_LISTENER; import static org.apache.maven.surefire.testng.conf.TestNGMapConfiguratorTest.LISTENER_PROP; import static org.apache.maven.surefire.testng.conf.TestNGMapConfiguratorTest.SECOND_LISTENER; @@ -33,46 +51,36 @@ /** * */ -public class TestNG5141ConfiguratorTest extends TestCase -{ +public class TestNG5141ConfiguratorTest extends TestCase { - public void testListenersOnSeparateLines() - { - try - { - String listenersOnSeveralLines = String.format( "%s , %n %s", FIRST_LISTENER, SECOND_LISTENER ); - Map convertedOptions = getConvertedOptions( LISTENER_PROP, listenersOnSeveralLines ); - List listeners = (List) convertedOptions.get( String.format( "-%s", LISTENER_PROP ) ); - assertEquals( 2, listeners.size() ); + public void testListenersOnSeparateLines() { + try { + String listenersOnSeveralLines = String.format("%s , %n %s", FIRST_LISTENER, SECOND_LISTENER); + Map convertedOptions = getConvertedOptions(LISTENER_PROP, listenersOnSeveralLines); + List listeners = (List) convertedOptions.get(String.format("-%s", LISTENER_PROP)); + assertEquals(2, listeners.size()); fail(); - } - catch ( TestSetFailedException e ) - { + } catch (TestSetFailedException e) { // TODO remove it when surefire will use "configure(CommandLineArgs)" } } - public void testListenersOnTheSameLine() - { - try - { - String listenersOnSeveralLines = String.format( "%s,%s", FIRST_LISTENER, SECOND_LISTENER ); - Map convertedOptions = getConvertedOptions( LISTENER_PROP, listenersOnSeveralLines ); - List listeners = (List) convertedOptions.get( String.format( "-%s", LISTENER_PROP ) ); - assertEquals( 2, listeners.size() ); + public void testListenersOnTheSameLine() { + try { + String listenersOnSeveralLines = String.format("%s,%s", FIRST_LISTENER, SECOND_LISTENER); + Map convertedOptions = getConvertedOptions(LISTENER_PROP, listenersOnSeveralLines); + List listeners = (List) convertedOptions.get(String.format("-%s", LISTENER_PROP)); + assertEquals(2, listeners.size()); fail(); - } - catch ( TestSetFailedException e ) - { + } catch (TestSetFailedException e) { // TODO remove it when surefire will use "configure(CommandLineArgs)" } } - private Map getConvertedOptions( String key, String value ) throws TestSetFailedException - { + private Map getConvertedOptions(String key, String value) throws TestSetFailedException { TestNGMapConfigurator testNGMapConfigurator = new TestNG5141Configurator(); Map raw = new HashMap<>(); - raw.put( key, value ); - return testNGMapConfigurator.getConvertedOptions( raw ); + raw.put(key, value); + return testNGMapConfigurator.getConvertedOptions(raw); } } diff --git a/surefire-providers/surefire-testng/src/test/java/org/apache/maven/surefire/testng/conf/TestNG5143ConfiguratorTest.java b/surefire-providers/surefire-testng/src/test/java/org/apache/maven/surefire/testng/conf/TestNG5143ConfiguratorTest.java index 4d874324fe..3ae364419c 100644 --- a/surefire-providers/surefire-testng/src/test/java/org/apache/maven/surefire/testng/conf/TestNG5143ConfiguratorTest.java +++ b/surefire-providers/surefire-testng/src/test/java/org/apache/maven/surefire/testng/conf/TestNG5143ConfiguratorTest.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.testng.conf; /* @@ -32,37 +50,32 @@ /** * */ -public class TestNG5143ConfiguratorTest extends TestCase -{ - public void testListenersOnSeparateLines() throws Exception - { - String listenersOnSeveralLines = String.format( "%s , %n %s", FIRST_LISTENER, SECOND_LISTENER ); - Map convertedOptions = getConvertedOptions( LISTENER_PROP, listenersOnSeveralLines ); - String listeners = (String) convertedOptions.get( String.format( "-%s", LISTENER_PROP ) ); - assertEquals( FIRST_LISTENER + "," + SECOND_LISTENER, listeners ); +public class TestNG5143ConfiguratorTest extends TestCase { + public void testListenersOnSeparateLines() throws Exception { + String listenersOnSeveralLines = String.format("%s , %n %s", FIRST_LISTENER, SECOND_LISTENER); + Map convertedOptions = getConvertedOptions(LISTENER_PROP, listenersOnSeveralLines); + String listeners = (String) convertedOptions.get(String.format("-%s", LISTENER_PROP)); + assertEquals(FIRST_LISTENER + "," + SECOND_LISTENER, listeners); } - public void testListenersOnTheSameLine() throws Exception - { - String listenersOnSeveralLines = String.format( "%s,%s", FIRST_LISTENER, SECOND_LISTENER ); - Map convertedOptions = getConvertedOptions( LISTENER_PROP, listenersOnSeveralLines ); - String listeners = (String) convertedOptions.get( String.format( "-%s", LISTENER_PROP ) ); - assertEquals( FIRST_LISTENER + "," + SECOND_LISTENER, listeners ); + public void testListenersOnTheSameLine() throws Exception { + String listenersOnSeveralLines = String.format("%s,%s", FIRST_LISTENER, SECOND_LISTENER); + Map convertedOptions = getConvertedOptions(LISTENER_PROP, listenersOnSeveralLines); + String listeners = (String) convertedOptions.get(String.format("-%s", LISTENER_PROP)); + assertEquals(FIRST_LISTENER + "," + SECOND_LISTENER, listeners); } - public void testReporter() throws Exception - { - Map convertedOptions = getConvertedOptions( "reporter", "classname" ); - assertNull( "classname", convertedOptions.get( "-reporterslist" ) ); - String reporter = (String) convertedOptions.get( "-reporter" ); - assertEquals( "classname", reporter ); + public void testReporter() throws Exception { + Map convertedOptions = getConvertedOptions("reporter", "classname"); + assertNull("classname", convertedOptions.get("-reporterslist")); + String reporter = (String) convertedOptions.get("-reporter"); + assertEquals("classname", reporter); } - private Map getConvertedOptions( String key, String value ) throws TestSetFailedException - { + private Map getConvertedOptions(String key, String value) throws TestSetFailedException { TestNGMapConfigurator testNGMapConfigurator = new TestNG5143Configurator(); Map raw = new HashMap<>(); - raw.put( key, value ); - return testNGMapConfigurator.getConvertedOptions( raw ); + raw.put(key, value); + return testNGMapConfigurator.getConvertedOptions(raw); } } diff --git a/surefire-providers/surefire-testng/src/test/java/org/apache/maven/surefire/testng/conf/TestNG60ConfiguratorTest.java b/surefire-providers/surefire-testng/src/test/java/org/apache/maven/surefire/testng/conf/TestNG60ConfiguratorTest.java index 2e3af9106c..1a36c10a98 100644 --- a/surefire-providers/surefire-testng/src/test/java/org/apache/maven/surefire/testng/conf/TestNG60ConfiguratorTest.java +++ b/surefire-providers/surefire-testng/src/test/java/org/apache/maven/surefire/testng/conf/TestNG60ConfiguratorTest.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.testng.conf; /* @@ -27,18 +45,14 @@ /** * @author Marvin Froeder */ -public class TestNG60ConfiguratorTest - extends TestCase -{ +public class TestNG60ConfiguratorTest extends TestCase { - public void testGetConvertedOptions() - throws Exception - { + public void testGetConvertedOptions() throws Exception { TestNGMapConfigurator testNGMapConfigurator = new TestNG60Configurator(); Map raw = new HashMap(); - raw.put( "objectfactory", "java.lang.String" ); - Map convertedOptions = testNGMapConfigurator.getConvertedOptions( raw ); - String objectfactory = (String) convertedOptions.get( "-objectfactory" ); - assertNotNull( objectfactory ); + raw.put("objectfactory", "java.lang.String"); + Map convertedOptions = testNGMapConfigurator.getConvertedOptions(raw); + String objectfactory = (String) convertedOptions.get("-objectfactory"); + assertNotNull(objectfactory); } } diff --git a/surefire-providers/surefire-testng/src/test/java/org/apache/maven/surefire/testng/conf/TestNGMapConfiguratorTest.java b/surefire-providers/surefire-testng/src/test/java/org/apache/maven/surefire/testng/conf/TestNGMapConfiguratorTest.java index c5c437cfc2..129ed1befb 100755 --- a/surefire-providers/surefire-testng/src/test/java/org/apache/maven/surefire/testng/conf/TestNGMapConfiguratorTest.java +++ b/surefire-providers/surefire-testng/src/test/java/org/apache/maven/surefire/testng/conf/TestNGMapConfiguratorTest.java @@ -1,3 +1,21 @@ +/* + * 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.maven.surefire.testng.conf; /* @@ -23,63 +41,55 @@ import java.util.List; import java.util.Map; -import org.apache.maven.surefire.api.testset.TestSetFailedException; - import junit.framework.TestCase; +import org.apache.maven.surefire.api.testset.TestSetFailedException; import org.testng.ReporterConfig; /** * @author Kristian Rosenvold */ -public class TestNGMapConfiguratorTest extends TestCase -{ +public class TestNGMapConfiguratorTest extends TestCase { public static final String FIRST_LISTENER = "org.testng.TestListenerAdapter"; public static final String SECOND_LISTENER = "org.testng.reporters.ExitCodeListener"; public static final String LISTENER_PROP = "listener"; - public void testGetConvertedOptions() throws Exception - { - Map convertedOptions = getConvertedOptions( "mixed", "true" ); - boolean bool = (Boolean) convertedOptions.get( "-mixed" ); - assertTrue( bool ); + public void testGetConvertedOptions() throws Exception { + Map convertedOptions = getConvertedOptions("mixed", "true"); + boolean bool = (Boolean) convertedOptions.get("-mixed"); + assertTrue(bool); } - public void testListenersOnSeparateLines() throws Exception - { - String listenersOnSeveralLines = String.format( "%s , %n %s", FIRST_LISTENER, SECOND_LISTENER ); - Map convertedOptions = getConvertedOptions( LISTENER_PROP, listenersOnSeveralLines ); - List listeners = (List) convertedOptions.get( String.format( "-%s", LISTENER_PROP ) ); - assertEquals( 2, listeners.size() ); + public void testListenersOnSeparateLines() throws Exception { + String listenersOnSeveralLines = String.format("%s , %n %s", FIRST_LISTENER, SECOND_LISTENER); + Map convertedOptions = getConvertedOptions(LISTENER_PROP, listenersOnSeveralLines); + List listeners = (List) convertedOptions.get(String.format("-%s", LISTENER_PROP)); + assertEquals(2, listeners.size()); } - public void testListenersOnTheSameLine() throws Exception - { - String listenersOnSeveralLines = String.format( "%s,%s", FIRST_LISTENER, SECOND_LISTENER ); - Map convertedOptions = getConvertedOptions( LISTENER_PROP, listenersOnSeveralLines ); - List listeners = (List) convertedOptions.get( String.format( "-%s", LISTENER_PROP ) ); - assertEquals( 2, listeners.size() ); + public void testListenersOnTheSameLine() throws Exception { + String listenersOnSeveralLines = String.format("%s,%s", FIRST_LISTENER, SECOND_LISTENER); + Map convertedOptions = getConvertedOptions(LISTENER_PROP, listenersOnSeveralLines); + List listeners = (List) convertedOptions.get(String.format("-%s", LISTENER_PROP)); + assertEquals(2, listeners.size()); } - public void testGroupByInstances() throws Exception - { - Map convertedOptions = getConvertedOptions( "group-by-instances", "true" ); - boolean bool = (Boolean) convertedOptions.get( "-group-by-instances" ); - assertTrue( bool ); + public void testGroupByInstances() throws Exception { + Map convertedOptions = getConvertedOptions("group-by-instances", "true"); + boolean bool = (Boolean) convertedOptions.get("-group-by-instances"); + assertTrue(bool); } - public void testReporter() throws Exception - { - Map convertedOptions = getConvertedOptions( "reporter", "classname" ); - List reporter = (List) convertedOptions.get( "-reporterslist" ); - ReporterConfig reporterConfig = reporter.get( 0 ); - assertEquals( "classname", reporterConfig.getClassName() ); + public void testReporter() throws Exception { + Map convertedOptions = getConvertedOptions("reporter", "classname"); + List reporter = (List) convertedOptions.get("-reporterslist"); + ReporterConfig reporterConfig = reporter.get(0); + assertEquals("classname", reporterConfig.getClassName()); } - private Map getConvertedOptions( String key, String value ) throws TestSetFailedException - { + private Map getConvertedOptions(String key, String value) throws TestSetFailedException { TestNGMapConfigurator testNGMapConfigurator = new TestNGMapConfigurator(); Map raw = new HashMap<>(); - raw.put( key, value ); - return testNGMapConfigurator.getConvertedOptions( raw ); + raw.put(key, value); + return testNGMapConfigurator.getConvertedOptions(raw); } } diff --git a/surefire-report-parser/pom.xml b/surefire-report-parser/pom.xml index 20d9a26313..baecc1951d 100644 --- a/surefire-report-parser/pom.xml +++ b/surefire-report-parser/pom.xml @@ -17,7 +17,6 @@ ~ specific language governing permissions and limitations ~ under the License. --> - 4.0.0 @@ -52,6 +51,9 @@ org.jacoco jacoco-maven-plugin + + jacoco.agent + jacoco-agent @@ -60,25 +62,23 @@ - - jacoco.agent - maven-surefire-plugin - - - org.apache.maven.surefire - surefire-shadefire - 3.0.0-M7 - - ${jvm.args.tests} ${jacoco.agent} **/JUnit4SuiteTest.java + + + org.apache.maven.surefire + surefire-shadefire + 3.0.0-M7 + + + diff --git a/surefire-report-parser/src/main/java/org/apache/maven/plugins/surefire/report/ReportTestCase.java b/surefire-report-parser/src/main/java/org/apache/maven/plugins/surefire/report/ReportTestCase.java index bd1429b55e..ac53c9182c 100644 --- a/surefire-report-parser/src/main/java/org/apache/maven/plugins/surefire/report/ReportTestCase.java +++ b/surefire-report-parser/src/main/java/org/apache/maven/plugins/surefire/report/ReportTestCase.java @@ -1,3 +1,21 @@ +/* + * 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.maven.plugins.surefire.report; /* @@ -24,8 +42,7 @@ /** * */ -public final class ReportTestCase -{ +public final class ReportTestCase { private String fullClassName; private String className; @@ -50,140 +67,116 @@ public final class ReportTestCase private boolean hasSkipped; - public String getName() - { + public String getName() { return name; } - public ReportTestCase setName( String name ) - { + public ReportTestCase setName(String name) { this.name = name; return this; } - public String getFullClassName() - { + public String getFullClassName() { return fullClassName; } - public ReportTestCase setFullClassName( String name ) - { + public ReportTestCase setFullClassName(String name) { fullClassName = name; return this; } - public String getClassName() - { + public String getClassName() { return className; } - public ReportTestCase setClassName( String name ) - { + public ReportTestCase setClassName(String name) { className = name; return this; } - public float getTime() - { + public float getTime() { return time; } - public ReportTestCase setTime( float time ) - { + public ReportTestCase setTime(float time) { this.time = time; return this; } - public String getFullName() - { + public String getFullName() { return fullName; } - public ReportTestCase setFullName( String fullName ) - { + public ReportTestCase setFullName(String fullName) { this.fullName = fullName; return this; } - public String getFailureMessage() - { + public String getFailureMessage() { return failureMessage; } - private ReportTestCase setFailureMessage( String failureMessage ) - { + private ReportTestCase setFailureMessage(String failureMessage) { this.failureMessage = failureMessage; return this; } - public String getFailureType() - { + public String getFailureType() { return failureType; } - public String getFailureErrorLine() - { + public String getFailureErrorLine() { return failureErrorLine; } - public ReportTestCase setFailureErrorLine( String failureErrorLine ) - { + public ReportTestCase setFailureErrorLine(String failureErrorLine) { this.failureErrorLine = failureErrorLine; return this; } - public String getFailureDetail() - { + public String getFailureDetail() { return failureDetail; } - public ReportTestCase setFailureDetail( String failureDetail ) - { + public ReportTestCase setFailureDetail(String failureDetail) { this.failureDetail = failureDetail; return this; } - public ReportTestCase setFailure( String message, String type ) - { - hasFailure = isNotBlank( type ); + public ReportTestCase setFailure(String message, String type) { + hasFailure = isNotBlank(type); hasError = false; hasSkipped = false; - return setFailureMessage( message ).setFailureType( type ); + return setFailureMessage(message).setFailureType(type); } - public ReportTestCase setError( String message, String type ) - { + public ReportTestCase setError(String message, String type) { hasFailure = false; - hasError = isNotBlank( type ); + hasError = isNotBlank(type); hasSkipped = false; - return setFailureMessage( message ).setFailureType( type ); + return setFailureMessage(message).setFailureType(type); } - public ReportTestCase setSkipped( String message ) - { + public ReportTestCase setSkipped(String message) { hasFailure = false; hasError = false; - hasSkipped = isNotBlank( message ); - return setFailureMessage( message ).setFailureType( "skipped" ); + hasSkipped = isNotBlank(message); + return setFailureMessage(message).setFailureType("skipped"); } - public boolean isSuccessful() - { + public boolean isSuccessful() { return !hasFailure() && !hasError() && !hasSkipped(); } - public boolean hasFailure() - { + public boolean hasFailure() { return hasFailure; } - public boolean hasError() - { + public boolean hasError() { return hasError; } - public boolean hasSkipped() - { + public boolean hasSkipped() { return hasSkipped; } @@ -191,13 +184,11 @@ public boolean hasSkipped() * {@inheritDoc} */ @Override - public String toString() - { + public String toString() { return fullName; } - private ReportTestCase setFailureType( String failureType ) - { + private ReportTestCase setFailureType(String failureType) { this.failureType = failureType; return this; } diff --git a/surefire-report-parser/src/main/java/org/apache/maven/plugins/surefire/report/ReportTestSuite.java b/surefire-report-parser/src/main/java/org/apache/maven/plugins/surefire/report/ReportTestSuite.java index 59e0e90f1d..a13725666e 100644 --- a/surefire-report-parser/src/main/java/org/apache/maven/plugins/surefire/report/ReportTestSuite.java +++ b/surefire-report-parser/src/main/java/org/apache/maven/plugins/surefire/report/ReportTestSuite.java @@ -1,3 +1,21 @@ +/* + * 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.maven.plugins.surefire.report; /* @@ -25,8 +43,7 @@ /** * */ -public final class ReportTestSuite -{ +public final class ReportTestSuite { private final List testCases = new ArrayList<>(); private int numberOfErrors; @@ -47,141 +64,117 @@ public final class ReportTestSuite private float timeElapsed; - public List getTestCases() - { + public List getTestCases() { return testCases; } - public int getNumberOfErrors() - { + public int getNumberOfErrors() { return numberOfErrors; } - public ReportTestSuite setNumberOfErrors( int numberOfErrors ) - { + public ReportTestSuite setNumberOfErrors(int numberOfErrors) { this.numberOfErrors = numberOfErrors; return this; } - public ReportTestSuite incrementNumberOfErrors() - { + public ReportTestSuite incrementNumberOfErrors() { ++numberOfErrors; return this; } - public int getNumberOfFailures() - { + public int getNumberOfFailures() { return numberOfFailures; } - public ReportTestSuite setNumberOfFailures( int numberOfFailures ) - { + public ReportTestSuite setNumberOfFailures(int numberOfFailures) { this.numberOfFailures = numberOfFailures; return this; } - public ReportTestSuite incrementNumberOfFailures() - { + public ReportTestSuite incrementNumberOfFailures() { ++numberOfFailures; return this; } - public int getNumberOfSkipped() - { + public int getNumberOfSkipped() { return numberOfSkipped; } - public ReportTestSuite setNumberOfSkipped( int numberOfSkipped ) - { + public ReportTestSuite setNumberOfSkipped(int numberOfSkipped) { this.numberOfSkipped = numberOfSkipped; return this; } - public ReportTestSuite incrementNumberOfSkipped() - { + public ReportTestSuite incrementNumberOfSkipped() { ++numberOfSkipped; return this; } - public int getNumberOfFlakes() - { + public int getNumberOfFlakes() { return numberOfFlakes; } - public ReportTestSuite setNumberOfFlakes( int numberOfFlakes ) - { + public ReportTestSuite setNumberOfFlakes(int numberOfFlakes) { this.numberOfFlakes = numberOfFlakes; return this; } - public ReportTestSuite incrementNumberOfFlakes() - { + public ReportTestSuite incrementNumberOfFlakes() { ++numberOfFlakes; return this; } - public int getNumberOfTests() - { + public int getNumberOfTests() { return numberOfTests == null ? testCases.size() : numberOfTests; } - public ReportTestSuite setNumberOfTests( int numberOfTests ) - { + public ReportTestSuite setNumberOfTests(int numberOfTests) { this.numberOfTests = numberOfTests; return this; } - public String getName() - { + public String getName() { return name; } - public ReportTestSuite setName( String name ) - { + public ReportTestSuite setName(String name) { this.name = name; return this; } - public String getFullClassName() - { + public String getFullClassName() { return fullClassName; } - public ReportTestSuite setFullClassName( String fullClassName ) - { + public ReportTestSuite setFullClassName(String fullClassName) { this.fullClassName = fullClassName; - int lastDotPosition = fullClassName.lastIndexOf( "." ); - name = fullClassName.substring( lastDotPosition + 1, fullClassName.length() ); - packageName = lastDotPosition == -1 ? "" : fullClassName.substring( 0, lastDotPosition ); + int lastDotPosition = fullClassName.lastIndexOf("."); + name = fullClassName.substring(lastDotPosition + 1, fullClassName.length()); + packageName = lastDotPosition == -1 ? "" : fullClassName.substring(0, lastDotPosition); return this; } - public String getPackageName() - { + public String getPackageName() { return packageName; } - public ReportTestSuite setPackageName( String packageName ) - { + public ReportTestSuite setPackageName(String packageName) { this.packageName = packageName; return this; } - public float getTimeElapsed() - { + public float getTimeElapsed() { return this.timeElapsed; } - public ReportTestSuite setTimeElapsed( float timeElapsed ) - { + public ReportTestSuite setTimeElapsed(float timeElapsed) { this.timeElapsed = timeElapsed; return this; } - ReportTestSuite setTestCases( List testCases ) - { + ReportTestSuite setTestCases(List testCases) { this.testCases.clear(); - this.testCases.addAll( testCases ); + this.testCases.addAll(testCases); return this; } @@ -189,9 +182,8 @@ ReportTestSuite setTestCases( List testCases ) * {@inheritDoc} */ @Override - public String toString() - { - return fullClassName + " [" + getNumberOfTests() + "/" + getNumberOfFailures() + "/" - + getNumberOfErrors() + "/" + getNumberOfSkipped() + "]"; + public String toString() { + return fullClassName + " [" + getNumberOfTests() + "/" + getNumberOfFailures() + "/" + getNumberOfErrors() + "/" + + getNumberOfSkipped() + "]"; } } diff --git a/surefire-report-parser/src/main/java/org/apache/maven/plugins/surefire/report/SurefireReportParser.java b/surefire-report-parser/src/main/java/org/apache/maven/plugins/surefire/report/SurefireReportParser.java index f6e644ff74..0ce45bcec9 100644 --- a/surefire-report-parser/src/main/java/org/apache/maven/plugins/surefire/report/SurefireReportParser.java +++ b/surefire-report-parser/src/main/java/org/apache/maven/plugins/surefire/report/SurefireReportParser.java @@ -1,3 +1,21 @@ +/* + * 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.maven.plugins.surefire.report; /* @@ -19,6 +37,8 @@ * under the License. */ +import javax.xml.parsers.ParserConfigurationException; + import java.io.File; import java.io.IOException; import java.text.NumberFormat; @@ -29,8 +49,6 @@ import java.util.Locale; import java.util.Map; -import javax.xml.parsers.ParserConfigurationException; - import org.apache.maven.plugin.surefire.log.api.ConsoleLogger; import org.apache.maven.reporting.MavenReportException; import org.apache.maven.shared.utils.io.DirectoryScanner; @@ -41,12 +59,11 @@ /** * */ -public final class SurefireReportParser -{ +public final class SurefireReportParser { private static final String INCLUDES = "*.xml"; private static final String EXCLUDES = - "*.txt, testng-failed.xml, testng-failures.xml, testng-results.xml, failsafe-summary*.xml"; + "*.txt, testng-failed.xml, testng-failures.xml, testng-results.xml, failsafe-summary*.xml"; private static final int PCENT = 100; @@ -58,53 +75,38 @@ public final class SurefireReportParser private final List reportsDirectories; - public SurefireReportParser( List reportsDirectories, Locale locale, ConsoleLogger consoleLogger ) - { + public SurefireReportParser(List reportsDirectories, Locale locale, ConsoleLogger consoleLogger) { this.reportsDirectories = reportsDirectories; - numberFormat = NumberFormat.getInstance( locale ); + numberFormat = NumberFormat.getInstance(locale); this.consoleLogger = consoleLogger; } - public List parseXMLReportFiles() - throws MavenReportException - { + public List parseXMLReportFiles() throws MavenReportException { final Collection xmlReportFiles = new ArrayList<>(); - for ( File reportsDirectory : reportsDirectories ) - { - if ( reportsDirectory.exists() ) - { - for ( String xmlReportFile : getIncludedFiles( reportsDirectory, INCLUDES, EXCLUDES ) ) - { - xmlReportFiles.add( new File( reportsDirectory, xmlReportFile ) ); + for (File reportsDirectory : reportsDirectories) { + if (reportsDirectory.exists()) { + for (String xmlReportFile : getIncludedFiles(reportsDirectory, INCLUDES, EXCLUDES)) { + xmlReportFiles.add(new File(reportsDirectory, xmlReportFile)); } } } - final TestSuiteXmlParser parser = new TestSuiteXmlParser( consoleLogger ); - for ( File aXmlReportFileList : xmlReportFiles ) - { - try - { - testSuites.addAll( parser.parse( aXmlReportFileList.getAbsolutePath() ) ); - } - catch ( ParserConfigurationException e ) - { - throw new MavenReportException( "Error setting up parser for JUnit XML report", e ); - } - catch ( SAXException e ) - { - throw new MavenReportException( "Error parsing JUnit XML report " + aXmlReportFileList, e ); - } - catch ( IOException e ) - { - throw new MavenReportException( "Error reading JUnit XML report " + aXmlReportFileList, e ); + final TestSuiteXmlParser parser = new TestSuiteXmlParser(consoleLogger); + for (File aXmlReportFileList : xmlReportFiles) { + try { + testSuites.addAll(parser.parse(aXmlReportFileList.getAbsolutePath())); + } catch (ParserConfigurationException e) { + throw new MavenReportException("Error setting up parser for JUnit XML report", e); + } catch (SAXException e) { + throw new MavenReportException("Error parsing JUnit XML report " + aXmlReportFileList, e); + } catch (IOException e) { + throw new MavenReportException("Error reading JUnit XML report " + aXmlReportFileList, e); } } return testSuites; } - public Map getSummary( List suites ) - { + public Map getSummary(List suites) { Map totalSummary = new HashMap<>(); int totalNumberOfTests = 0; @@ -117,8 +119,7 @@ public Map getSummary( List suites ) float totalElapsedTime = 0.0f; - for ( ReportTestSuite suite : suites ) - { + for (ReportTestSuite suite : suites) { totalNumberOfTests += suite.getNumberOfTests(); totalNumberOfErrors += suite.getNumberOfErrors(); @@ -131,67 +132,57 @@ public Map getSummary( List suites ) } String totalPercentage = - computePercentage( totalNumberOfTests, totalNumberOfErrors, totalNumberOfFailures, totalNumberOfSkipped ); + computePercentage(totalNumberOfTests, totalNumberOfErrors, totalNumberOfFailures, totalNumberOfSkipped); - totalSummary.put( "totalTests", Integer.toString( totalNumberOfTests ) ); + totalSummary.put("totalTests", Integer.toString(totalNumberOfTests)); - totalSummary.put( "totalErrors", Integer.toString( totalNumberOfErrors ) ); + totalSummary.put("totalErrors", Integer.toString(totalNumberOfErrors)); - totalSummary.put( "totalFailures", Integer.toString( totalNumberOfFailures ) ); + totalSummary.put("totalFailures", Integer.toString(totalNumberOfFailures)); - totalSummary.put( "totalSkipped", Integer.toString( totalNumberOfSkipped ) ); + totalSummary.put("totalSkipped", Integer.toString(totalNumberOfSkipped)); - totalSummary.put( "totalElapsedTime", numberFormat.format( totalElapsedTime ) ); + totalSummary.put("totalElapsedTime", numberFormat.format(totalElapsedTime)); - totalSummary.put( "totalPercentage", totalPercentage ); + totalSummary.put("totalPercentage", totalPercentage); return totalSummary; } - public NumberFormat getNumberFormat() - { + public NumberFormat getNumberFormat() { return numberFormat; } - public Map> getSuitesGroupByPackage( List testSuitesList ) - { + public Map> getSuitesGroupByPackage(List testSuitesList) { Map> suitePackage = new HashMap<>(); - for ( ReportTestSuite suite : testSuitesList ) - { + for (ReportTestSuite suite : testSuitesList) { List suiteList = new ArrayList<>(); - if ( suitePackage.get( suite.getPackageName() ) != null ) - { - suiteList = suitePackage.get( suite.getPackageName() ); + if (suitePackage.get(suite.getPackageName()) != null) { + suiteList = suitePackage.get(suite.getPackageName()); } - suiteList.add( suite ); + suiteList.add(suite); - suitePackage.put( suite.getPackageName(), suiteList ); + suitePackage.put(suite.getPackageName(), suiteList); } return suitePackage; } - public String computePercentage( int tests, int errors, int failures, int skipped ) - { - float percentage = - tests == 0 ? 0 : ( (float) ( tests - errors - failures - skipped ) / (float) tests ) * PCENT; - return numberFormat.format( percentage ); + public String computePercentage(int tests, int errors, int failures, int skipped) { + float percentage = tests == 0 ? 0 : ((float) (tests - errors - failures - skipped) / (float) tests) * PCENT; + return numberFormat.format(percentage); } - public List getFailureDetails( List testSuites ) - { + public List getFailureDetails(List testSuites) { List failureDetails = new ArrayList<>(); - for ( ReportTestSuite suite : testSuites ) - { - for ( ReportTestCase tCase : suite.getTestCases() ) - { - if ( !tCase.isSuccessful() ) - { - failureDetails.add( tCase ); + for (ReportTestSuite suite : testSuites) { + for (ReportTestCase tCase : suite.getTestCases()) { + if (!tCase.isSuccessful()) { + failureDetails.add(tCase); } } } @@ -205,21 +196,20 @@ public List getFailureDetails( List testSuites * @param directory the directory * @return {@code true} if the specified directory contains at least one report file. */ - public static boolean hasReportFiles( File directory ) - { - return directory != null && directory.isDirectory() - && getIncludedFiles( directory, INCLUDES, EXCLUDES ).length != 0; + public static boolean hasReportFiles(File directory) { + return directory != null + && directory.isDirectory() + && getIncludedFiles(directory, INCLUDES, EXCLUDES).length != 0; } - private static String[] getIncludedFiles( File directory, String includes, String excludes ) - { + private static String[] getIncludedFiles(File directory, String includes, String excludes) { DirectoryScanner scanner = new DirectoryScanner(); - scanner.setBasedir( directory ); + scanner.setBasedir(directory); - scanner.setIncludes( split( includes, "," ) ); + scanner.setIncludes(split(includes, ",")); - scanner.setExcludes( split( excludes, "," ) ); + scanner.setExcludes(split(excludes, ",")); scanner.scan(); diff --git a/surefire-report-parser/src/main/java/org/apache/maven/plugins/surefire/report/TestSuiteXmlParser.java b/surefire-report-parser/src/main/java/org/apache/maven/plugins/surefire/report/TestSuiteXmlParser.java index e470af2328..485750457a 100644 --- a/surefire-report-parser/src/main/java/org/apache/maven/plugins/surefire/report/TestSuiteXmlParser.java +++ b/surefire-report-parser/src/main/java/org/apache/maven/plugins/surefire/report/TestSuiteXmlParser.java @@ -1,3 +1,21 @@ +/* + * 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.maven.plugins.surefire.report; /* @@ -19,6 +37,10 @@ * under the License. */ +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.parsers.SAXParser; +import javax.xml.parsers.SAXParserFactory; + import java.io.File; import java.io.FileInputStream; import java.io.IOException; @@ -30,10 +52,6 @@ import java.util.List; import java.util.Map; -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.parsers.SAXParser; -import javax.xml.parsers.SAXParserFactory; - import org.apache.maven.plugin.surefire.log.api.ConsoleLogger; import org.xml.sax.Attributes; import org.xml.sax.InputSource; @@ -47,10 +65,8 @@ /** * */ -public final class TestSuiteXmlParser - extends DefaultHandler -{ - private final NumberFormat numberFormat = NumberFormat.getInstance( ENGLISH ); +public final class TestSuiteXmlParser extends DefaultHandler { + private final NumberFormat numberFormat = NumberFormat.getInstance(ENGLISH); private final ConsoleLogger consoleLogger; @@ -68,24 +84,19 @@ public final class TestSuiteXmlParser private boolean valid; - public TestSuiteXmlParser( ConsoleLogger consoleLogger ) - { + public TestSuiteXmlParser(ConsoleLogger consoleLogger) { this.consoleLogger = consoleLogger; } - public List parse( String xmlPath ) - throws ParserConfigurationException, SAXException, IOException - { - File f = new File( xmlPath ); - try ( InputStreamReader stream = new InputStreamReader( new FileInputStream( f ), UTF_8 ) ) - { - return parse( stream ); + public List parse(String xmlPath) throws ParserConfigurationException, SAXException, IOException { + File f = new File(xmlPath); + try (InputStreamReader stream = new InputStreamReader(new FileInputStream(f), UTF_8)) { + return parse(stream); } } - public List parse( InputStreamReader stream ) - throws ParserConfigurationException, SAXException, IOException - { + public List parse(InputStreamReader stream) + throws ParserConfigurationException, SAXException, IOException { SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser saxParser = factory.newSAXParser(); @@ -95,13 +106,13 @@ public List parse( InputStreamReader stream ) classesToSuitesIndex = new HashMap<>(); suites = new ArrayList<>(); - saxParser.parse( new InputSource( stream ), this ); + saxParser.parse(new InputSource(stream), this); - if ( currentSuite != defaultSuite ) - { // omit the defaultSuite if it's empty and there are alternatives - if ( defaultSuite.getNumberOfTests() == 0 ) - { - suites.remove( classesToSuitesIndex.get( defaultSuite.getFullClassName() ).intValue() ); + if (currentSuite != defaultSuite) { // omit the defaultSuite if it's empty and there are alternatives + if (defaultSuite.getNumberOfTests() == 0) { + suites.remove(classesToSuitesIndex + .get(defaultSuite.getFullClassName()) + .intValue()); } } @@ -112,88 +123,74 @@ public List parse( InputStreamReader stream ) * {@inheritDoc} */ @Override - public void startElement( String uri, String localName, String qName, Attributes attributes ) - throws SAXException - { - if ( valid ) - { - try - { - switch ( qName ) - { + public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { + if (valid) { + try { + switch (qName) { case "testsuite": defaultSuite = new ReportTestSuite(); currentSuite = defaultSuite; - try - { - Number time = numberFormat.parse( attributes.getValue( "time" ) ); + try { + Number time = numberFormat.parse(attributes.getValue("time")); - defaultSuite.setTimeElapsed( time.floatValue() ); - } - catch ( NullPointerException e ) - { - consoleLogger.error( "WARNING: no time attribute found on testsuite element" ); + defaultSuite.setTimeElapsed(time.floatValue()); + } catch (NullPointerException e) { + consoleLogger.error("WARNING: no time attribute found on testsuite element"); } - final String name = attributes.getValue( "name" ); - final String group = attributes.getValue( "group" ); - defaultSuite.setFullClassName( isBlank( group ) - ? /*name is full class name*/ name - : /*group is package name*/ group + "." + name ); + final String name = attributes.getValue("name"); + final String group = attributes.getValue("group"); + defaultSuite.setFullClassName( + isBlank(group) + ? /*name is full class name*/ name + : /*group is package name*/ group + "." + name); - suites.add( defaultSuite ); - classesToSuitesIndex.put( defaultSuite.getFullClassName(), suites.size() - 1 ); + suites.add(defaultSuite); + classesToSuitesIndex.put(defaultSuite.getFullClassName(), suites.size() - 1); break; case "testcase": currentElement = new StringBuilder(); - testCase = new ReportTestCase() - .setName( attributes.getValue( "name" ) ); + testCase = new ReportTestCase().setName(attributes.getValue("name")); - String fullClassName = attributes.getValue( "classname" ); + String fullClassName = attributes.getValue("classname"); // if the testcase declares its own classname, it may need to belong to its own suite - if ( fullClassName != null ) - { - Integer currentSuiteIndex = classesToSuitesIndex.get( fullClassName ); - if ( currentSuiteIndex == null ) - { - currentSuite = new ReportTestSuite() - .setFullClassName( fullClassName ); - suites.add( currentSuite ); - classesToSuitesIndex.put( fullClassName, suites.size() - 1 ); - } - else - { - currentSuite = suites.get( currentSuiteIndex ); + if (fullClassName != null) { + Integer currentSuiteIndex = classesToSuitesIndex.get(fullClassName); + if (currentSuiteIndex == null) { + currentSuite = new ReportTestSuite().setFullClassName(fullClassName); + suites.add(currentSuite); + classesToSuitesIndex.put(fullClassName, suites.size() - 1); + } else { + currentSuite = suites.get(currentSuiteIndex); } } - String timeAsString = attributes.getValue( "time" ); - Number time = isBlank( timeAsString ) ? 0 : numberFormat.parse( timeAsString ); + String timeAsString = attributes.getValue("time"); + Number time = isBlank(timeAsString) ? 0 : numberFormat.parse(timeAsString); - testCase.setFullClassName( currentSuite.getFullClassName() ) - .setClassName( currentSuite.getName() ) - .setFullName( currentSuite.getFullClassName() + "." + testCase.getName() ) - .setTime( time.floatValue() ); + testCase.setFullClassName(currentSuite.getFullClassName()) + .setClassName(currentSuite.getName()) + .setFullName(currentSuite.getFullClassName() + "." + testCase.getName()) + .setTime(time.floatValue()); - if ( currentSuite != defaultSuite ) - { - currentSuite.setTimeElapsed( testCase.getTime() + currentSuite.getTimeElapsed() ); + if (currentSuite != defaultSuite) { + currentSuite.setTimeElapsed(testCase.getTime() + currentSuite.getTimeElapsed()); } break; case "failure": - testCase.setFailure( attributes.getValue( "message" ), attributes.getValue( "type" ) ); + testCase.setFailure(attributes.getValue("message"), attributes.getValue("type")); currentSuite.incrementNumberOfFailures(); break; case "error": - testCase.setError( attributes.getValue( "message" ), attributes.getValue( "type" ) ); + testCase.setError(attributes.getValue("message"), attributes.getValue("type")); currentSuite.incrementNumberOfErrors(); break; case "skipped": - String message = attributes.getValue( "message" ); - testCase.setSkipped( message != null ? message : "skipped" ); + String message = attributes.getValue("message"); + testCase.setSkipped(message != null ? message : "skipped"); currentSuite.incrementNumberOfSkipped(); break; case "flakyFailure": @@ -206,10 +203,8 @@ public void startElement( String uri, String localName, String qName, Attributes default: break; } - } - catch ( ParseException e ) - { - throw new SAXException( e.getMessage(), e ); + } catch (ParseException e) { + throw new SAXException(e.getMessage(), e); } } } @@ -218,27 +213,22 @@ public void startElement( String uri, String localName, String qName, Attributes * {@inheritDoc} */ @Override - public void endElement( String uri, String localName, String qName ) - throws SAXException - { - switch ( qName ) - { + public void endElement(String uri, String localName, String qName) throws SAXException { + switch (qName) { case "testcase": - currentSuite.getTestCases().add( testCase ); + currentSuite.getTestCases().add(testCase); break; case "failure": case "error": - testCase.setFailureDetail( currentElement.toString() ) - .setFailureErrorLine( parseErrorLine( currentElement, testCase.getFullClassName() ) ); + testCase.setFailureDetail(currentElement.toString()) + .setFailureErrorLine(parseErrorLine(currentElement, testCase.getFullClassName())); break; case "time": - try - { - defaultSuite.setTimeElapsed( numberFormat.parse( currentElement.toString() ).floatValue() ); - } - catch ( ParseException e ) - { - throw new SAXException( e.getMessage(), e ); + try { + defaultSuite.setTimeElapsed( + numberFormat.parse(currentElement.toString()).floatValue()); + } catch (ParseException e) { + throw new SAXException(e.getMessage(), e); } break; default: @@ -251,32 +241,25 @@ public void endElement( String uri, String localName, String qName ) * {@inheritDoc} */ @Override - public void characters( char[] ch, int start, int length ) - { + public void characters(char[] ch, int start, int length) { assert start >= 0; assert length >= 0; - if ( valid && isNotBlank( start, length, ch ) ) - { - currentElement.append( ch, start, length ); + if (valid && isNotBlank(start, length, ch)) { + currentElement.append(ch, start, length); } } - public boolean isValid() - { + public boolean isValid() { return valid; } - static boolean isNotBlank( int from, int len, char... s ) - { + static boolean isNotBlank(int from, int len, char... s) { assert from >= 0; assert len >= 0; - if ( s != null ) - { - for ( int i = 0; i < len; i++ ) - { + if (s != null) { + for (int i = 0; i < len; i++) { char c = s[from++]; - if ( c != ' ' && c != '\t' && c != '\n' && c != '\r' && c != '\f' ) - { + if (c != ' ' && c != '\t' && c != '\n' && c != '\r' && c != '\f') { return true; } } @@ -284,56 +267,47 @@ static boolean isNotBlank( int from, int len, char... s ) return false; } - static boolean isNumeric( StringBuilder s, final int from, final int to ) - { + static boolean isNumeric(StringBuilder s, final int from, final int to) { assert from >= 0; assert from <= to; - for ( int i = from; i != to; ) - { - if ( !Character.isDigit( s.charAt( i++ ) ) ) - { + for (int i = from; i != to; ) { + if (!Character.isDigit(s.charAt(i++))) { return false; } } return from != to; } - static String parseErrorLine( StringBuilder currentElement, String fullClassName ) - { - final String[] linePatterns = { "at " + fullClassName + '.', "at " + fullClassName + '$' }; - int[] indexes = lastIndexOf( currentElement, linePatterns ); + static String parseErrorLine(StringBuilder currentElement, String fullClassName) { + final String[] linePatterns = {"at " + fullClassName + '.', "at " + fullClassName + '$'}; + int[] indexes = lastIndexOf(currentElement, linePatterns); int patternStartsAt = indexes[0]; - if ( patternStartsAt != -1 ) - { - int searchFrom = patternStartsAt + ( linePatterns[ indexes[1] ] ).length(); - searchFrom = 1 + currentElement.indexOf( ":", searchFrom ); - int searchTo = currentElement.indexOf( ")", searchFrom ); - return isNumeric( currentElement, searchFrom, searchTo ) - ? currentElement.substring( searchFrom, searchTo ) - : ""; + if (patternStartsAt != -1) { + int searchFrom = patternStartsAt + (linePatterns[indexes[1]]).length(); + searchFrom = 1 + currentElement.indexOf(":", searchFrom); + int searchTo = currentElement.indexOf(")", searchFrom); + return isNumeric(currentElement, searchFrom, searchTo) + ? currentElement.substring(searchFrom, searchTo) + : ""; } return ""; } - static int[] lastIndexOf( StringBuilder source, String... linePatterns ) - { - int end = source.indexOf( "Caused by:" ); - if ( end == -1 ) - { + static int[] lastIndexOf(StringBuilder source, String... linePatterns) { + int end = source.indexOf("Caused by:"); + if (end == -1) { end = source.length(); } int startsAt = -1; int pattern = -1; - for ( int i = 0; i < linePatterns.length; i++ ) - { + for (int i = 0; i < linePatterns.length; i++) { String linePattern = linePatterns[i]; - int currentStartsAt = source.lastIndexOf( linePattern, end ); - if ( currentStartsAt > startsAt ) - { + int currentStartsAt = source.lastIndexOf(linePattern, end); + if (currentStartsAt > startsAt) { startsAt = currentStartsAt; pattern = i; } } - return new int[] { startsAt, pattern }; + return new int[] {startsAt, pattern}; } } diff --git a/surefire-report-parser/src/test/java/org/apache/maven/plugins/surefire/report/JUnit4SuiteTest.java b/surefire-report-parser/src/test/java/org/apache/maven/plugins/surefire/report/JUnit4SuiteTest.java index 8c143dd284..bd88140b2c 100644 --- a/surefire-report-parser/src/test/java/org/apache/maven/plugins/surefire/report/JUnit4SuiteTest.java +++ b/surefire-report-parser/src/test/java/org/apache/maven/plugins/surefire/report/JUnit4SuiteTest.java @@ -1,3 +1,21 @@ +/* + * 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.maven.plugins.surefire.report; /* @@ -30,15 +48,13 @@ * @author Tibor Digana (tibor17) * @since 2.21.0 */ -public class JUnit4SuiteTest extends TestCase -{ - public static Test suite() - { +public class JUnit4SuiteTest extends TestCase { + public static Test suite() { TestSuite suite = new TestSuite(); - suite.addTestSuite( ReportTestCaseTest.class ); - suite.addTestSuite( ReportTestSuiteTest.class ); - suite.addTestSuite( SurefireReportParserTest.class ); - suite.addTest( new JUnit4TestAdapter( TestSuiteXmlParserTest.class ) ); + suite.addTestSuite(ReportTestCaseTest.class); + suite.addTestSuite(ReportTestSuiteTest.class); + suite.addTestSuite(SurefireReportParserTest.class); + suite.addTest(new JUnit4TestAdapter(TestSuiteXmlParserTest.class)); return suite; } } diff --git a/surefire-report-parser/src/test/java/org/apache/maven/plugins/surefire/report/ReportTestCaseTest.java b/surefire-report-parser/src/test/java/org/apache/maven/plugins/surefire/report/ReportTestCaseTest.java index 6ca030ed36..f80e7ae576 100644 --- a/surefire-report-parser/src/test/java/org/apache/maven/plugins/surefire/report/ReportTestCaseTest.java +++ b/surefire-report-parser/src/test/java/org/apache/maven/plugins/surefire/report/ReportTestCaseTest.java @@ -1,3 +1,21 @@ +/* + * 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.maven.plugins.surefire.report; /* @@ -24,50 +42,42 @@ /** * @author Jontri */ -@SuppressWarnings( "checkstyle:magicnumber" ) -public class ReportTestCaseTest - extends TestCase -{ +@SuppressWarnings("checkstyle:magicnumber") +public class ReportTestCaseTest extends TestCase { private ReportTestCase tCase; /** * {@inheritDoc} */ @Override - protected void setUp() - throws Exception - { + protected void setUp() throws Exception { super.setUp(); tCase = new ReportTestCase(); } - public void testSetName() - { - tCase.setName( "Test Case Name" ); + public void testSetName() { + tCase.setName("Test Case Name"); - assertEquals( "Test Case Name", tCase.getName() ); + assertEquals("Test Case Name", tCase.getName()); } - public void testSetTime() - { - tCase.setTime( .06f ); + public void testSetTime() { + tCase.setTime(.06f); - assertEquals( .06f, tCase.getTime(), 0.0 ); + assertEquals(.06f, tCase.getTime(), 0.0); } - public void testSetFailure() - { - tCase.setFailure( "messageVal", "typeVal" ); + public void testSetFailure() { + tCase.setFailure("messageVal", "typeVal"); - assertEquals( "messageVal", tCase.getFailureMessage() ); - assertEquals( "typeVal", tCase.getFailureType() ); + assertEquals("messageVal", tCase.getFailureMessage()); + assertEquals("typeVal", tCase.getFailureType()); } - public void testSetFullName() - { - tCase.setFullName( "Test Case Full Name" ); + public void testSetFullName() { + tCase.setFullName("Test Case Full Name"); - assertEquals( "Test Case Full Name", tCase.getFullName() ); + assertEquals("Test Case Full Name", tCase.getFullName()); } } diff --git a/surefire-report-parser/src/test/java/org/apache/maven/plugins/surefire/report/ReportTestSuiteTest.java b/surefire-report-parser/src/test/java/org/apache/maven/plugins/surefire/report/ReportTestSuiteTest.java index 8109da493e..d7c892398e 100644 --- a/surefire-report-parser/src/test/java/org/apache/maven/plugins/surefire/report/ReportTestSuiteTest.java +++ b/surefire-report-parser/src/test/java/org/apache/maven/plugins/surefire/report/ReportTestSuiteTest.java @@ -1,3 +1,21 @@ +/* + * 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.maven.plugins.surefire.report; /* @@ -27,82 +45,70 @@ /** * */ -@SuppressWarnings( "checkstyle:magicnumber" ) -public class ReportTestSuiteTest - extends TestCase -{ +@SuppressWarnings("checkstyle:magicnumber") +public class ReportTestSuiteTest extends TestCase { private ReportTestSuite tSuite; /** * {@inheritDoc} */ @Override - protected void setUp() - throws Exception - { + protected void setUp() throws Exception { super.setUp(); tSuite = new ReportTestSuite(); } - public void testSetTestCases() - { + public void testSetTestCases() { ReportTestCase tCase = new ReportTestCase(); List tCaseList = new ArrayList<>(); - tCaseList.add( tCase ); + tCaseList.add(tCase); - tSuite.setTestCases( tCaseList ); + tSuite.setTestCases(tCaseList); - assertEquals( tCase, tSuite.getTestCases().get( 0 ) ); + assertEquals(tCase, tSuite.getTestCases().get(0)); } - public void testSetNumberedOfErrors() - { - tSuite.setNumberOfErrors( 9 ); + public void testSetNumberedOfErrors() { + tSuite.setNumberOfErrors(9); - assertEquals( 9, tSuite.getNumberOfErrors() ); + assertEquals(9, tSuite.getNumberOfErrors()); } - public void testSetNumberOfFailures() - { - tSuite.setNumberOfFailures( 10 ); + public void testSetNumberOfFailures() { + tSuite.setNumberOfFailures(10); - assertEquals( 10, tSuite.getNumberOfFailures() ); + assertEquals(10, tSuite.getNumberOfFailures()); } - public void testSetNumberOfSkipped() - { - tSuite.setNumberOfSkipped( 5 ); + public void testSetNumberOfSkipped() { + tSuite.setNumberOfSkipped(5); - assertEquals( 5, tSuite.getNumberOfSkipped() ); + assertEquals(5, tSuite.getNumberOfSkipped()); } - public void testSetNumberOfTests() - { - tSuite.setNumberOfTests( 11 ); + public void testSetNumberOfTests() { + tSuite.setNumberOfTests(11); - assertEquals( 11, tSuite.getNumberOfTests() ); + assertEquals(11, tSuite.getNumberOfTests()); } - public void testSetName() - { - tSuite.setName( "Suite Name" ); + public void testSetName() { + tSuite.setName("Suite Name"); - assertEquals( "Suite Name", tSuite.getName() ); + assertEquals("Suite Name", tSuite.getName()); } - public void testSetPackageName() - { - tSuite.setPackageName( "Suite Package Name" ); + public void testSetPackageName() { + tSuite.setPackageName("Suite Package Name"); - assertEquals( "Suite Package Name", tSuite.getPackageName() ); + assertEquals("Suite Package Name", tSuite.getPackageName()); } - public void testSetTimeElapsed() - { - tSuite.setTimeElapsed( .06f ); + public void testSetTimeElapsed() { + tSuite.setTimeElapsed(.06f); - assertEquals( .06f, tSuite.getTimeElapsed(), 0.0 ); + assertEquals(.06f, tSuite.getTimeElapsed(), 0.0); } } diff --git a/surefire-report-parser/src/test/java/org/apache/maven/plugins/surefire/report/SurefireReportParserTest.java b/surefire-report-parser/src/test/java/org/apache/maven/plugins/surefire/report/SurefireReportParserTest.java index 8bc9f1c3bc..06a8af83b8 100644 --- a/surefire-report-parser/src/test/java/org/apache/maven/plugins/surefire/report/SurefireReportParserTest.java +++ b/surefire-report-parser/src/test/java/org/apache/maven/plugins/surefire/report/SurefireReportParserTest.java @@ -1,3 +1,21 @@ +/* + * 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.maven.plugins.surefire.report; /* @@ -28,9 +46,8 @@ import java.util.List; import java.util.Map; -import org.apache.maven.plugin.surefire.log.api.NullConsoleLogger; - import junit.framework.TestCase; +import org.apache.maven.plugin.surefire.log.api.NullConsoleLogger; import static java.util.Collections.singletonList; import static java.util.Locale.ENGLISH; @@ -38,124 +55,114 @@ /** * */ -@SuppressWarnings( "checkstyle:magicnumber" ) -public class SurefireReportParserTest - extends TestCase -{ - public void testParseXMLReportFiles() - throws Exception - { +@SuppressWarnings("checkstyle:magicnumber") +public class SurefireReportParserTest extends TestCase { + public void testParseXMLReportFiles() throws Exception { SurefireReportParser report = - new SurefireReportParser( singletonList( getTestDir() ), ENGLISH, new NullConsoleLogger() ); + new SurefireReportParser(singletonList(getTestDir()), ENGLISH, new NullConsoleLogger()); List suites = report.parseXMLReportFiles(); - assertEquals( 8, suites.size() ); + assertEquals(8, suites.size()); - for ( ReportTestSuite suite : suites ) - { - assertNotNull( suite.getName() + " was not correctly parsed", suite.getTestCases() ); - assertNotNull( suite.getName() ); - assertNotNull( suite.getPackageName() ); + for (ReportTestSuite suite : suites) { + assertNotNull(suite.getName() + " was not correctly parsed", suite.getTestCases()); + assertNotNull(suite.getName()); + assertNotNull(suite.getPackageName()); } } - private File getTestDir() - throws UnsupportedEncodingException - { - URL resource = getClass().getResource( "/test-reports" ); + private File getTestDir() throws UnsupportedEncodingException { + URL resource = getClass().getResource("/test-reports"); // URLDecoder.decode necessary for JDK 1.5+, where spaces are escaped to %20 - return new File( URLDecoder.decode( resource.getPath(), "UTF-8" ) ).getAbsoluteFile(); + return new File(URLDecoder.decode(resource.getPath(), "UTF-8")).getAbsoluteFile(); } - public void testGetSummary() - throws Exception - { + public void testGetSummary() throws Exception { ReportTestSuite tSuite1 = new ReportTestSuite() - .setNumberOfErrors( 10 ) - .setNumberOfFailures( 20 ) - .setNumberOfSkipped( 2 ) - .setTimeElapsed( 1.0f ) - .setNumberOfTests( 100 ); + .setNumberOfErrors(10) + .setNumberOfFailures(20) + .setNumberOfSkipped(2) + .setTimeElapsed(1.0f) + .setNumberOfTests(100); ReportTestSuite tSuite2 = new ReportTestSuite() - .setNumberOfErrors( 10 ) - .setNumberOfFailures( 20 ) - .setNumberOfSkipped( 2 ) - .setTimeElapsed( 1.0f ) - .setNumberOfTests( 100 ); + .setNumberOfErrors(10) + .setNumberOfFailures(20) + .setNumberOfSkipped(2) + .setTimeElapsed(1.0f) + .setNumberOfTests(100); List suites = new ArrayList<>(); - suites.add( tSuite1 ); + suites.add(tSuite1); - suites.add( tSuite2 ); + suites.add(tSuite2); - SurefireReportParser report = new SurefireReportParser( null, ENGLISH, new NullConsoleLogger() ); + SurefireReportParser report = new SurefireReportParser(null, ENGLISH, new NullConsoleLogger()); - Map testMap = report.getSummary( suites ); + Map testMap = report.getSummary(suites); - assertEquals( 20, Integer.parseInt( testMap.get( "totalErrors" ) ) ); + assertEquals(20, Integer.parseInt(testMap.get("totalErrors"))); - assertEquals( 40, Integer.parseInt( testMap.get( "totalFailures" ) ) ); + assertEquals(40, Integer.parseInt(testMap.get("totalFailures"))); - assertEquals( 200, Integer.parseInt( testMap.get( "totalTests" ) ) ); + assertEquals(200, Integer.parseInt(testMap.get("totalTests"))); - assertEquals( 4, Integer.parseInt( testMap.get( "totalSkipped" ) ) ); + assertEquals(4, Integer.parseInt(testMap.get("totalSkipped"))); NumberFormat numberFormat = report.getNumberFormat(); - assertEquals( 2.0f, numberFormat.parse( testMap.get( "totalElapsedTime" ) ).floatValue(), 0.0f ); + assertEquals(2.0f, numberFormat.parse(testMap.get("totalElapsedTime")).floatValue(), 0.0f); - assertEquals( 68.00f, numberFormat.parse( testMap.get( "totalPercentage" ) ).floatValue(), 0 ); + assertEquals(68.00f, numberFormat.parse(testMap.get("totalPercentage")).floatValue(), 0); } - public void testGetSuitesGroupByPackage() - { + public void testGetSuitesGroupByPackage() { ReportTestSuite tSuite1 = new ReportTestSuite(); ReportTestSuite tSuite2 = new ReportTestSuite(); ReportTestSuite tSuite3 = new ReportTestSuite(); - tSuite1.setPackageName( "Package1" ); + tSuite1.setPackageName("Package1"); - tSuite2.setPackageName( "Package1" ); + tSuite2.setPackageName("Package1"); - tSuite3.setPackageName( "Package2" ); + tSuite3.setPackageName("Package2"); List suites = new ArrayList<>(); - suites.add( tSuite1 ); + suites.add(tSuite1); - suites.add( tSuite2 ); + suites.add(tSuite2); - suites.add( tSuite3 ); + suites.add(tSuite3); - SurefireReportParser report = new SurefireReportParser( null, ENGLISH, new NullConsoleLogger() ); + SurefireReportParser report = new SurefireReportParser(null, ENGLISH, new NullConsoleLogger()); - Map> groupMap = report.getSuitesGroupByPackage( suites ); + Map> groupMap = report.getSuitesGroupByPackage(suites); - assertEquals( 2, groupMap.size() ); + assertEquals(2, groupMap.size()); - assertEquals( tSuite1, groupMap.get( "Package1" ).get( 0 ) ); + assertEquals(tSuite1, groupMap.get("Package1").get(0)); - assertEquals( tSuite2, groupMap.get( "Package1" ).get( 1 ) ); + assertEquals(tSuite2, groupMap.get("Package1").get(1)); - assertEquals( tSuite3, groupMap.get( "Package2" ).get( 0 ) ); + assertEquals(tSuite3, groupMap.get("Package2").get(0)); } - public void testComputePercentage() - throws Exception - { - SurefireReportParser report = new SurefireReportParser( null, ENGLISH, new NullConsoleLogger() ); + public void testComputePercentage() throws Exception { + SurefireReportParser report = new SurefireReportParser(null, ENGLISH, new NullConsoleLogger()); NumberFormat numberFormat = report.getNumberFormat(); - assertEquals( 70.00f, numberFormat.parse( report.computePercentage( 100, 20, 10, 0 ) ).floatValue(), 0 ); + assertEquals( + 70.00f, + numberFormat.parse(report.computePercentage(100, 20, 10, 0)).floatValue(), + 0); } - public void testGetFailureDetails() - { + public void testGetFailureDetails() { ReportTestSuite tSuite1 = new ReportTestSuite(); ReportTestSuite tSuite2 = new ReportTestSuite(); @@ -166,38 +173,38 @@ public void testGetFailureDetails() ReportTestCase tCase3 = new ReportTestCase(); - tCase1.setFailure( null, IllegalArgumentException.class.getName() ); + tCase1.setFailure(null, IllegalArgumentException.class.getName()); - tCase3.setFailure( "index: 0, size: 0", IndexOutOfBoundsException.class.getName() ); + tCase3.setFailure("index: 0, size: 0", IndexOutOfBoundsException.class.getName()); List tCases = new ArrayList<>(); List tCases2 = new ArrayList<>(); - tCases.add( tCase1 ); + tCases.add(tCase1); - tCases.add( tCase2 ); + tCases.add(tCase2); - tCases2.add( tCase3 ); + tCases2.add(tCase3); - tSuite1.setTestCases( tCases ); + tSuite1.setTestCases(tCases); - tSuite2.setTestCases( tCases2 ); + tSuite2.setTestCases(tCases2); List suites = new ArrayList<>(); - suites.add( tSuite1 ); + suites.add(tSuite1); - suites.add( tSuite2 ); + suites.add(tSuite2); - SurefireReportParser report = new SurefireReportParser( null, ENGLISH, new NullConsoleLogger() ); + SurefireReportParser report = new SurefireReportParser(null, ENGLISH, new NullConsoleLogger()); - List failures = report.getFailureDetails( suites ); + List failures = report.getFailureDetails(suites); - assertEquals( 2, failures.size() ); + assertEquals(2, failures.size()); - assertEquals( tCase1, failures.get( 0 ) ); + assertEquals(tCase1, failures.get(0)); - assertEquals( tCase3, failures.get( 1 ) ); + assertEquals(tCase3, failures.get(1)); } } diff --git a/surefire-report-parser/src/test/java/org/apache/maven/plugins/surefire/report/TestSuiteXmlParserTest.java b/surefire-report-parser/src/test/java/org/apache/maven/plugins/surefire/report/TestSuiteXmlParserTest.java index 9a7ada80df..6bedb2fab0 100644 --- a/surefire-report-parser/src/test/java/org/apache/maven/plugins/surefire/report/TestSuiteXmlParserTest.java +++ b/surefire-report-parser/src/test/java/org/apache/maven/plugins/surefire/report/TestSuiteXmlParserTest.java @@ -1,3 +1,21 @@ +/* + * 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.maven.plugins.surefire.report; /* @@ -33,22 +51,21 @@ import org.junit.Test; import static java.nio.charset.StandardCharsets.UTF_8; -import static org.junit.Assert.assertNotNull; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.empty; +import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.assertNull; import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; import static org.junit.Assume.assumeTrue; -import static org.hamcrest.Matchers.empty; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.MatcherAssert.assertThat; /** * @author Kristian Rosenvold */ -@SuppressWarnings( { "checkstyle:magicnumber", "checkstyle:linelength" } ) -public class TestSuiteXmlParserTest -{ +@SuppressWarnings({"checkstyle:magicnumber", "checkstyle:linelength"}) +public class TestSuiteXmlParserTest { private static final String[] LINE_PATTERNS = {"at org.apache.Test.", "at org.apache.Test$"}; private final Collection loggedErrors = new ArrayList<>(); @@ -56,83 +73,68 @@ public class TestSuiteXmlParserTest private ConsoleLogger consoleLogger; @Before - public void instantiateLogger() - { - consoleLogger = new ConsoleLogger() - { + public void instantiateLogger() { + consoleLogger = new ConsoleLogger() { @Override - public boolean isDebugEnabled() - { + public boolean isDebugEnabled() { return true; } @Override - public void debug( String message ) - { - } + public void debug(String message) {} @Override - public boolean isInfoEnabled() - { + public boolean isInfoEnabled() { return true; } @Override - public void info( String message ) - { - } + public void info(String message) {} @Override - public boolean isWarnEnabled() - { + public boolean isWarnEnabled() { return true; } @Override - public void warning( String message ) - { - loggedErrors.add( message ); + public void warning(String message) { + loggedErrors.add(message); } @Override - public boolean isErrorEnabled() - { + public boolean isErrorEnabled() { return true; } @Override - public void error( String message ) - { - loggedErrors.add( message ); + public void error(String message) { + loggedErrors.add(message); } @Override - public void error( String message, Throwable t ) - { - loggedErrors.add( message ); + public void error(String message, Throwable t) { + loggedErrors.add(message); } @Override - public void error( Throwable t ) - { - loggedErrors.add( t.getLocalizedMessage() ); + public void error(Throwable t) { + loggedErrors.add(t.getLocalizedMessage()); } }; } @After - public void verifyErrorFreeLogger() - { - assertThat( loggedErrors, is( empty() ) ); + public void verifyErrorFreeLogger() { + assertThat(loggedErrors, is(empty())); } @Test - public void testParse() throws Exception - { - TestSuiteXmlParser testSuiteXmlParser = new TestSuiteXmlParser( consoleLogger ); + public void testParse() throws Exception { + TestSuiteXmlParser testSuiteXmlParser = new TestSuiteXmlParser(consoleLogger); String xml = "\n" + "\n" - + " \n" + " \n" + + " \n" + + " \n" + " \n" + " \n" + " \n" @@ -160,230 +162,226 @@ public void testParse() throws Exception + "\n" + " \n" + ""; - InputStream byteArrayIs = new ByteArrayInputStream( xml.getBytes() ); - List parse = testSuiteXmlParser.parse( new InputStreamReader( byteArrayIs, UTF_8 ) ); - assertThat( parse.size(), is( 1 ) ); - ReportTestSuite report = parse.get( 0 ); - assertThat( report.getFullClassName(), is( "wellFormedXmlFailures.TestSurefire3" ) ); - assertThat( report.getName(), is( "TestSurefire3" ) ); - assertThat( report.getPackageName(), is( "wellFormedXmlFailures" ) ); - assertThat( report.getNumberOfTests(), is( 4 ) ); - assertThat( report.getNumberOfSkipped(), is( 0 ) ); - assertThat( report.getNumberOfErrors(), is( 0 ) ); - assertThat( report.getNumberOfFailures(), is( 4 ) ); - assertThat( report.getNumberOfFlakes(), is( 0 ) ); - assertThat( report.getTimeElapsed(), is( 0.005f ) ); - assertThat( report.getTestCases().size(), is( 4 ) ); + InputStream byteArrayIs = new ByteArrayInputStream(xml.getBytes()); + List parse = testSuiteXmlParser.parse(new InputStreamReader(byteArrayIs, UTF_8)); + assertThat(parse.size(), is(1)); + ReportTestSuite report = parse.get(0); + assertThat(report.getFullClassName(), is("wellFormedXmlFailures.TestSurefire3")); + assertThat(report.getName(), is("TestSurefire3")); + assertThat(report.getPackageName(), is("wellFormedXmlFailures")); + assertThat(report.getNumberOfTests(), is(4)); + assertThat(report.getNumberOfSkipped(), is(0)); + assertThat(report.getNumberOfErrors(), is(0)); + assertThat(report.getNumberOfFailures(), is(4)); + assertThat(report.getNumberOfFlakes(), is(0)); + assertThat(report.getTimeElapsed(), is(0.005f)); + assertThat(report.getTestCases().size(), is(4)); List tests = report.getTestCases(); - assertThat( tests.get( 0 ).getFullClassName(), is( "wellFormedXmlFailures.TestSurefire3" ) ); - assertThat( tests.get( 0 ).getName(), is( "testLower" ) ); - assertThat( tests.get( 0 ).getFailureDetail(), - is( "junit.framework.AssertionFailedError: <\n" + assertThat(tests.get(0).getFullClassName(), is("wellFormedXmlFailures.TestSurefire3")); + assertThat(tests.get(0).getName(), is("testLower")); + assertThat( + tests.get(0).getFailureDetail(), + is("junit.framework.AssertionFailedError: <\n" + "\tat junit.framework.Assert.fail(Assert.java:47)\n" - + "\tat wellFormedXmlFailures.TestSurefire3.testLower(TestSurefire3.java:30)\n" ) ); - assertThat( tests.get( 0 ).getClassName(), is( "TestSurefire3" ) ); - assertThat( tests.get( 0 ).getTime(), is( 0.005f ) ); - assertThat( tests.get( 0 ).getFailureErrorLine(), is( "30" ) ); - assertThat( tests.get( 0 ).getFailureMessage(), is( "<" ) ); - assertThat( tests.get( 0 ).getFullName(), is( "wellFormedXmlFailures.TestSurefire3.testLower" ) ); - assertThat( tests.get( 0 ).getFailureType(), is( "junit.framework.AssertionFailedError" ) ); - assertThat( tests.get( 0 ).hasError(), is( false ) ); - - assertThat( tests.get( 1 ).getFullClassName(), is( "wellFormedXmlFailures.TestSurefire3" ) ); - assertThat( tests.get( 1 ).getName(), is( "testU0000" ) ); - assertThat( tests.get( 1 ).getFailureDetail(), - is( "junit.framework.AssertionFailedError: \n" + "\tat junit.framework.Assert.fail(Assert.java:47)\n" - + "\tat wellFormedXmlFailures.TestSurefire3.testU0000(TestSurefire3.java:40)\n" ) ); - assertThat( tests.get( 1 ).getClassName(), is( "TestSurefire3" ) ); - assertThat( tests.get( 1 ).getTime(), is( 0f ) ); - assertThat( tests.get( 1 ).getFailureErrorLine(), is( "40" ) ); - assertThat( tests.get( 1 ).getFailureMessage(), is( "&0#;" ) ); - assertThat( tests.get( 1 ).getFullName(), is( "wellFormedXmlFailures.TestSurefire3.testU0000" ) ); - assertThat( tests.get( 1 ).getFailureType(), is( "junit.framework.AssertionFailedError" ) ); - assertThat( tests.get( 1 ).hasError(), is( false ) ); - - assertThat( tests.get( 2 ).getFullClassName(), is( "wellFormedXmlFailures.TestSurefire3" ) ); - assertThat( tests.get( 2 ).getName(), is( "testGreater" ) ); - assertThat( tests.get( 2 ).getFailureDetail(), - is( "junit.framework.AssertionFailedError: >\n" + "\tat junit.framework.Assert.fail(Assert.java:47)\n" - + "\tat wellFormedXmlFailures.TestSurefire3.testGreater(TestSurefire3.java:35)\n" ) ); - assertThat( tests.get( 2 ).getClassName(), is( "TestSurefire3" ) ); - assertThat( tests.get( 2 ).getTime(), is( 0f ) ); - assertThat( tests.get( 2 ).getFailureErrorLine(), is( "35" ) ); - assertThat( tests.get( 2 ).getFailureMessage(), is( ">" ) ); - assertThat( tests.get( 2 ).getFullName(), is( "wellFormedXmlFailures.TestSurefire3.testGreater" ) ); - assertThat( tests.get( 2 ).getFailureType(), is( "junit.framework.AssertionFailedError" ) ); - assertThat( tests.get( 2 ).hasError(), is( false ) ); - - assertThat( tests.get( 3 ).getFullClassName(), is( "wellFormedXmlFailures.TestSurefire3" ) ); - assertThat( tests.get( 3 ).getName(), is( "testQuote" ) ); - assertThat( tests.get( 3 ).getFailureDetail(), - is( "junit.framework.AssertionFailedError: \"\n" + "\tat junit.framework.Assert.fail(Assert.java:47)\n" - + "\tat wellFormedXmlFailures.TestSurefire3.testQuote(TestSurefire3.java:25)\n" ) ); - assertThat( tests.get( 3 ).getClassName(), is( "TestSurefire3" ) ); - assertThat( tests.get( 3 ).getTime(), is( 0f ) ); - assertThat( tests.get( 3 ).getFailureErrorLine(), is( "25" ) ); - assertThat( tests.get( 3 ).getFailureMessage(), is( "\"" ) ); - assertThat( tests.get( 3 ).getFullName(), is( "wellFormedXmlFailures.TestSurefire3.testQuote" ) ); - assertThat( tests.get( 3 ).getFailureType(), is( "junit.framework.AssertionFailedError" ) ); - assertThat( tests.get( 3 ).hasError(), is( false ) ); + + "\tat wellFormedXmlFailures.TestSurefire3.testLower(TestSurefire3.java:30)\n")); + assertThat(tests.get(0).getClassName(), is("TestSurefire3")); + assertThat(tests.get(0).getTime(), is(0.005f)); + assertThat(tests.get(0).getFailureErrorLine(), is("30")); + assertThat(tests.get(0).getFailureMessage(), is("<")); + assertThat(tests.get(0).getFullName(), is("wellFormedXmlFailures.TestSurefire3.testLower")); + assertThat(tests.get(0).getFailureType(), is("junit.framework.AssertionFailedError")); + assertThat(tests.get(0).hasError(), is(false)); + + assertThat(tests.get(1).getFullClassName(), is("wellFormedXmlFailures.TestSurefire3")); + assertThat(tests.get(1).getName(), is("testU0000")); + assertThat( + tests.get(1).getFailureDetail(), + is("junit.framework.AssertionFailedError: \n" + "\tat junit.framework.Assert.fail(Assert.java:47)\n" + + "\tat wellFormedXmlFailures.TestSurefire3.testU0000(TestSurefire3.java:40)\n")); + assertThat(tests.get(1).getClassName(), is("TestSurefire3")); + assertThat(tests.get(1).getTime(), is(0f)); + assertThat(tests.get(1).getFailureErrorLine(), is("40")); + assertThat(tests.get(1).getFailureMessage(), is("&0#;")); + assertThat(tests.get(1).getFullName(), is("wellFormedXmlFailures.TestSurefire3.testU0000")); + assertThat(tests.get(1).getFailureType(), is("junit.framework.AssertionFailedError")); + assertThat(tests.get(1).hasError(), is(false)); + + assertThat(tests.get(2).getFullClassName(), is("wellFormedXmlFailures.TestSurefire3")); + assertThat(tests.get(2).getName(), is("testGreater")); + assertThat( + tests.get(2).getFailureDetail(), + is("junit.framework.AssertionFailedError: >\n" + "\tat junit.framework.Assert.fail(Assert.java:47)\n" + + "\tat wellFormedXmlFailures.TestSurefire3.testGreater(TestSurefire3.java:35)\n")); + assertThat(tests.get(2).getClassName(), is("TestSurefire3")); + assertThat(tests.get(2).getTime(), is(0f)); + assertThat(tests.get(2).getFailureErrorLine(), is("35")); + assertThat(tests.get(2).getFailureMessage(), is(">")); + assertThat(tests.get(2).getFullName(), is("wellFormedXmlFailures.TestSurefire3.testGreater")); + assertThat(tests.get(2).getFailureType(), is("junit.framework.AssertionFailedError")); + assertThat(tests.get(2).hasError(), is(false)); + + assertThat(tests.get(3).getFullClassName(), is("wellFormedXmlFailures.TestSurefire3")); + assertThat(tests.get(3).getName(), is("testQuote")); + assertThat( + tests.get(3).getFailureDetail(), + is("junit.framework.AssertionFailedError: \"\n" + "\tat junit.framework.Assert.fail(Assert.java:47)\n" + + "\tat wellFormedXmlFailures.TestSurefire3.testQuote(TestSurefire3.java:25)\n")); + assertThat(tests.get(3).getClassName(), is("TestSurefire3")); + assertThat(tests.get(3).getTime(), is(0f)); + assertThat(tests.get(3).getFailureErrorLine(), is("25")); + assertThat(tests.get(3).getFailureMessage(), is("\"")); + assertThat(tests.get(3).getFullName(), is("wellFormedXmlFailures.TestSurefire3.testQuote")); + assertThat(tests.get(3).getFailureType(), is("junit.framework.AssertionFailedError")); + assertThat(tests.get(3).hasError(), is(false)); } @Test - public void testParser() throws Exception - { - TestSuiteXmlParser parser = new TestSuiteXmlParser( consoleLogger ); + public void testParser() throws Exception { + TestSuiteXmlParser parser = new TestSuiteXmlParser(consoleLogger); Collection oldResult = parser.parse( - "src/test/resources/fixture/testsuitexmlparser/TEST-org.apache.maven.surefire.test.FailingTest.xml" ); + "src/test/resources/fixture/testsuitexmlparser/TEST-org.apache.maven.surefire.test.FailingTest.xml"); - assertNotNull( oldResult ); + assertNotNull(oldResult); - assertEquals( 1, oldResult.size() ); + assertEquals(1, oldResult.size()); ReportTestSuite next = oldResult.iterator().next(); - assertEquals( 2, next.getNumberOfTests() ); + assertEquals(2, next.getNumberOfTests()); } @Test - public void successfulSurefireTestReport() throws Exception - { - TestSuiteXmlParser parser = new TestSuiteXmlParser( consoleLogger ); - File surefireReport = new File( "src/test/resources/junit-pathWithÜmlaut/TEST-umlautTest.BasicTest.xml" ); - assumeTrue( surefireReport.isFile() ); - Collection suites = parser.parse( surefireReport.getCanonicalPath() ); - assertNotNull( suites ); - assertEquals( 1, suites.size() ); + public void successfulSurefireTestReport() throws Exception { + TestSuiteXmlParser parser = new TestSuiteXmlParser(consoleLogger); + File surefireReport = new File("src/test/resources/junit-pathWithÜmlaut/TEST-umlautTest.BasicTest.xml"); + assumeTrue(surefireReport.isFile()); + Collection suites = parser.parse(surefireReport.getCanonicalPath()); + assertNotNull(suites); + assertEquals(1, suites.size()); ReportTestSuite suite = suites.iterator().next(); - assertThat( suite.getNumberOfTests(), is( 1 ) ); - assertEquals( 1, suite.getNumberOfTests() ); - assertEquals( 0, suite.getNumberOfFlakes() ); - assertEquals( 0, suite.getNumberOfFailures() ); - assertEquals( 0, suite.getNumberOfErrors() ); - assertEquals( 0, suite.getNumberOfSkipped() ); - assertThat( suite.getTimeElapsed(), is( 0.002f ) ); - assertThat( suite.getFullClassName(), is( "umlautTest.BasicTest" ) ); - assertThat( suite.getPackageName(), is( "umlautTest" ) ); - assertThat( suite.getName(), is( "BasicTest" ) ); + assertThat(suite.getNumberOfTests(), is(1)); + assertEquals(1, suite.getNumberOfTests()); + assertEquals(0, suite.getNumberOfFlakes()); + assertEquals(0, suite.getNumberOfFailures()); + assertEquals(0, suite.getNumberOfErrors()); + assertEquals(0, suite.getNumberOfSkipped()); + assertThat(suite.getTimeElapsed(), is(0.002f)); + assertThat(suite.getFullClassName(), is("umlautTest.BasicTest")); + assertThat(suite.getPackageName(), is("umlautTest")); + assertThat(suite.getName(), is("BasicTest")); ReportTestCase test = suite.getTestCases().iterator().next(); - assertTrue( test.isSuccessful() ); - assertNull( test.getFailureDetail() ); - assertNull( test.getFailureErrorLine() ); - assertNull( test.getFailureType() ); - assertThat( test.getTime(), is( 0.002f ) ); - assertThat( test.getFullClassName(), is( "umlautTest.BasicTest" ) ); - assertThat( test.getClassName(), is( "BasicTest" ) ); - assertThat( test.getName(), is( "testSetUp" ) ); - assertThat( test.getFullName(), is( "umlautTest.BasicTest.testSetUp" ) ); + assertTrue(test.isSuccessful()); + assertNull(test.getFailureDetail()); + assertNull(test.getFailureErrorLine()); + assertNull(test.getFailureType()); + assertThat(test.getTime(), is(0.002f)); + assertThat(test.getFullClassName(), is("umlautTest.BasicTest")); + assertThat(test.getClassName(), is("BasicTest")); + assertThat(test.getName(), is("testSetUp")); + assertThat(test.getFullName(), is("umlautTest.BasicTest.testSetUp")); } @Test - public void testParserHitsFailsafeSummary() throws Exception - { - TestSuiteXmlParser parser = new TestSuiteXmlParser( consoleLogger ); + public void testParserHitsFailsafeSummary() throws Exception { + TestSuiteXmlParser parser = new TestSuiteXmlParser(consoleLogger); - parser.parse( "src/test/resources/fixture/testsuitexmlparser/failsafe-summary.xml" ); + parser.parse("src/test/resources/fixture/testsuitexmlparser/failsafe-summary.xml"); - assertFalse( parser.isValid() ); + assertFalse(parser.isValid()); parser.parse( - "src/test/resources/fixture/testsuitexmlparser/TEST-org.apache.maven.surefire.test.FailingTest.xml" ); + "src/test/resources/fixture/testsuitexmlparser/TEST-org.apache.maven.surefire.test.FailingTest.xml"); - assertTrue( parser.isValid() ); + assertTrue(parser.isValid()); } @Test - public void lastIndexOfPatternOfOrdinalTest() - { - final StringBuilder stackTrace = new StringBuilder( - "\tat org.apache.Test.util(Test.java:60)\n" + "\tat org.apache.Test.test(Test.java:30)\n" - + "\tat com.sun.Impl.xyz(Impl.java:258)\n" ); - - int[] result = TestSuiteXmlParser.lastIndexOf( stackTrace, LINE_PATTERNS ); - assertThat( result[0], is( 40 ) ); - assertThat( result[1], is( 0 ) ); - String errorLine = TestSuiteXmlParser.parseErrorLine( stackTrace, "org.apache.Test" ); - assertThat( errorLine, is( "30" ) ); + public void lastIndexOfPatternOfOrdinalTest() { + final StringBuilder stackTrace = new StringBuilder("\tat org.apache.Test.util(Test.java:60)\n" + + "\tat org.apache.Test.test(Test.java:30)\n" + "\tat com.sun.Impl.xyz(Impl.java:258)\n"); + + int[] result = TestSuiteXmlParser.lastIndexOf(stackTrace, LINE_PATTERNS); + assertThat(result[0], is(40)); + assertThat(result[1], is(0)); + String errorLine = TestSuiteXmlParser.parseErrorLine(stackTrace, "org.apache.Test"); + assertThat(errorLine, is("30")); } @Test - public void lastIndexOfPatternOfOrdinalTestWithCause() - { + public void lastIndexOfPatternOfOrdinalTestWithCause() { final StringBuilder stackTrace = new StringBuilder( "\tat org.apache.Test.util(Test.java:60)\n" + "\tat org.apache.Test.test(Test.java:30)\n" + "\tat com.sun.Impl.xyz(Impl.java:258)\n" + "\tat Caused by: java.lang.IndexOutOfBoundsException\n" - + "\tat org.apache.Test.util(Test.java:70)\n" ); + + "\tat org.apache.Test.util(Test.java:70)\n"); - int[] result = TestSuiteXmlParser.lastIndexOf( stackTrace, LINE_PATTERNS ); - assertThat( result[0], is( 40 ) ); - assertThat( result[1], is( 0 ) ); - String errorLine = TestSuiteXmlParser.parseErrorLine( stackTrace, "org.apache.Test" ); - assertThat( errorLine, is( "30" ) ); + int[] result = TestSuiteXmlParser.lastIndexOf(stackTrace, LINE_PATTERNS); + assertThat(result[0], is(40)); + assertThat(result[1], is(0)); + String errorLine = TestSuiteXmlParser.parseErrorLine(stackTrace, "org.apache.Test"); + assertThat(errorLine, is("30")); } @Test - public void lastIndexOfPatternOfEnclosedTest() - { - final StringBuilder source = new StringBuilder( - "\tat org.apache.Test.util(Test.java:60)\n" - + "\tat org.apache.Test$Nested.test(Test.java:30)\n" - + "\tat com.sun.Impl.xyz(Impl.java:258)\n" ); - - int[] result = TestSuiteXmlParser.lastIndexOf( source, LINE_PATTERNS ); - assertThat( result[0], is( 40 ) ); - assertThat( result[1], is( 1 ) ); - String errorLine = TestSuiteXmlParser.parseErrorLine( source, "org.apache.Test$Nested" ); - assertThat( errorLine, is( "30" ) ); + public void lastIndexOfPatternOfEnclosedTest() { + final StringBuilder source = new StringBuilder("\tat org.apache.Test.util(Test.java:60)\n" + + "\tat org.apache.Test$Nested.test(Test.java:30)\n" + + "\tat com.sun.Impl.xyz(Impl.java:258)\n"); + + int[] result = TestSuiteXmlParser.lastIndexOf(source, LINE_PATTERNS); + assertThat(result[0], is(40)); + assertThat(result[1], is(1)); + String errorLine = TestSuiteXmlParser.parseErrorLine(source, "org.apache.Test$Nested"); + assertThat(errorLine, is("30")); } @Test - public void lastIndexOfPatternOfEnclosedTestWithCause() - { + public void lastIndexOfPatternOfEnclosedTestWithCause() { final StringBuilder source = new StringBuilder( "\tat org.apache.Test.util(Test.java:60)\n" + "\tat org.apache.Test$Nested.test(Test.java:30)\n" + "\tat com.sun.Impl.xyz(Impl.java:258)\n" + "\tat Caused by: java.lang.IndexOutOfBoundsException\n" - + "\tat org.apache.Test$Nested.util(Test.java:70)\n" ); + + "\tat org.apache.Test$Nested.util(Test.java:70)\n"); - int[] result = TestSuiteXmlParser.lastIndexOf( source, LINE_PATTERNS ); - assertThat( result[0], is( 40 ) ); - assertThat( result[1], is( 1 ) ); - String errorLine = TestSuiteXmlParser.parseErrorLine( source, "org.apache.Test$Nested" ); - assertThat( errorLine, is( "30" ) ); + int[] result = TestSuiteXmlParser.lastIndexOf(source, LINE_PATTERNS); + assertThat(result[0], is(40)); + assertThat(result[1], is(1)); + String errorLine = TestSuiteXmlParser.parseErrorLine(source, "org.apache.Test$Nested"); + assertThat(errorLine, is("30")); } @Test - public void shouldParserEverythingInOrdinalTest() throws Exception - { - TestSuiteXmlParser parser = new TestSuiteXmlParser( consoleLogger ); - List tests = parser.parse( - "src/test/resources/fixture/testsuitexmlparser/TEST-surefire.MyTest.xml" ); - assertTrue( parser.isValid() ); - assertThat( tests.size(), is( 1 ) ); - assertThat( tests.get( 0 ).getFullClassName(), is( "surefire.MyTest" ) ); - assertThat( tests.get( 0 ).getNumberOfErrors(), is( 1 ) ); - assertThat( tests.get( 0 ).getNumberOfFlakes(), is( 0 ) ); - assertThat( tests.get( 0 ).getNumberOfSkipped(), is( 0 ) ); - assertThat( tests.get( 0 ).getNumberOfFailures(), is( 0 ) ); - assertThat( tests.get( 0 ).getPackageName(), is( "surefire" ) ); - assertThat( tests.get( 0 ).getNumberOfTests(), is( 1 ) ); - assertThat( tests.get( 0 ).getTestCases().size(), is( 1 ) ); - assertFalse( tests.get( 0 ).getTestCases().get( 0 ).isSuccessful() ); - assertThat( tests.get( 0 ).getTestCases().get( 0 ).getFailureErrorLine(), is( "13" ) ); - assertThat( tests.get( 0 ).getTestCases().get( 0 ).getFailureType(), is( "java.lang.RuntimeException" ) ); - assertThat( tests.get( 0 ).getTestCases().get( 0 ).getFullClassName(), is( "surefire.MyTest" ) ); - assertThat( tests.get( 0 ).getTestCases().get( 0 ).getClassName(), is( "MyTest" ) ); - assertThat( tests.get( 0 ).getTestCases().get( 0 ).getName(), is( "test" ) ); - assertThat( tests.get( 0 ).getTestCases().get( 0 ).getFullName(), is( "surefire.MyTest.test" ) ); - assertThat( tests.get( 0 ).getTestCases().get( 0 ).getTime(), is( 0.1f ) ); - assertThat( tests.get( 0 ).getTestCases().get( 0 ).getFailureMessage(), is( "this is different message" ) ); - - assertThat( tests.get( 0 ).getTestCases().get( 0 ).getFailureDetail(), - is( "java.lang.RuntimeException: java.lang.IndexOutOfBoundsException\n" + public void shouldParserEverythingInOrdinalTest() throws Exception { + TestSuiteXmlParser parser = new TestSuiteXmlParser(consoleLogger); + List tests = + parser.parse("src/test/resources/fixture/testsuitexmlparser/TEST-surefire.MyTest.xml"); + assertTrue(parser.isValid()); + assertThat(tests.size(), is(1)); + assertThat(tests.get(0).getFullClassName(), is("surefire.MyTest")); + assertThat(tests.get(0).getNumberOfErrors(), is(1)); + assertThat(tests.get(0).getNumberOfFlakes(), is(0)); + assertThat(tests.get(0).getNumberOfSkipped(), is(0)); + assertThat(tests.get(0).getNumberOfFailures(), is(0)); + assertThat(tests.get(0).getPackageName(), is("surefire")); + assertThat(tests.get(0).getNumberOfTests(), is(1)); + assertThat(tests.get(0).getTestCases().size(), is(1)); + assertFalse(tests.get(0).getTestCases().get(0).isSuccessful()); + assertThat(tests.get(0).getTestCases().get(0).getFailureErrorLine(), is("13")); + assertThat(tests.get(0).getTestCases().get(0).getFailureType(), is("java.lang.RuntimeException")); + assertThat(tests.get(0).getTestCases().get(0).getFullClassName(), is("surefire.MyTest")); + assertThat(tests.get(0).getTestCases().get(0).getClassName(), is("MyTest")); + assertThat(tests.get(0).getTestCases().get(0).getName(), is("test")); + assertThat(tests.get(0).getTestCases().get(0).getFullName(), is("surefire.MyTest.test")); + assertThat(tests.get(0).getTestCases().get(0).getTime(), is(0.1f)); + assertThat(tests.get(0).getTestCases().get(0).getFailureMessage(), is("this is different message")); + + assertThat( + tests.get(0).getTestCases().get(0).getFailureDetail(), + is("java.lang.RuntimeException: java.lang.IndexOutOfBoundsException\n" + "\tat surefire.MyTest.rethrownDelegate(MyTest.java:24)\n" + "\tat surefire.MyTest.newRethrownDelegate(MyTest.java:17)\n" - + "\tat surefire.MyTest.test(MyTest.java:13)\n" + "\tat sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\n" + + "\tat surefire.MyTest.test(MyTest.java:13)\n" + + "\tat sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\n" + "\tat sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)\n" + "\tat sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)\n" + "\tat java.lang.reflect.Method.invoke(Method.java:606)\n" @@ -412,40 +410,39 @@ public void shouldParserEverythingInOrdinalTest() throws Exception + "\tat surefire.MyTest.access$100(MyTest.java:9)\n" + "\tat surefire.MyTest$Nested.run(MyTest.java:38)\n" + "\tat surefire.MyTest.delegate(MyTest.java:29)\n" - + "\tat surefire.MyTest.rethrownDelegate(MyTest.java:22)" ) ); - assertThat( tests.get( 0 ).getTestCases().get( 0 ).hasError(), is( true ) ); + + "\tat surefire.MyTest.rethrownDelegate(MyTest.java:22)")); + assertThat(tests.get(0).getTestCases().get(0).hasError(), is(true)); } @Test - public void shouldParserEverythingInEnclosedTest() throws Exception - { - TestSuiteXmlParser parser = new TestSuiteXmlParser( consoleLogger ); - List tests = parser.parse( - "src/test/resources/fixture/testsuitexmlparser/TEST-surefire.MyTest-enclosed.xml" ); - assertTrue( parser.isValid() ); - assertThat( tests.size(), is( 1 ) ); - assertThat( tests.get( 0 ).getFullClassName(), is( "surefire.MyTest$A" ) ); - assertThat( tests.get( 0 ).getNumberOfErrors(), is( 1 ) ); - assertThat( tests.get( 0 ).getNumberOfFlakes(), is( 0 ) ); - assertThat( tests.get( 0 ).getNumberOfSkipped(), is( 0 ) ); - assertThat( tests.get( 0 ).getNumberOfFailures(), is( 0 ) ); - assertThat( tests.get( 0 ).getPackageName(), is( "surefire" ) ); - assertThat( tests.get( 0 ).getNumberOfTests(), is( 1 ) ); - assertThat( tests.get( 0 ).getTestCases().size(), is( 1 ) ); - assertFalse( tests.get( 0 ).getTestCases().get( 0 ).isSuccessful() ); - assertThat( tests.get( 0 ).getTestCases().get( 0 ).getFailureErrorLine(), is( "45" ) ); - assertThat( tests.get( 0 ).getTestCases().get( 0 ).getFailureType(), is( "java.lang.RuntimeException" ) ); - assertThat( tests.get( 0 ).getTestCases().get( 0 ).getFullClassName(), is( "surefire.MyTest$A" ) ); - assertThat( tests.get( 0 ).getTestCases().get( 0 ).getClassName(), is( "MyTest$A" ) ); - assertThat( tests.get( 0 ).getTestCases().get( 0 ).getName(), is( "t" ) ); - assertThat( tests.get( 0 ).getTestCases().get( 0 ).getFullName(), is( "surefire.MyTest$A.t" ) ); - assertThat( tests.get( 0 ).getTestCases().get( 0 ).getTime(), is( 0f ) ); - - assertThat( tests.get( 0 ).getTestCases().get( 0 ).getFailureMessage(), - is( "java.lang.IndexOutOfBoundsException" ) ); - - assertThat( tests.get( 0 ).getTestCases().get( 0 ).getFailureDetail(), - is( "java.lang.RuntimeException: java.lang.IndexOutOfBoundsException\n" + public void shouldParserEverythingInEnclosedTest() throws Exception { + TestSuiteXmlParser parser = new TestSuiteXmlParser(consoleLogger); + List tests = + parser.parse("src/test/resources/fixture/testsuitexmlparser/TEST-surefire.MyTest-enclosed.xml"); + assertTrue(parser.isValid()); + assertThat(tests.size(), is(1)); + assertThat(tests.get(0).getFullClassName(), is("surefire.MyTest$A")); + assertThat(tests.get(0).getNumberOfErrors(), is(1)); + assertThat(tests.get(0).getNumberOfFlakes(), is(0)); + assertThat(tests.get(0).getNumberOfSkipped(), is(0)); + assertThat(tests.get(0).getNumberOfFailures(), is(0)); + assertThat(tests.get(0).getPackageName(), is("surefire")); + assertThat(tests.get(0).getNumberOfTests(), is(1)); + assertThat(tests.get(0).getTestCases().size(), is(1)); + assertFalse(tests.get(0).getTestCases().get(0).isSuccessful()); + assertThat(tests.get(0).getTestCases().get(0).getFailureErrorLine(), is("45")); + assertThat(tests.get(0).getTestCases().get(0).getFailureType(), is("java.lang.RuntimeException")); + assertThat(tests.get(0).getTestCases().get(0).getFullClassName(), is("surefire.MyTest$A")); + assertThat(tests.get(0).getTestCases().get(0).getClassName(), is("MyTest$A")); + assertThat(tests.get(0).getTestCases().get(0).getName(), is("t")); + assertThat(tests.get(0).getTestCases().get(0).getFullName(), is("surefire.MyTest$A.t")); + assertThat(tests.get(0).getTestCases().get(0).getTime(), is(0f)); + + assertThat(tests.get(0).getTestCases().get(0).getFailureMessage(), is("java.lang.IndexOutOfBoundsException")); + + assertThat( + tests.get(0).getTestCases().get(0).getFailureDetail(), + is("java.lang.RuntimeException: java.lang.IndexOutOfBoundsException\n" + "\tat surefire.MyTest.rethrownDelegate(MyTest.java:24)\n" + "\tat surefire.MyTest.newRethrownDelegate(MyTest.java:17)\n" + "\tat surefire.MyTest.access$200(MyTest.java:9)\n" @@ -487,40 +484,39 @@ public void shouldParserEverythingInEnclosedTest() throws Exception + "\tat surefire.MyTest.access$100(MyTest.java:9)\n" + "\tat surefire.MyTest$Nested.run(MyTest.java:38)\n" + "\tat surefire.MyTest.delegate(MyTest.java:29)\n" - + "\tat surefire.MyTest.rethrownDelegate(MyTest.java:22)\n" ) ); - assertThat( tests.get( 0 ).getTestCases().get( 0 ).hasError(), is( true ) ); + + "\tat surefire.MyTest.rethrownDelegate(MyTest.java:22)\n")); + assertThat(tests.get(0).getTestCases().get(0).hasError(), is(true)); } @Test - public void shouldParserEverythingInEnclosedTrimStackTraceTest() throws Exception - { - TestSuiteXmlParser parser = new TestSuiteXmlParser( consoleLogger ); + public void shouldParserEverythingInEnclosedTrimStackTraceTest() throws Exception { + TestSuiteXmlParser parser = new TestSuiteXmlParser(consoleLogger); List tests = parser.parse( - "src/test/resources/fixture/testsuitexmlparser/TEST-surefire.MyTest-enclosed-trimStackTrace.xml" ); - assertTrue( parser.isValid() ); - assertThat( tests.size(), is( 1 ) ); - assertThat( tests.get( 0 ).getFullClassName(), is( "surefire.MyTest$A" ) ); - assertThat( tests.get( 0 ).getNumberOfErrors(), is( 1 ) ); - assertThat( tests.get( 0 ).getNumberOfFlakes(), is( 0 ) ); - assertThat( tests.get( 0 ).getNumberOfSkipped(), is( 0 ) ); - assertThat( tests.get( 0 ).getNumberOfFailures(), is( 0 ) ); - assertThat( tests.get( 0 ).getPackageName(), is( "surefire" ) ); - assertThat( tests.get( 0 ).getNumberOfTests(), is( 1 ) ); - assertThat( tests.get( 0 ).getTestCases().size(), is( 1 ) ); - assertFalse( tests.get( 0 ).getTestCases().get( 0 ).isSuccessful() ); - assertThat( tests.get( 0 ).getTestCases().get( 0 ).getFailureErrorLine(), is( "45" ) ); - assertThat( tests.get( 0 ).getTestCases().get( 0 ).getFailureType(), is( "java.lang.RuntimeException" ) ); - assertThat( tests.get( 0 ).getTestCases().get( 0 ).getFullClassName(), is( "surefire.MyTest$A" ) ); - assertThat( tests.get( 0 ).getTestCases().get( 0 ).getClassName(), is( "MyTest$A" ) ); - assertThat( tests.get( 0 ).getTestCases().get( 0 ).getName(), is( "t" ) ); - assertThat( tests.get( 0 ).getTestCases().get( 0 ).getFullName(), is( "surefire.MyTest$A.t" ) ); - assertThat( tests.get( 0 ).getTestCases().get( 0 ).getTime(), is( 0f ) ); - - assertThat( tests.get( 0 ).getTestCases().get( 0 ).getFailureMessage(), - is( "java.lang.IndexOutOfBoundsException" ) ); - - assertThat( tests.get( 0 ).getTestCases().get( 0 ).getFailureDetail(), - is( "java.lang.RuntimeException: java.lang.IndexOutOfBoundsException\n" + "src/test/resources/fixture/testsuitexmlparser/TEST-surefire.MyTest-enclosed-trimStackTrace.xml"); + assertTrue(parser.isValid()); + assertThat(tests.size(), is(1)); + assertThat(tests.get(0).getFullClassName(), is("surefire.MyTest$A")); + assertThat(tests.get(0).getNumberOfErrors(), is(1)); + assertThat(tests.get(0).getNumberOfFlakes(), is(0)); + assertThat(tests.get(0).getNumberOfSkipped(), is(0)); + assertThat(tests.get(0).getNumberOfFailures(), is(0)); + assertThat(tests.get(0).getPackageName(), is("surefire")); + assertThat(tests.get(0).getNumberOfTests(), is(1)); + assertThat(tests.get(0).getTestCases().size(), is(1)); + assertFalse(tests.get(0).getTestCases().get(0).isSuccessful()); + assertThat(tests.get(0).getTestCases().get(0).getFailureErrorLine(), is("45")); + assertThat(tests.get(0).getTestCases().get(0).getFailureType(), is("java.lang.RuntimeException")); + assertThat(tests.get(0).getTestCases().get(0).getFullClassName(), is("surefire.MyTest$A")); + assertThat(tests.get(0).getTestCases().get(0).getClassName(), is("MyTest$A")); + assertThat(tests.get(0).getTestCases().get(0).getName(), is("t")); + assertThat(tests.get(0).getTestCases().get(0).getFullName(), is("surefire.MyTest$A.t")); + assertThat(tests.get(0).getTestCases().get(0).getTime(), is(0f)); + + assertThat(tests.get(0).getTestCases().get(0).getFailureMessage(), is("java.lang.IndexOutOfBoundsException")); + + assertThat( + tests.get(0).getTestCases().get(0).getFailureDetail(), + is("java.lang.RuntimeException: java.lang.IndexOutOfBoundsException\n" + "\tat surefire.MyTest.failure(MyTest.java:33)\n" + "\tat surefire.MyTest.access$100(MyTest.java:9)\n" + "\tat surefire.MyTest$Nested.run(MyTest.java:38)\n" @@ -528,40 +524,39 @@ public void shouldParserEverythingInEnclosedTrimStackTraceTest() throws Exceptio + "\tat surefire.MyTest.rethrownDelegate(MyTest.java:22)\n" + "\tat surefire.MyTest.newRethrownDelegate(MyTest.java:17)\n" + "\tat surefire.MyTest.access$200(MyTest.java:9)\n" - + "\tat surefire.MyTest$A.t(MyTest.java:45)\n" ) ); - assertThat( tests.get( 0 ).getTestCases().get( 0 ).hasError(), is( true ) ); + + "\tat surefire.MyTest$A.t(MyTest.java:45)\n")); + assertThat(tests.get(0).getTestCases().get(0).hasError(), is(true)); } @Test - public void shouldParserEverythingInNestedClassTest() throws Exception - { - TestSuiteXmlParser parser = new TestSuiteXmlParser( consoleLogger ); - List tests = parser.parse( - "src/test/resources/fixture/testsuitexmlparser/TEST-surefire.MyTest-nestedClass.xml" ); - assertTrue( parser.isValid() ); - assertThat( tests.size(), is( 1 ) ); - assertThat( tests.get( 0 ).getFullClassName(), is( "surefire.MyTest" ) ); - assertThat( tests.get( 0 ).getNumberOfErrors(), is( 1 ) ); - assertThat( tests.get( 0 ).getNumberOfFlakes(), is( 0 ) ); - assertThat( tests.get( 0 ).getNumberOfSkipped(), is( 0 ) ); - assertThat( tests.get( 0 ).getNumberOfFailures(), is( 0 ) ); - assertThat( tests.get( 0 ).getPackageName(), is( "surefire" ) ); - assertThat( tests.get( 0 ).getNumberOfTests(), is( 1 ) ); - assertThat( tests.get( 0 ).getTestCases().size(), is( 1 ) ); - assertFalse( tests.get( 0 ).getTestCases().get( 0 ).isSuccessful() ); - assertThat( tests.get( 0 ).getTestCases().get( 0 ).getFailureErrorLine(), is( "13" ) ); - assertThat( tests.get( 0 ).getTestCases().get( 0 ).getFailureType(), is( "java.lang.RuntimeException" ) ); - assertThat( tests.get( 0 ).getTestCases().get( 0 ).getFullClassName(), is( "surefire.MyTest" ) ); - assertThat( tests.get( 0 ).getTestCases().get( 0 ).getClassName(), is( "MyTest" ) ); - assertThat( tests.get( 0 ).getTestCases().get( 0 ).getName(), is( "test" ) ); - assertThat( tests.get( 0 ).getTestCases().get( 0 ).getFullName(), is( "surefire.MyTest.test" ) ); - assertThat( tests.get( 0 ).getTestCases().get( 0 ).getTime(), is( 0f ) ); - - assertThat( tests.get( 0 ).getTestCases().get( 0 ).getFailureMessage(), - is( "java.lang.IndexOutOfBoundsException" ) ); - - assertThat( tests.get( 0 ).getTestCases().get( 0 ).getFailureDetail(), - is( "java.lang.RuntimeException: java.lang.IndexOutOfBoundsException\n" + public void shouldParserEverythingInNestedClassTest() throws Exception { + TestSuiteXmlParser parser = new TestSuiteXmlParser(consoleLogger); + List tests = + parser.parse("src/test/resources/fixture/testsuitexmlparser/TEST-surefire.MyTest-nestedClass.xml"); + assertTrue(parser.isValid()); + assertThat(tests.size(), is(1)); + assertThat(tests.get(0).getFullClassName(), is("surefire.MyTest")); + assertThat(tests.get(0).getNumberOfErrors(), is(1)); + assertThat(tests.get(0).getNumberOfFlakes(), is(0)); + assertThat(tests.get(0).getNumberOfSkipped(), is(0)); + assertThat(tests.get(0).getNumberOfFailures(), is(0)); + assertThat(tests.get(0).getPackageName(), is("surefire")); + assertThat(tests.get(0).getNumberOfTests(), is(1)); + assertThat(tests.get(0).getTestCases().size(), is(1)); + assertFalse(tests.get(0).getTestCases().get(0).isSuccessful()); + assertThat(tests.get(0).getTestCases().get(0).getFailureErrorLine(), is("13")); + assertThat(tests.get(0).getTestCases().get(0).getFailureType(), is("java.lang.RuntimeException")); + assertThat(tests.get(0).getTestCases().get(0).getFullClassName(), is("surefire.MyTest")); + assertThat(tests.get(0).getTestCases().get(0).getClassName(), is("MyTest")); + assertThat(tests.get(0).getTestCases().get(0).getName(), is("test")); + assertThat(tests.get(0).getTestCases().get(0).getFullName(), is("surefire.MyTest.test")); + assertThat(tests.get(0).getTestCases().get(0).getTime(), is(0f)); + + assertThat(tests.get(0).getTestCases().get(0).getFailureMessage(), is("java.lang.IndexOutOfBoundsException")); + + assertThat( + tests.get(0).getTestCases().get(0).getFailureDetail(), + is("java.lang.RuntimeException: java.lang.IndexOutOfBoundsException\n" + "\tat surefire.MyTest.rethrownDelegate(MyTest.java:24)\n" + "\tat surefire.MyTest.newRethrownDelegate(MyTest.java:17)\n" + "\tat surefire.MyTest.test(MyTest.java:13)\n" @@ -594,40 +589,39 @@ public void shouldParserEverythingInNestedClassTest() throws Exception + "\tat surefire.MyTest.access$100(MyTest.java:9)\n" + "\tat surefire.MyTest$Nested.run(MyTest.java:38)\n" + "\tat surefire.MyTest.delegate(MyTest.java:29)\n" - + "\tat surefire.MyTest.rethrownDelegate(MyTest.java:22)" ) ); - assertThat( tests.get( 0 ).getTestCases().get( 0 ).hasError(), is( true ) ); + + "\tat surefire.MyTest.rethrownDelegate(MyTest.java:22)")); + assertThat(tests.get(0).getTestCases().get(0).hasError(), is(true)); } @Test - public void shouldParserEverythingInNestedClassTrimStackTraceTest() throws Exception - { - TestSuiteXmlParser parser = new TestSuiteXmlParser( consoleLogger ); + public void shouldParserEverythingInNestedClassTrimStackTraceTest() throws Exception { + TestSuiteXmlParser parser = new TestSuiteXmlParser(consoleLogger); List tests = parser.parse( - "src/test/resources/fixture/testsuitexmlparser/TEST-surefire.MyTest-nestedClass-trimStackTrace.xml" ); - assertTrue( parser.isValid() ); - assertThat( tests.size(), is( 1 ) ); - assertThat( tests.get( 0 ).getFullClassName(), is( "surefire.MyTest" ) ); - assertThat( tests.get( 0 ).getNumberOfErrors(), is( 1 ) ); - assertThat( tests.get( 0 ).getNumberOfFlakes(), is( 0 ) ); - assertThat( tests.get( 0 ).getNumberOfSkipped(), is( 0 ) ); - assertThat( tests.get( 0 ).getNumberOfFailures(), is( 0 ) ); - assertThat( tests.get( 0 ).getPackageName(), is( "surefire" ) ); - assertThat( tests.get( 0 ).getNumberOfTests(), is( 1 ) ); - assertThat( tests.get( 0 ).getTestCases().size(), is( 1 ) ); - assertFalse( tests.get( 0 ).getTestCases().get( 0 ).isSuccessful() ); - assertThat( tests.get( 0 ).getTestCases().get( 0 ).getFailureErrorLine(), is( "13" ) ); - assertThat( tests.get( 0 ).getTestCases().get( 0 ).getFailureType(), is( "java.lang.RuntimeException" ) ); - assertThat( tests.get( 0 ).getTestCases().get( 0 ).getFullClassName(), is( "surefire.MyTest" ) ); - assertThat( tests.get( 0 ).getTestCases().get( 0 ).getClassName(), is( "MyTest" ) ); - assertThat( tests.get( 0 ).getTestCases().get( 0 ).getName(), is( "test" ) ); - assertThat( tests.get( 0 ).getTestCases().get( 0 ).getFullName(), is( "surefire.MyTest.test" ) ); - assertThat( tests.get( 0 ).getTestCases().get( 0 ).getTime(), is( 0f ) ); - - assertThat( tests.get( 0 ).getTestCases().get( 0 ).getFailureMessage(), - is( "java.lang.IndexOutOfBoundsException" ) ); - - assertThat( tests.get( 0 ).getTestCases().get( 0 ).getFailureDetail(), - is( "java.lang.RuntimeException: java.lang.IndexOutOfBoundsException\n" + "src/test/resources/fixture/testsuitexmlparser/TEST-surefire.MyTest-nestedClass-trimStackTrace.xml"); + assertTrue(parser.isValid()); + assertThat(tests.size(), is(1)); + assertThat(tests.get(0).getFullClassName(), is("surefire.MyTest")); + assertThat(tests.get(0).getNumberOfErrors(), is(1)); + assertThat(tests.get(0).getNumberOfFlakes(), is(0)); + assertThat(tests.get(0).getNumberOfSkipped(), is(0)); + assertThat(tests.get(0).getNumberOfFailures(), is(0)); + assertThat(tests.get(0).getPackageName(), is("surefire")); + assertThat(tests.get(0).getNumberOfTests(), is(1)); + assertThat(tests.get(0).getTestCases().size(), is(1)); + assertFalse(tests.get(0).getTestCases().get(0).isSuccessful()); + assertThat(tests.get(0).getTestCases().get(0).getFailureErrorLine(), is("13")); + assertThat(tests.get(0).getTestCases().get(0).getFailureType(), is("java.lang.RuntimeException")); + assertThat(tests.get(0).getTestCases().get(0).getFullClassName(), is("surefire.MyTest")); + assertThat(tests.get(0).getTestCases().get(0).getClassName(), is("MyTest")); + assertThat(tests.get(0).getTestCases().get(0).getName(), is("test")); + assertThat(tests.get(0).getTestCases().get(0).getFullName(), is("surefire.MyTest.test")); + assertThat(tests.get(0).getTestCases().get(0).getTime(), is(0f)); + + assertThat(tests.get(0).getTestCases().get(0).getFailureMessage(), is("java.lang.IndexOutOfBoundsException")); + + assertThat( + tests.get(0).getTestCases().get(0).getFailureDetail(), + is("java.lang.RuntimeException: java.lang.IndexOutOfBoundsException\n" + "\tat surefire.MyTest.rethrownDelegate(MyTest.java:24)\n" + "\tat surefire.MyTest.newRethrownDelegate(MyTest.java:17)\n" + "\tat surefire.MyTest.test(MyTest.java:13)\n" @@ -636,27 +630,25 @@ public void shouldParserEverythingInNestedClassTrimStackTraceTest() throws Excep + "\tat surefire.MyTest.access$100(MyTest.java:9)\n" + "\tat surefire.MyTest$Nested.run(MyTest.java:38)\n" + "\tat surefire.MyTest.delegate(MyTest.java:29)\n" - + "\tat surefire.MyTest.rethrownDelegate(MyTest.java:22)" ) ); - assertThat( tests.get( 0 ).getTestCases().get( 0 ).hasError(), is( true ) ); + + "\tat surefire.MyTest.rethrownDelegate(MyTest.java:22)")); + assertThat(tests.get(0).getTestCases().get(0).hasError(), is(true)); } @Test - public void shouldTestNotBlank() - { - assertFalse( TestSuiteXmlParser.isNotBlank( 1, 2, ' ', ' ', ' ', '\n' ) ); - assertFalse( TestSuiteXmlParser.isNotBlank( 1, 2, ' ', '\t', ' ', '\n' ) ); - assertFalse( TestSuiteXmlParser.isNotBlank( 1, 2, ' ', ' ', '\r', '\n' ) ); - assertFalse( TestSuiteXmlParser.isNotBlank( 1, 2, ' ', ' ', '\f', '\n' ) ); - assertTrue( TestSuiteXmlParser.isNotBlank( 1, 2, ' ', 'a', ' ', '\n' ) ); - assertTrue( TestSuiteXmlParser.isNotBlank( 1, 2, ' ', ' ', 'a', '\n' ) ); - assertTrue( TestSuiteXmlParser.isNotBlank( 1, 2, ' ', 'a', 'b', '\n' ) ); + public void shouldTestNotBlank() { + assertFalse(TestSuiteXmlParser.isNotBlank(1, 2, ' ', ' ', ' ', '\n')); + assertFalse(TestSuiteXmlParser.isNotBlank(1, 2, ' ', '\t', ' ', '\n')); + assertFalse(TestSuiteXmlParser.isNotBlank(1, 2, ' ', ' ', '\r', '\n')); + assertFalse(TestSuiteXmlParser.isNotBlank(1, 2, ' ', ' ', '\f', '\n')); + assertTrue(TestSuiteXmlParser.isNotBlank(1, 2, ' ', 'a', ' ', '\n')); + assertTrue(TestSuiteXmlParser.isNotBlank(1, 2, ' ', ' ', 'a', '\n')); + assertTrue(TestSuiteXmlParser.isNotBlank(1, 2, ' ', 'a', 'b', '\n')); } @Test - public void shouldTestIsNumeric() - { - assertFalse( TestSuiteXmlParser.isNumeric( new StringBuilder( "0?5142" ), 1, 3 ) ); - assertTrue( TestSuiteXmlParser.isNumeric( new StringBuilder( "0?51M2" ), 2, 4 ) ); - assertFalse( TestSuiteXmlParser.isNumeric( new StringBuilder( "0?51M2" ), 2, 5 ) ); + public void shouldTestIsNumeric() { + assertFalse(TestSuiteXmlParser.isNumeric(new StringBuilder("0?5142"), 1, 3)); + assertTrue(TestSuiteXmlParser.isNumeric(new StringBuilder("0?51M2"), 2, 4)); + assertFalse(TestSuiteXmlParser.isNumeric(new StringBuilder("0?51M2"), 2, 5)); } } diff --git a/surefire-shadefire/pom.xml b/surefire-shadefire/pom.xml index debb6773b3..77627bef72 100644 --- a/surefire-shadefire/pom.xml +++ b/surefire-shadefire/pom.xml @@ -1,3 +1,4 @@ + - 4.0.0 @@ -31,8 +31,7 @@ ShadeFire JUnit3 Provider A super-shaded junit3 provider that is used by surefire to build itself, that basically has ALL classes relocated to facilitate no API-conflict whatsoever with ourself. - The only remaining point of conflict is around the booter properties file format. - + The only remaining point of conflict is around the booter properties file format. @@ -66,10 +65,10 @@ maven-shade-plugin - package shade + package diff --git a/surefire-shared-utils/pom.xml b/surefire-shared-utils/pom.xml index d5d912a23f..342eeecd94 100644 --- a/surefire-shared-utils/pom.xml +++ b/surefire-shared-utils/pom.xml @@ -17,112 +17,109 @@ ~ specific language governing permissions and limitations ~ under the License. --> - - 4.0.0 + 4.0.0 - - org.apache.maven.surefire - surefire - 3.0.0-M10-SNAPSHOT - + + org.apache.maven.surefire + surefire + 3.0.0-M10-SNAPSHOT + - surefire-shared-utils - Surefire Shared Utils - - Relocated Java packages of maven-shared-utils and several Apache Commons utilities in Surefire. - + surefire-shared-utils + Surefire Shared Utils + Relocated Java packages of maven-shared-utils and several Apache Commons utilities in Surefire. - - - The Apache Software License, Version 2.0 - http://www.apache.org/licenses/LICENSE-2.0.txt - repo - - + + + The Apache Software License, Version 2.0 + http://www.apache.org/licenses/LICENSE-2.0.txt + repo + + - - - org.apache.maven.shared - maven-shared-utils - - - commons-io - commons-io - - - org.apache.commons - commons-lang3 - - - org.apache.commons - commons-compress - - + + + org.apache.maven.shared + maven-shared-utils + + + commons-io + commons-io + + + org.apache.commons + commons-lang3 + + + org.apache.commons + commons-compress + + - - - - maven-shade-plugin - - - - shade - - - - - org.apache.maven.shared.utils - org.apache.maven.surefire.shared.utils - - - org.apache.commons.io - org.apache.maven.surefire.shared.io - - - org.apache.commons.lang3 - org.apache.maven.surefire.shared.lang3 - - - org.apache.commons.compress - org.apache.maven.surefire.shared.compress - - - - - - - - - - - - ide-development - - - - maven-install-plugin - - - install-devel-jar - install - - install-file - - - surefire-shared-utils - 3-SNAPSHOT - target/${project.build.finalName}.jar - - - - - - - - + ide-development + + + + maven-install-plugin + + + install-devel-jar + + install-file + + install + + surefire-shared-utils + 3-SNAPSHOT + target/${project.build.finalName}.jar + + + + + + + +